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