1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 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 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
23 package com.att.nsa.dmaapMMAgent;
25 import java.io.BufferedReader;
26 import java.io.DataOutputStream;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.io.OutputStream;
34 import java.net.HttpURLConnection;
36 import java.util.ArrayList;
37 import java.util.Properties;
39 import org.apache.log4j.Logger;
40 import org.jasypt.util.text.BasicTextEncryptor;
42 import com.att.nsa.dmaapMMAgent.dao.CreateMirrorMaker;
43 import com.att.nsa.dmaapMMAgent.dao.DeleteMirrorMaker;
44 import com.att.nsa.dmaapMMAgent.dao.ListMirrorMaker;
45 import com.att.nsa.dmaapMMAgent.dao.MirrorMaker;
46 import com.att.nsa.dmaapMMAgent.dao.UpdateMirrorMaker;
47 import com.att.nsa.dmaapMMAgent.dao.UpdateWhiteList;
48 import com.att.nsa.dmaapMMAgent.utils.MirrorMakerProcessHandler;
49 import com.google.gson.Gson;
50 import com.google.gson.internal.LinkedTreeMap;
51 import com.sun.org.apache.xerces.internal.impl.dtd.models.CMAny;
52 import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
54 public class MirrorMakerAgent {
55 static final Logger logger = Logger.getLogger(MirrorMakerAgent.class);
56 Properties mirrorMakerProperties = new Properties();
57 ListMirrorMaker mirrorMakers = null;
58 String mmagenthome = "";
59 String kafkahome = "";
61 String topicname = "";
64 private static String secret = "utdfpWlgyDQ2ZB8SLVRtmN834I1JcT9J";
66 public static void main(String[] args) {
67 if (args != null && args.length == 2) {
68 if (args[0].equals("-encrypt")) {
69 BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
70 textEncryptor.setPassword(secret);
71 String plainText = textEncryptor.encrypt(args[1]);
72 System.out.println("Encrypted Password is :" + plainText);
75 } else if (args != null && args.length > 0) {
77 "Usage: ./mmagent to run with the configuration \n -encrypt <password> to Encrypt Password for config ");
80 MirrorMakerAgent agent = new MirrorMakerAgent();
81 if (agent.checkStartup()) {
82 logger.info("mmagent started, loading properties");
83 agent.checkAgentProcess();
84 agent.readAgentTopic();
87 "ERROR: mmagent startup unsuccessful, please make sure the mmagenthome /etc/mmagent.config is set and mechid have the rights to the topic");
91 private boolean checkStartup() {
92 FileInputStream input = null;
94 this.mmagenthome = System.getProperty("MMAGENTHOME");
95 input = new FileInputStream(mmagenthome + "/etc/mmagent.config");
96 logger.info("mmagenthome is set :" + mmagenthome + " loading properties at /etc/mmagent.config");
97 } catch (IOException ex) {
98 logger.error(mmagenthome + "/etc/mmagent.config not found. Set -DMMAGENTHOME and check the config file" + ex);
104 } catch (IOException e) {
105 logger.error(" IOException occers " + e);
112 /*input = new FileInputStream(kafkahome + "/bin/kafka-run-class.sh");*/
114 throw new IOException();
116 logger.info("kakahome is set :" + kafkahome);
117 } catch (IOException ex) {
118 logger.error(kafkahome + "/bin/kafka-run-class.sh not found. Make sure kafka home is set correctly" + ex);
124 } catch (IOException e) {
125 logger.error("IOException" + e);
129 String response = publishTopic("{\"test\":\"test\"}");
130 if (response.startsWith("ERROR:")) {
131 logger.error("Problem publishing to topic, please verify the config " + this.topicname + " MR URL is:"
132 + this.topicURL + " Error is: " + response);
135 logger.info("Published to Topic :" + this.topicname + " Successfully");
136 response = subscribeTopic("1");
137 if (response != null && response.startsWith("ERROR:")) {
138 logger.error("Problem subscribing to topic, please verify the config " + this.topicname + " MR URL is:"
139 + this.topicURL + " Error is: " + response);
142 logger.info("Subscribed to Topic :" + this.topicname + " Successfully");
146 private void checkPropertiesFile(String agentName, String propName, String info, boolean refresh) {
147 InputStream input = null;
148 OutputStream out = null;
151 throw new IOException();
153 input = new FileInputStream(mmagenthome + "/etc/" + agentName + propName + ".properties");
154 } catch (IOException ex) {
155 logger.error(" IOException will be handled " + ex);
157 input = new FileInputStream(mmagenthome + "/etc/" + propName + ".properties");
158 Properties prop = new Properties();
160 if (propName.equals("consumer")) {
161 prop.setProperty("group.id", agentName);
162 prop.setProperty("zookeeper.connect", info);
164 prop.setProperty("metadata.broker.list", info);
166 out = new FileOutputStream(mmagenthome + "/etc/" + agentName + propName + ".properties");
169 } catch (Exception e) {
170 logger.error("Exception at checkPropertiesFile " +e);
176 } catch (IOException e) {
183 } catch (IOException e) {
185 logger.error("IOException" + e);
191 private void checkAgentProcess() {
192 logger.info("Checking MirrorMaker Process");
193 if (mirrorMakers != null) {
194 int mirrorMakersCount = mirrorMakers.getListMirrorMaker().size();
195 for (int i = 0; i < mirrorMakersCount; i++) {
196 MirrorMaker mm = mirrorMakers.getListMirrorMaker().get(i);
197 if (MirrorMakerProcessHandler.checkMirrorMakerProcess(mm.name) == false) {
198 checkPropertiesFile(mm.name, "consumer", mm.consumer, false);
199 checkPropertiesFile(mm.name, "producer", mm.producer, false);
201 if (mm.whitelist != null && !mm.whitelist.equals("")) {
202 logger.info("MirrorMaker " + mm.name + " is not running, restarting. Check Logs for more Details");
203 MirrorMakerProcessHandler.startMirrorMaker(this.mmagenthome, this.kafkahome, mm.name,
204 mmagenthome + "/etc/" + mm.name + "consumer.properties",
205 mmagenthome + "/etc/" + mm.name + "producer.properties", mm.whitelist);
206 mm.setStatus("RESTARTING");
209 logger.info("MirrorMaker " + mm.name + " is STOPPED");
210 mm.setStatus("STOPPED");
214 } catch (InterruptedException e) {
215 Thread.currentThread().interrupt();
217 mirrorMakers.getListMirrorMaker().set(i, mm);
219 logger.info("MirrorMaker " + mm.name + " is running");
220 mm.setStatus("RUNNING");
221 mirrorMakers.getListMirrorMaker().set(i, mm);
225 // Gson g = new Gson();
226 // System.out.println(g.toJson(mirrorMakers));
229 private String subscribeTopic(String timeout) {
230 String response = "";
232 String requestURL = this.topicURL + "/events/" + this.topicname + "/mirrormakeragent/1?timeout=" + timeout
234 String authString = this.mechid + ":" + this.password;
235 String authStringEnc = Base64.encode(authString.getBytes());
236 URL url = new URL(requestURL);
237 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
238 connection.setRequestMethod("GET");
239 connection.setDoOutput(true);
240 connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
241 connection.setRequestProperty("Content-Type", "application/json");
242 InputStream content = (InputStream) connection.getInputStream();
243 BufferedReader in = new BufferedReader(new InputStreamReader(content));
246 while ((line = in.readLine()) != null) {
247 response = response + line;
250 // get message as JSON String Array
251 String[] topicMessage = g.fromJson(response, String[].class);
252 if (topicMessage.length != 0) {
253 return topicMessage[0];
255 } catch (Exception e) {
256 logger.error(" Exception Occered " + e);
257 return "ERROR:" + e.getMessage() + " Server Response is:" + response;
262 private String publishTopic(String message) {
264 String requestURL = this.topicURL + "/events/" + this.topicname;
265 String authString = this.mechid + ":" + this.password;
266 String authStringEnc = Base64.encode(authString.getBytes());
267 URL url = new URL(requestURL);
268 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
269 connection.setRequestMethod("POST");
270 connection.setDoOutput(true);
271 connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
272 connection.setRequestProperty("Content-Type", "application/json");
273 connection.setRequestProperty("Content-Length", Integer.toString(message.length()));
274 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
275 wr.write(message.getBytes());
277 InputStream content = (InputStream) connection.getInputStream();
278 BufferedReader in = new BufferedReader(new InputStreamReader(content));
280 String response = "";
281 while ((line = in.readLine()) != null) {
282 response = response + line;
286 } catch (Exception e) {
287 return "ERROR:" + e.getLocalizedMessage();
291 private void readAgentTopic() {
293 int connectionattempt = 0;
295 logger.info("--------------------------------");
296 logger.info("Waiting for Messages for 60 secs");
297 String topicMessage = subscribeTopic("60000");
299 LinkedTreeMap<?, ?> object = null;
300 if (topicMessage != null) {
302 object = g.fromJson(topicMessage, LinkedTreeMap.class);
304 // Cast the 1st item (since limit=1 and see the type of
306 if (object.get("createMirrorMaker") != null) {
307 logger.info("Received createMirrorMaker request from topic");
308 CreateMirrorMaker m = g.fromJson(topicMessage, CreateMirrorMaker.class);
309 createMirrorMaker(m.getCreateMirrorMaker());
311 mirrorMakers.setMessageID(m.getMessageID());
312 publishTopic(g.toJson(mirrorMakers));
313 mirrorMakers.setMessageID("");
314 } else if (object.get("updateMirrorMaker") != null) {
315 logger.info("Received updateMirrorMaker request from topic");
316 UpdateMirrorMaker m = g.fromJson(topicMessage, UpdateMirrorMaker.class);
317 updateMirrorMaker(m.getUpdateMirrorMaker());
319 mirrorMakers.setMessageID(m.getMessageID());
320 publishTopic(g.toJson(mirrorMakers));
321 mirrorMakers.setMessageID("");
322 } else if (object.get("deleteMirrorMaker") != null) {
323 logger.info("Received deleteMirrorMaker request from topic");
324 DeleteMirrorMaker m = g.fromJson(topicMessage, DeleteMirrorMaker.class);
325 deleteMirrorMaker(m.getDeleteMirrorMaker());
327 mirrorMakers.setMessageID(m.getMessageID());
328 publishTopic(g.toJson(mirrorMakers));
329 mirrorMakers.setMessageID("");
330 } else if (object.get("listAllMirrorMaker") != null) {
331 logger.info("Received listALLMirrorMaker request from topic");
333 mirrorMakers.setMessageID((String) object.get("messageID"));
334 publishTopic(g.toJson(mirrorMakers));
335 mirrorMakers.setMessageID("");
336 } else if (object.get("updateWhiteList") != null) {
337 logger.info("Received updateWhiteList request from topic");
338 UpdateWhiteList m = g.fromJson(topicMessage, UpdateWhiteList.class);
339 updateWhiteList(m.getUpdateWhiteList());
341 mirrorMakers.setMessageID(m.getMessageID());
342 publishTopic(g.toJson(mirrorMakers));
343 mirrorMakers.setMessageID("");
344 } else if (object.get("listMirrorMaker") != null) {
345 logger.info("Received listMirrorMaker from topic, skipping messages");
347 logger.info("Received unknown request from topic");
349 } catch (Exception ex) {
351 if (connectionattempt > 5) {
352 logger.info("Can't connect to the topic, mmagent shutting down , " + topicMessage);
355 logger.info("Can't connect to the topic, " + topicMessage + " Retrying " + connectionattempt
356 + " of 5 times in 1 minute" + " Error:" + ex.getLocalizedMessage());
360 // Check all MirrorMaker every min
361 connectionattempt = 0;
366 } catch (Exception e) {
372 protected void createMirrorMaker(MirrorMaker newMirrorMaker) {
373 boolean exists = false;
374 if (mirrorMakers != null) {
375 int mirrorMakersCount = mirrorMakers.getListMirrorMaker().size();
376 for (int i = 0; i < mirrorMakersCount; i++) {
377 MirrorMaker mm = mirrorMakers.getListMirrorMaker().get(i);
378 if (mm.name.equals(newMirrorMaker.name)) {
380 logger.info("MirrorMaker already exist for:" + newMirrorMaker.name);
385 logger.info("Adding new MirrorMaker:" + newMirrorMaker.name);
386 if (exists == false && mirrorMakers != null) {
387 mirrorMakers.getListMirrorMaker().add(newMirrorMaker);
388 } else if (exists == false && mirrorMakers == null) {
389 mirrorMakers = new ListMirrorMaker();
390 ArrayList<MirrorMaker> list = mirrorMakers.getListMirrorMaker();
391 list = new ArrayList<MirrorMaker>();
392 list.add(newMirrorMaker);
393 mirrorMakers.setListMirrorMaker(list);
395 checkPropertiesFile(newMirrorMaker.name, "consumer", newMirrorMaker.consumer, true);
396 checkPropertiesFile(newMirrorMaker.name, "producer", newMirrorMaker.producer, true);
399 mirrorMakerProperties.setProperty("mirrormakers", g.toJson(this.mirrorMakers));
400 OutputStream out = null;
402 out = new FileOutputStream(mmagenthome + "/etc/mmagent.config");
403 mirrorMakerProperties.store(out, "");
404 } catch (IOException ex) {
405 ex.printStackTrace();
410 } catch (IOException e) {
417 private void updateMirrorMaker(MirrorMaker newMirrorMaker) {
418 boolean exists = false;
419 if (mirrorMakers != null) {
420 int mirrorMakersCount = mirrorMakers.getListMirrorMaker().size();
421 for (int i = 0; i < mirrorMakersCount; i++) {
422 MirrorMaker mm = mirrorMakers.getListMirrorMaker().get(i);
423 if (mm.name.equals(newMirrorMaker.name)) {
425 mm.setConsumer(newMirrorMaker.getConsumer());
426 mm.setProducer(newMirrorMaker.getProducer());
427 mirrorMakers.getListMirrorMaker().set(i, mm);
428 logger.info("Updating MirrorMaker:" + newMirrorMaker.name);
433 checkPropertiesFile(newMirrorMaker.name, "consumer", newMirrorMaker.consumer, true);
434 checkPropertiesFile(newMirrorMaker.name, "producer", newMirrorMaker.producer, true);
437 mirrorMakerProperties.setProperty("mirrormakers", g.toJson(this.mirrorMakers));
438 OutputStream out = null;
440 out = new FileOutputStream(mmagenthome + "/etc/mmagent.config");
441 mirrorMakerProperties.store(out, "");
442 MirrorMakerProcessHandler.stopMirrorMaker(newMirrorMaker.name);
445 } catch (InterruptedException e) {
447 } catch (IOException ex) {
448 ex.printStackTrace();
453 } catch (IOException e) {
459 logger.info("MirrorMaker Not found for:" + newMirrorMaker.name);
463 private void updateWhiteList(MirrorMaker newMirrorMaker) {
464 boolean exists = false;
465 if (mirrorMakers != null) {
466 int mirrorMakersCount = mirrorMakers.getListMirrorMaker().size();
467 for (int i = 0; i < mirrorMakersCount; i++) {
468 MirrorMaker mm = mirrorMakers.getListMirrorMaker().get(i);
469 if (mm.name.equals(newMirrorMaker.name)) {
471 mm.setWhitelist(newMirrorMaker.whitelist);
472 mirrorMakers.getListMirrorMaker().set(i, mm);
473 logger.info("Updating MirrorMaker WhiteList:" + newMirrorMaker.name + " WhiteList:"
474 + newMirrorMaker.whitelist);
480 mirrorMakerProperties.setProperty("mirrormakers", g.toJson(this.mirrorMakers));
481 OutputStream out = null;
483 out = new FileOutputStream(mmagenthome + "/etc/mmagent.config");
484 mirrorMakerProperties.store(out, "");
485 MirrorMakerProcessHandler.stopMirrorMaker(newMirrorMaker.name);
488 } catch (InterruptedException e) {
490 } catch (IOException ex) {
491 ex.printStackTrace();
496 } catch (IOException e) {
498 logger.error("IOException occered " + e);
503 logger.info("MirrorMaker Not found for:" + newMirrorMaker.name);
507 private void deleteMirrorMaker(MirrorMaker newMirrorMaker) {
508 boolean exists = false;
509 if (mirrorMakers != null) {
510 int mirrorMakersCount = mirrorMakers.getListMirrorMaker().size();
511 for (int i = 0; i < mirrorMakersCount; i++) {
512 MirrorMaker mm = mirrorMakers.getListMirrorMaker().get(i);
513 if (mm.name.equals(newMirrorMaker.name)) {
515 mirrorMakers.getListMirrorMaker().remove(i);
516 logger.info("Removing MirrorMaker:" + newMirrorMaker.name);
517 i = mirrorMakersCount;
523 String path = mmagenthome + "/etc/" + newMirrorMaker.name + "consumer" + ".properties";
524 File file = new File(path);
526 } catch (Exception ex) {
529 String path = mmagenthome + "/etc/" + newMirrorMaker.name + "producer" + ".properties";
530 File file = new File(path);
532 } catch (Exception ex) {
535 mirrorMakerProperties.setProperty("mirrormakers", g.toJson(this.mirrorMakers));
536 OutputStream out = null;
538 out = new FileOutputStream(mmagenthome + "/etc/mmagent.config");
539 mirrorMakerProperties.store(out, "");
540 MirrorMakerProcessHandler.stopMirrorMaker(newMirrorMaker.name);
541 } catch (IOException ex) {
542 ex.printStackTrace();
547 } catch (IOException e) {
553 logger.info("MirrorMaker Not found for:" + newMirrorMaker.name);
557 private void loadProperties() {
558 InputStream input = null;
561 input = new FileInputStream(mmagenthome + "/etc/mmagent.config");
562 mirrorMakerProperties.load(input);
564 if (mirrorMakerProperties.getProperty("mirrormakers") == null) {
565 this.mirrorMakers = new ListMirrorMaker();
566 ArrayList<MirrorMaker> list = this.mirrorMakers.getListMirrorMaker();
567 list = new ArrayList<MirrorMaker>();
568 this.mirrorMakers.setListMirrorMaker(list);
570 this.mirrorMakers = g.fromJson(mirrorMakerProperties.getProperty("mirrormakers"),
571 ListMirrorMaker.class);
574 this.kafkahome = mirrorMakerProperties.getProperty("kafkahome");
575 this.topicURL = mirrorMakerProperties.getProperty("topicURL");
576 this.topicname = mirrorMakerProperties.getProperty("topicname");
577 this.mechid = mirrorMakerProperties.getProperty("mechid");
579 BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
580 textEncryptor.setPassword(secret);
581 //this.password = textEncryptor.decrypt(mirrorMakerProperties.getProperty("password"));
582 this.password = mirrorMakerProperties.getProperty("password");
583 } catch (IOException ex) {
584 // ex.printStackTrace();
589 } catch (IOException e) {
590 // e.printStackTrace();