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