2 * ============LICENSE_START====================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
22 package org.onap.aaf.auth.batch;
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;
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;
42 import java.util.TimeZone;
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;
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;
70 public abstract class Batch {
72 private static StaticSlot ssargs;
74 protected static final String STARS = "*****";
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;
84 private static File logdir;
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";
92 protected final Organization org;
94 protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException {
95 if (batchEnv != null) {
96 env.info().log("Redirecting to ",batchEnv,"environment");
98 for (String key : new String[]{
99 CassAccess.CASSANDRA_CLUSTERS,
100 CassAccess.CASSANDRA_CLUSTERS_PORT,
101 CassAccess.CASSANDRA_CLUSTERS_USER_NAME,
102 CassAccess.CASSANDRA_CLUSTERS_PASSWORD,
103 VERSION,GUI_URL,MAX_EMAILS,
107 if ((str = env.getProperty(batchEnv+'.'+key))!=null) {
108 env.setProperty(key, str);
114 cluster = CassAccess.cluster(env,batchEnv);
115 env.info().log("cluster name - ",cluster.getClusterName());
116 String dryRunStr = env.getProperty( "DRY_RUN" );
117 if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) {
121 env.info().log("dryRun set to TRUE");
124 org = OrganizationFactory.init(env);
125 org.setTestMode(dryRun);
127 // Special names to allow behaviors beyond normal rules
128 specialNames = new HashSet<>();
129 specialDomains = new ArrayList<>();
130 String names = env.getProperty( "SPECIAL_NAMES" );
133 env.info().log("Loading SPECIAL_NAMES");
134 for (String s :names.split(",") ) {
135 env.info().log("\tspecial: " + s );
136 if(s.indexOf('@')>0) {
137 specialNames.add( s.trim() );
139 specialDomains.add(s.trim());
145 protected abstract void run(AuthzTrans trans);
146 protected abstract void _close(AuthzTrans trans);
148 public String[] args() {
149 return env.get(ssargs);
152 public boolean isDryRun()
157 public boolean isSpecial(String user) {
161 if (specialNames != null && specialNames.contains(user)) {
162 env.info().log("specialName: " + user);
165 if(specialDomains!=null) {
166 for(String sd : specialDomains) {
167 if(user.endsWith(sd)) {
168 env.info().log("specialDomain: " + user + " matches " + sd);
178 protected PrintStream fallout(PrintStream inFallout, String logType)
180 PrintStream fallout = inFallout;
181 if (fallout == null) {
182 File dir = new File("logs");
188 long uniq = System.currentTimeMillis();
190 f = new File(dir, getClass().getSimpleName() + "_" + logType + "_"
193 fallout = new PrintStream(new FileOutputStream(f, true));
198 public Organization getOrgFromID(AuthzTrans trans, String user) {
199 Organization organization;
201 organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase());
202 } catch (OrganizationException e1) {
203 trans.error().log(e1);
207 if (organization == null) {
208 PrintStream fallout = null;
211 fallout = fallout(fallout, "Fallout");
212 fallout.print("INVALID_ID,");
213 fallout.println(user);
214 } catch (Exception e) {
215 env.error().log("Could not write to Fallout File", e);
220 return (organization);
223 public static Row executeDeleteQuery(Statement stmt) {
226 row = session.execute(stmt).one();
233 public static int acquireRunLock(String className) {
234 Boolean testEnv = true;
235 String envStr = env.getProperty("AFT_ENVIRONMENT");
237 if (envStr != null) {
238 if ("AFTPRD".equals(envStr)) {
243 .log("AFT_ENVIRONMENT property is required and was not found. Exiting.");
248 env.info().log("TESTMODE: skipping RunLock");
252 String hostname = null;
254 hostname = InetAddress.getLocalHost().getHostName();
255 } catch (UnknownHostException e) {
257 env.warn().log("Unable to get hostname");
261 ResultSet existing = session.execute(String.format(
262 "select * from authz.run_lock where class = '%s'", className));
264 for (Row row : existing) {
265 long curr = System.currentTimeMillis();
266 ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field
269 long interval = (1 * 60 * 1000); // @@ Create a value in props file
271 long prev = lastRun.getLong();
273 if ((curr - prev) <= interval) {
275 String.format("Too soon! Last run was %d minutes ago.",
276 ((curr - prev) / 1000) / 60));
278 String.format("Min time between runs is %d minutes ",
279 (interval / 1000) / 60));
281 String.format("Last ran on machine: %s at %s",
282 row.getString("host"), row.getDate("start")));
285 env.info().log("Delete old lock");
286 deleteLock(className);
290 GregorianCalendar current = new GregorianCalendar();
292 // We want our time in UTC, hence "+0000"
293 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000");
294 fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
297 .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS",
298 className, hostname, fmt.format(current.getTime()));
302 Row row = session.execute(cql).one();
303 if (!row.getBool("[applied]")) {
304 env.warn().log("Lightweight Transaction failed to write lock.");
306 String.format("host with lock: %s, running at %s",
307 row.getString("host"), row.getDate("start")));
313 private static void deleteLock( String className) {
314 Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one();
315 if (! row.getBool("[applied]")) {
316 env.info().log( "delete failed" );
320 private static void transferVMProps(AuthzEnv env, String ... props) {
322 for (String key : props) {
323 if ((value = System.getProperty(key))!=null) {
324 env.setProperty(key, value);
329 protected static File logDir() {
331 String ld = env.getProperty(LOG_DIR);
333 if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir
336 ld = "logs/"+batchEnv;
339 logdir = new File(ld);
340 if(!logdir.exists()) {
346 protected int count(String str, char c) {
347 if (str==null || str.isEmpty()) {
351 for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) {
358 public final void close(AuthzTrans trans) {
363 public static void main(String[] args) {
364 // Use a StringBuilder to save off logs until a File can be setup
365 StringBuilderOutputStream sbos = new StringBuilderOutputStream();
366 PropAccess access = new PropAccess(new PrintStream(sbos),args);
367 access.log(Level.INIT, "------- Starting Batch ------\n Args: ");
368 for(String s: args) {
369 sbos.getBuffer().append(s);
370 sbos.getBuffer().append(' ');
373 InputStream is = null;
379 if(access.getProperty(Config.CADI_PROP_FILES)==null) {
380 File f = new File("authBatch.props");
383 filename = f.getAbsolutePath();
384 is = new FileInputStream(f);
385 propLoc = f.getPath();
387 URL rsrc = ClassLoader.getSystemResource("authBatch.props");
388 filename = rsrc.toString();
389 is = rsrc.openStream();
390 propLoc = rsrc.getPath();
395 System.err.println("authBatch.props must exist in current dir, or in Classpath");
400 if (filename != null) {
401 access.log(Level.INFO,"Instantiated properties from", filename);
404 // Log where Config found
405 access.log(Level.INFO,"Configuring from", propLoc);
409 env = new AuthzEnv(access);
411 transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization");
413 // Be able to change Environments
414 // load extra properties, i.e.
415 // PERF.cassandra.clusters=....
416 batchEnv = env.getProperty(CASS_ENV);
418 batchEnv = batchEnv.trim();
421 File logFile = new File(logDir() + "/batch" + Chrono.dateOnlyStamp(new Date()) + ".log" );
422 PrintStream batchLog = new PrintStream(new FileOutputStream(logFile,true));
424 access.setStreamLogIt(batchLog);
426 batchLog.print(sbos.getBuffer());
428 Logger.getRootLogger().addAppender(new Log4JAccessAppender(access));
431 AuthzTrans trans = env.newTrans();
433 TimeTaken tt = trans.start("Total Run", Env.SUB);
435 int len = args.length;
437 String toolName = args[0];
441 String nargs[] = new String[len];
443 System.arraycopy(args, 1, nargs, 0, len);
446 env.put(ssargs = env.staticSlot("ARGS"), nargs);
449 * Add New Batch Programs (inherit from Batch) here
452 // Might be a Report, Update or Temp Batch
454 String classifier = "";
456 String[] pkgs = new String[] {
457 "org.onap.aaf.auth.batch.update",
458 "org.onap.aaf.auth.batch.reports",
459 "org.onap.aaf.auth.batch.temp"
462 String ebp = env.getProperty("EXTRA_BATCH_PKGS");
464 String[] ebps = Split.splitTrim(':', ebp);
465 String[] temp = new String[ebps.length + pkgs.length];
466 System.arraycopy(pkgs,0, temp, 0, pkgs.length);
467 System.arraycopy(ebps,0,temp,pkgs.length,ebps.length);
471 for(String p : pkgs) {
473 cls = ClassLoader.getSystemClassLoader().loadClass(p + '.' + toolName);
474 int lastDot = p.lastIndexOf('.');
475 if(p.length()>0 || p.length()!=lastDot) {
476 StringBuilder sb = new StringBuilder();
477 sb.append(Character.toUpperCase(p.charAt(++lastDot)));
478 while(++lastDot<p.length()) {
479 sb.append(p.charAt(lastDot));
482 classifier = sb.toString();
485 } catch (ClassNotFoundException e) {
490 Constructor<?> cnst = cls.getConstructor(AuthzTrans.class);
491 batch = (Batch) cnst.newInstance(trans);
492 env.info().log("Begin", classifier, toolName);
497 trans.error().log("No Batch named", toolName, "found");
500 * End New Batch Programs (inherit from Batch) here
512 StringBuilder sb = new StringBuilder("Task Times\n");
513 trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE);
514 trans.info().log(sb);
520 } catch (Exception e) {
521 e.printStackTrace(System.err);
522 // Exceptions thrown by DB aren't stopping the whole process.