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