d51ec6008a6c81a47627cf5e47fb2dc7f4f12474
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / Batch.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 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 package org.onap.aaf.auth.batch;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PrintStream;
30 import java.lang.reflect.Constructor;
31 import java.net.InetAddress;
32 import java.net.URL;
33 import java.net.UnknownHostException;
34 import java.nio.ByteBuffer;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.Date;
38 import java.util.GregorianCalendar;
39 import java.util.HashSet;
40 import java.util.List;
41 import java.util.Set;
42 import java.util.TimeZone;
43
44 import org.apache.log4j.Logger;
45 import org.onap.aaf.auth.common.Define;
46 import org.onap.aaf.auth.dao.CassAccess;
47 import org.onap.aaf.auth.env.AuthzEnv;
48 import org.onap.aaf.auth.env.AuthzTrans;
49 import org.onap.aaf.auth.log4j.Log4JAccessAppender;
50 import org.onap.aaf.auth.org.Organization;
51 import org.onap.aaf.auth.org.OrganizationException;
52 import org.onap.aaf.auth.org.OrganizationFactory;
53 import org.onap.aaf.cadi.Access.Level;
54 import org.onap.aaf.cadi.PropAccess;
55 import org.onap.aaf.cadi.config.Config;
56 import org.onap.aaf.misc.env.APIException;
57 import org.onap.aaf.misc.env.Env;
58 import org.onap.aaf.misc.env.StaticSlot;
59 import org.onap.aaf.misc.env.TimeTaken;
60 import org.onap.aaf.misc.env.util.Chrono;
61 import org.onap.aaf.misc.env.util.Split;
62 import org.onap.aaf.misc.env.util.StringBuilderOutputStream;
63
64 import com.datastax.driver.core.Cluster;
65 import com.datastax.driver.core.ResultSet;
66 import com.datastax.driver.core.Row;
67 import com.datastax.driver.core.Session;
68 import com.datastax.driver.core.Statement;
69
70 public abstract class Batch {
71
72     private static StaticSlot ssargs;
73
74     protected static final String STARS = "*****";
75
76     protected final Cluster cluster; 
77     protected static AuthzEnv env;
78     protected static Session session;
79     protected static Set<String> specialNames;
80     protected static List<String> specialDomains;
81     protected static boolean dryRun; 
82     protected static String batchEnv;
83
84         private static File logdir;
85
86     public static final String CASS_ENV = "CASS_ENV";
87     public static final String LOG_DIR = "LOG_DIR";
88     protected static final String MAX_EMAILS="MAX_EMAILS";
89     protected static final String VERSION="VERSION";
90     public static final String GUI_URL="GUI_URL";
91     
92     protected final Organization org;
93         protected String version;
94         protected static final Date now = new Date();
95         protected static final Date never = new Date(0);
96         
97     protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException {
98         if (batchEnv != null) {
99             env.info().log("Redirecting to ",batchEnv,"environment");
100             String str;
101             for (String key : new String[]{
102                     CassAccess.CASSANDRA_CLUSTERS,
103                     CassAccess.CASSANDRA_CLUSTERS_PORT,
104                     CassAccess.CASSANDRA_CLUSTERS_USER_NAME,
105                     CassAccess.CASSANDRA_CLUSTERS_PASSWORD,
106                     VERSION,GUI_URL,MAX_EMAILS,
107                     LOG_DIR,
108                     "SPECIAL_NAMES"
109                     }) {
110                 if ((str = env.getProperty(batchEnv+'.'+key))!=null) {
111                     env.setProperty(key, str);
112                 }
113             }
114         }
115
116         // Setup for Dry Run
117         cluster = CassAccess.cluster(env,batchEnv);
118         env.info().log("cluster name - ",cluster.getClusterName());
119         String dryRunStr = env.getProperty( "DRY_RUN" );
120         if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) {
121             dryRun = false;
122         } else {
123             dryRun = true;
124             env.info().log("dryRun set to TRUE");
125         }
126
127         org = OrganizationFactory.init(env);
128         if(org==null) {
129                 throw new OrganizationException("Organization MUST be defined for Batch");
130         }
131         org.setTestMode(dryRun);
132
133         // Special names to allow behaviors beyond normal rules
134         specialNames = new HashSet<>();
135         specialDomains = new ArrayList<>();
136         String names = env.getProperty( "SPECIAL_NAMES" );
137         if ( names != null )
138         {
139             env.info().log("Loading SPECIAL_NAMES");
140             for (String s :names.split(",") ) {
141                 env.info().log("\tspecial: " + s );
142                 if(s.indexOf('@')>0) {
143                         specialNames.add( s.trim() );
144                 } else {
145                         specialDomains.add(s.trim());
146                 }
147             }
148         }
149         
150         version = env.getProperty(VERSION,Config.AAF_DEFAULT_API_VERSION);
151     }
152
153     protected abstract void run(AuthzTrans trans);
154     protected void _close(AuthzTrans trans) {}
155     
156     public String[] args() {
157         return env.get(ssargs);
158     }
159     
160     public boolean isDryRun()
161     {
162         return dryRun;
163     }
164     
165     public boolean isSpecial(String user) {
166         if(user==null) {
167                 return false;
168         }
169         if (specialNames != null && specialNames.contains(user)) {
170             env.info().log("specialName: " + user);
171             return (true);
172         } else {
173                 if(specialDomains!=null) {
174                         for(String sd : specialDomains) {
175                                 if(user.endsWith(sd)) {
176                                         env.info().log("specialDomain: " + user + " matches " + sd);
177                                         return (true);
178                                 }
179                         }
180                 }
181         }
182         return (false);
183     }
184
185
186     protected PrintStream fallout(PrintStream inFallout, String logType)
187             throws IOException {
188         PrintStream fallout = inFallout;
189         if (fallout == null) {
190             File dir = new File("logs");
191             if (!dir.exists()) {
192                 dir.mkdirs();
193             }
194
195             File f = null;
196             long uniq = System.currentTimeMillis();
197
198             f = new File(dir, getClass().getSimpleName() + "_" + logType + "_"
199                     + uniq + ".log");
200
201             fallout = new PrintStream(new FileOutputStream(f, true));
202         }
203         return fallout;
204     }
205
206     public Organization getOrgFromID(AuthzTrans trans, String user) {
207         Organization organization;
208         try {
209             organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase());
210         } catch (OrganizationException e1) {
211             trans.error().log(e1);
212             organization=null;
213         }
214
215         if (organization == null) {
216             PrintStream fallout = null;
217
218             try {
219                 fallout = fallout(fallout, "Fallout");
220                 fallout.print("INVALID_ID,");
221                 fallout.println(user);
222             } catch (Exception e) {
223                 env.error().log("Could not write to Fallout File", e);
224             }
225             return (null);
226         }
227
228         return (organization);
229     }
230     
231     public static Row executeDeleteQuery(Statement stmt) {
232         Row row = null;
233         if (!dryRun) {
234             row = session.execute(stmt).one();
235         }
236
237         return (row);
238
239     }
240         
241     public static int acquireRunLock(String className) {
242         Boolean testEnv = true;
243         String envStr = env.getProperty("AFT_ENVIRONMENT");
244
245         if (envStr != null) {
246             if ("AFTPRD".equals(envStr)) {
247                 testEnv = false;
248             }
249         } else {
250             env.fatal()
251                     .log("AFT_ENVIRONMENT property is required and was not found. Exiting.");
252             System.exit(1);
253         }
254
255         if (testEnv) {
256             env.info().log("TESTMODE: skipping RunLock");
257             return (1);
258         }
259
260         String hostname = null;
261         try {
262             hostname = InetAddress.getLocalHost().getHostName();
263         } catch (UnknownHostException e) {
264             e.printStackTrace();
265             env.warn().log("Unable to get hostname");
266             return (0);
267         }
268
269         ResultSet existing = session.execute(String.format(
270                 "select * from authz.run_lock where class = '%s'", className));
271
272         for (Row row : existing) {
273             long curr = System.currentTimeMillis();
274             ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field
275                                                         // by name?
276
277             long interval = (1 * 60 * 1000); // @@ Create a value in props file
278                                                 // for this
279             long prev = lastRun.getLong();
280
281             if ((curr - prev) <= interval) {
282                 env.warn().log(
283                         String.format("Too soon! Last run was %d minutes ago.",
284                                 ((curr - prev) / 1000) / 60));
285                 env.warn().log(
286                         String.format("Min time between runs is %d minutes ",
287                                 (interval / 1000) / 60));
288                 env.warn().log(
289                         String.format("Last ran on machine: %s at %s",
290                                 row.getString("host"), row.getDate("start")));
291                 return (0);
292             } else {
293                 env.info().log("Delete old lock");
294                 deleteLock(className);
295             }
296         }
297
298         GregorianCalendar current = new GregorianCalendar();
299
300         // We want our time in UTC, hence "+0000"
301         SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000");
302         fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
303
304         String cql = String
305                 .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS",
306                         className, hostname, fmt.format(current.getTime()));
307
308         env.info().log(cql);
309
310         Row row = session.execute(cql).one();
311         if (!row.getBool("[applied]")) {
312             env.warn().log("Lightweight Transaction failed to write lock.");
313             env.warn().log(
314                     String.format("host with lock: %s, running at %s",
315                             row.getString("host"), row.getDate("start")));
316             return (0);
317         }
318         return (1);
319     }
320     
321     private static void deleteLock( String className) {
322         Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one();
323         if (! row.getBool("[applied]")) {
324             env.info().log( "delete failed" );
325         }
326     }
327
328     private static void transferVMProps(AuthzEnv env, String ... props) {
329         String value;
330         for (String key : props) {
331             if ((value = System.getProperty(key))!=null) {
332                 env.setProperty(key, value);
333             }
334         }
335     }
336     
337     protected static File logDir() {
338         if(logdir == null) {
339                 String ld = env.getProperty(LOG_DIR);
340                 if (ld==null) {
341                     if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir
342                         ld = "logs/";
343                     } else {
344                         ld = "logs/"+batchEnv;
345                     }
346                 }
347                 logdir = new File(ld);
348                 if(!logdir.exists()) {
349                         logdir.mkdirs();
350                 }
351         } 
352         return logdir;
353     }
354     protected int count(String str, char c) {
355         if (str==null || str.isEmpty()) {
356             return 0;
357         } else {
358             int count=1;
359             for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) {
360                 ++count;
361             }
362             return count;
363         }
364     }
365
366     public final void close(AuthzTrans trans) {
367         _close(trans);
368         if(session!=null) {
369                 session.close();
370         }
371         if(cluster!=null) {
372             cluster.close();
373         }
374     }
375
376     public static void main(String[] args) {
377         // Use a StringBuilder to save off logs until a File can be setup
378         StringBuilderOutputStream sbos = new StringBuilderOutputStream();
379         PropAccess access = new PropAccess(new PrintStream(sbos),args);
380         access.log(Level.INIT, "------- Starting Batch ------\n  Args: ");
381         for(String s: args) {
382                 sbos.getBuffer().append(s);
383                 sbos.getBuffer().append(' ');
384         }
385         
386         InputStream is = null;
387         String filename;
388         String propLoc;
389         try {
390             Define.set(access);
391             
392             if(access.getProperty(Config.CADI_PROP_FILES)==null) {
393                     File f = new File("authBatch.props");
394                     try {
395                         if (f.exists()) {
396                             filename = f.getAbsolutePath();
397                             is = new FileInputStream(f);
398                             propLoc = f.getPath();
399                         } else {
400                             URL rsrc = ClassLoader.getSystemResource("authBatch.props");
401                             filename = rsrc.toString();
402                             is = rsrc.openStream();
403                             propLoc = rsrc.getPath();
404                         }
405                         access.load(is);
406                     } finally {
407                         if (is == null) {
408                             System.err.println("authBatch.props must exist in current dir, or in Classpath");
409                             System.exit(1);
410                         }
411                         is.close();
412                     }
413                     if (filename != null) {
414                         access.log(Level.INFO,"Instantiated properties from", filename);
415                     }
416
417                     // Log where Config found
418                     access.log(Level.INFO,"Configuring from", propLoc);
419
420             }
421
422             env = new AuthzEnv(access);
423             
424             transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization");
425
426             // Be able to change Environments
427             // load extra properties, i.e.
428             // PERF.cassandra.clusters=....
429             batchEnv = env.getProperty(CASS_ENV);
430             if(batchEnv!=null) {
431                 batchEnv = batchEnv.trim();
432             }
433
434             File logFile = new File(logDir() + "/batch" + Chrono.dateOnlyStamp(new Date()) + ".log" );
435             PrintStream batchLog = new PrintStream(new FileOutputStream(logFile,true));
436             try {
437                     access.setStreamLogIt(batchLog);
438                     sbos.flush();
439                     batchLog.print(sbos.getBuffer());
440                     sbos = null;
441                     Logger.getRootLogger().addAppender(new Log4JAccessAppender(access));
442
443                     Batch batch = null;
444                     AuthzTrans trans = env.newTrans();
445         
446                     TimeTaken tt = trans.start("Total Run", Env.SUB);
447                     try {
448                         int len = args.length;
449                         if (len > 0) {
450                             String toolName = args[0];
451                             len -= 1;
452                             if (len < 0)
453                                 len = 0;
454                             String nargs[] = new String[len];
455                             if (len > 0) {
456                                 System.arraycopy(args, 1, nargs, 0, len);
457                             }
458         
459                             env.put(ssargs = env.staticSlot("ARGS"), nargs);
460         
461                             /*
462                              * Add New Batch Programs (inherit from Batch) here
463                              */
464         
465                             // Might be a Report, Update or Temp Batch
466                             Class<?> cls = null;
467                             String classifier = "";
468         
469                             String[] pkgs = new String[] {
470                                         "org.onap.aaf.auth.batch.update",
471                                         "org.onap.aaf.auth.batch.reports",
472                                         "org.onap.aaf.auth.batch.temp"
473                                         };
474                                         
475                             String ebp = env.getProperty("EXTRA_BATCH_PKGS");
476                             if(ebp!=null) {
477                                 String[] ebps = Split.splitTrim(':', ebp);
478                                 String[] temp = new String[ebps.length + pkgs.length];
479                                 System.arraycopy(pkgs,0, temp, 0, pkgs.length);
480                                 System.arraycopy(ebps,0,temp,pkgs.length,ebps.length);
481                                 pkgs = temp;
482                             }
483                             
484                             for(String p : pkgs) {
485                                     try {
486                                         cls = ClassLoader.getSystemClassLoader().loadClass(p + '.' + toolName);
487                                         int lastDot = p.lastIndexOf('.');
488                                         if(p.length()>0 || p.length()!=lastDot) { 
489                                                 StringBuilder sb = new StringBuilder();
490                                                 sb.append(Character.toUpperCase(p.charAt(++lastDot)));
491                                                 while(++lastDot<p.length()) {
492                                                         sb.append(p.charAt(lastDot));
493                                                 }
494                                                 sb.append(':');
495                                                 classifier = sb.toString();
496                                                 break;
497                                         }
498                                     } catch (ClassNotFoundException e) {
499                                         cls = null;
500                                     }
501                             }
502                             if (cls != null) {
503                                 Constructor<?> cnst = cls.getConstructor(AuthzTrans.class);
504                                 batch = (Batch) cnst.newInstance(trans);
505                                 env.info().log("Begin", classifier, toolName);
506                             }
507                         
508         
509                             if (batch == null) {
510                                 trans.error().log("No Batch named", toolName, "found");
511                             }
512                             /*
513                              * End New Batch Programs (inherit from Batch) here
514                              */
515         
516                         }
517                         if (batch != null) {
518                             batch.run(trans);
519                         }
520                     } finally {
521                         tt.done();
522                         if (batch != null) {
523                             batch.close(trans);
524                         }
525                         StringBuilder sb = new StringBuilder("Task Times\n");
526                         trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE);
527                         trans.info().log(sb);
528                     }
529             } finally {
530                 batchLog.close();
531             }
532
533         } catch (Exception e) {
534             e.printStackTrace(System.err);
535             // Exceptions thrown by DB aren't stopping the whole process.
536             System.exit(1);
537         }
538     }
539
540 }
541