b32e888281072ddfb6bbf120f8cb748331fba895
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / util / AAIRSyncUtility.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
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 /**
22  * 
23  */
24 package org.openecomp.aai.util;
25
26 import java.io.BufferedReader;
27 import java.io.InputStreamReader;
28 import java.net.InetAddress;
29 import java.net.UnknownHostException;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.StringTokenizer;
33
34 import org.openecomp.aai.exceptions.AAIException;
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37
38
39 public class AAIRSyncUtility {
40
41         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIRSyncUtility.class);    
42         private final String DEFAULT_CHECK = new String("aai.primary.filetransfer.");
43         
44         /**
45          * Instantiates a new AAIR sync utility.
46          */
47         public AAIRSyncUtility() {
48
49         }
50
51         /**
52          * Do command.
53          *
54          * @param command the command
55          * @return the int
56          * @throws Exception the exception
57          */
58         public int doCommand(List<String> command)  
59                           throws Exception 
60         { 
61                 String s = null; 
62                               
63                 ProcessBuilder pb = new ProcessBuilder(command); 
64                 Process process = pb.start(); 
65                           
66                 BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
67                 BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); 
68                           
69                 LOGGER.debug("Here is the standard output of the command:\n"); 
70                 while ((s = stdInput.readLine()) != null) 
71                 { 
72                         LOGGER.debug(s);
73                 } 
74                           
75                 LOGGER.debug("Here is the standard error of the command (if any):\n"); 
76                 while ((s = stdError.readLine()) != null) 
77                 { 
78                         LOGGER.debug(s);
79                 } 
80                 return process.waitFor();
81         } 
82                             
83
84         /**
85          * Method sendRsyncCommand.
86          *
87          * @param transId the trans id
88          * @param fileName the file name
89          */
90         public void sendRsyncCommand(String transId, String fileName) 
91         {
92                 String aaiServerList = null;
93                 String rsyncOptionsList = null;
94                 
95                 try {
96                         aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist");
97                         rsyncOptionsList = AAIConfig.get("aai.rsync.options.list");
98                         String enableRsync = AAIConfig.get("aai.rsync.enabled");
99                         
100                         if (!AAIConfig.isEmpty(enableRsync) && "n".equalsIgnoreCase(enableRsync)){
101                         LOGGER.info("rsync not invoked for " + fileName + ": rsync is not enabled in aaiconfig.properties");
102                                 return;
103                         }
104                 } catch ( Exception e ) {
105                 LOGGER.warn( "rsync not invoked: missing aaiconfig.properties entries for rsync" );
106                 }
107                 
108                 LOGGER.info("rsync to copy files started....");
109                 
110         ArrayList<String> remoteHostList = new ArrayList<String>();
111         StringTokenizer serverList = new StringTokenizer( aaiServerList, "|" );
112         String host = null;
113                 try {
114                         host = getHost();
115                         String remoteConnString = null;
116                          
117                         remoteHostList = getRemoteHostList(serverList, host);
118                         LOGGER.debug("This host:" + host);
119                 String pickUpDirectory = AAIConfig.get("instar.pickup.dir");
120                 String user = AAIConfig.get("aai.rsync.remote.user"); 
121                 String rsyncCmd = AAIConfig.get("aai.rsync.command");
122                 
123                 //Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
124                 
125                 java.util.Iterator<String> remoteHostItr = remoteHostList.iterator();
126                 while (!remoteHostList.isEmpty() && remoteHostItr.hasNext()) {
127                         String remoteHost = remoteHostItr.next();
128                         remoteConnString =user+"@"+remoteHost+":"+pickUpDirectory;
129                                    
130                                 List<String> commands = new ArrayList<String>(); 
131                             commands.add(rsyncCmd); 
132                             StringTokenizer optionTks = new StringTokenizer( rsyncOptionsList, "|" );
133                             while (optionTks.hasMoreTokens()){
134                                 commands.add(optionTks.nextToken());
135                             }
136                             commands.add(fileName); // src directory/fileName
137                             commands.add(remoteConnString); // target username/host/path
138                             LOGGER.debug("Commands: " + commands.toString());
139                             int rsyncResult = doCommand(commands);
140                             if ( rsyncResult == 0 ) {
141                                 LOGGER.info("rsync completed for "+remoteHost);
142                             }else {
143                                         LOGGER.error("rsync failed for "+ remoteHost+ " with response code "+rsyncResult );
144                                 }
145                         } 
146         } catch ( Exception e) {
147                 LOGGER.error("no server found processing serverList for host " + host + ": " + e.getMessage() + " (AAI_4000)");
148                 }
149         }
150
151         /**
152          * Gets the remote host list.
153          *
154          * @param serverList the server list
155          * @param host the host
156          * @return the remote host list
157          */
158         private ArrayList<String> getRemoteHostList(StringTokenizer serverList, String host) {
159                 ArrayList<String> remoteHostList = new ArrayList<String>();
160                 String remoteHost = null;
161                 while ( serverList.hasMoreTokens() ) {
162                 remoteHost = serverList.nextToken();
163                 if (!host.equalsIgnoreCase(remoteHost)){
164                         remoteHostList.add(remoteHost);
165                 }
166                 }
167                 return remoteHostList;
168         }
169
170         /**
171          * Gets the host.
172          *
173          * @return the host
174          * @throws AAIException the AAI exception
175          */
176         private String getHost() throws AAIException {
177                 String aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist");
178                 String hostname = null;
179                 try {
180                         InetAddress ip = InetAddress.getLocalHost();
181                 if ( ip != null ) {
182                         hostname = ip.getHostName();
183                         if ( hostname != null ) {
184                                 if  ( !( aaiServerList.contains(hostname) ) )
185                                         LOGGER.warn("Host name not found in server list " + hostname);
186                         } else
187                                 LOGGER.warn("InetAddress returned null hostname");
188                 } 
189                  
190                 } catch (UnknownHostException e) {
191                         LOGGER.warn("InetAddress getLocalHost exception " + e.getMessage());
192         }
193         
194                 return hostname;
195         }
196         
197 }