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 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;
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;
93 protected String version;
94 protected static final Date now = new Date();
95 protected static final Date never = new Date(0);
97 protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException {
98 if (batchEnv != null) {
99 env.info().log("Redirecting to ",batchEnv,"environment");
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,
111 if ((str = env.getProperty(batchEnv+'.'+key))!=null) {
112 env.setProperty(key, str);
119 cluster = CassAccess.cluster(env,batchEnv);
121 env.info().log("cluster name - ",cluster.getClusterName());
122 String dryRunStr = env.getProperty( "DRY_RUN" );
123 if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) {
127 env.info().log("dryRun set to TRUE");
130 org = OrganizationFactory.init(env);
132 throw new OrganizationException("Organization MUST be defined for Batch");
134 org.setTestMode(dryRun);
136 // Special names to allow behaviors beyond normal rules
137 specialNames = new HashSet<>();
138 specialDomains = new ArrayList<>();
139 String names = env.getProperty( "SPECIAL_NAMES" );
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() );
148 specialDomains.add(s.trim());
153 version = env.getProperty(VERSION,Config.AAF_DEFAULT_API_VERSION);
156 protected abstract void run(AuthzTrans trans);
157 protected void _close(AuthzTrans trans) {}
159 public String[] args() {
160 return env.get(ssargs);
163 public boolean isDryRun()
168 public boolean isSpecial(String user) {
172 if (specialNames != null && specialNames.contains(user)) {
173 env.info().log("specialName: " + user);
176 if(specialDomains!=null) {
177 for(String sd : specialDomains) {
178 if(user.endsWith(sd)) {
179 env.info().log("specialDomain: " + user + " matches " + sd);
189 protected PrintStream fallout(PrintStream inFallout, String logType)
191 PrintStream fallout = inFallout;
192 if (fallout == null) {
193 File dir = new File("logs");
199 long uniq = System.currentTimeMillis();
201 f = new File(dir, getClass().getSimpleName() + "_" + logType + "_"
204 fallout = new PrintStream(new FileOutputStream(f, true));
209 public Organization getOrgFromID(AuthzTrans trans, String user) {
210 Organization organization;
212 organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase());
213 } catch (OrganizationException e1) {
214 trans.error().log(e1);
218 if (organization == null) {
219 PrintStream fallout = null;
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);
231 return (organization);
234 public static Row executeDeleteQuery(Statement stmt) {
237 row = session.execute(stmt).one();
244 public static int acquireRunLock(String className) {
245 Boolean testEnv = true;
246 String envStr = env.getProperty("AFT_ENVIRONMENT");
248 if (envStr != null) {
249 if ("AFTPRD".equals(envStr)) {
254 .log("AFT_ENVIRONMENT property is required and was not found. Exiting.");
259 env.info().log("TESTMODE: skipping RunLock");
263 String hostname = null;
265 hostname = InetAddress.getLocalHost().getHostName();
266 } catch (UnknownHostException e) {
268 env.warn().log("Unable to get hostname");
272 ResultSet existing = session.execute(String.format(
273 "select * from authz.run_lock where class = '%s'", className));
275 for (Row row : existing) {
276 long curr = System.currentTimeMillis();
277 ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field
280 long interval = (1 * 60 * 1000); // @@ Create a value in props file
282 long prev = lastRun.getLong();
284 if ((curr - prev) <= interval) {
286 String.format("Too soon! Last run was %d minutes ago.",
287 ((curr - prev) / 1000) / 60));
289 String.format("Min time between runs is %d minutes ",
290 (interval / 1000) / 60));
292 String.format("Last ran on machine: %s at %s",
293 row.getString("host"), row.getDate("start")));
296 env.info().log("Delete old lock");
297 deleteLock(className);
301 GregorianCalendar current = new GregorianCalendar();
303 // We want our time in UTC, hence "+0000"
304 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000");
305 fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
308 .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS",
309 className, hostname, fmt.format(current.getTime()));
313 Row row = session.execute(cql).one();
314 if (!row.getBool("[applied]")) {
315 env.warn().log("Lightweight Transaction failed to write lock.");
317 String.format("host with lock: %s, running at %s",
318 row.getString("host"), row.getDate("start")));
324 private static void deleteLock( String className) {
325 Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one();
326 if (! row.getBool("[applied]")) {
327 env.info().log( "delete failed" );
331 private static void transferVMProps(AuthzEnv env, String ... props) {
333 for (String key : props) {
334 if ((value = System.getProperty(key))!=null) {
335 env.setProperty(key, value);
340 protected static File logDir() {
342 String ld = env.getProperty(LOG_DIR);
344 if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir
347 ld = "logs/"+batchEnv;
350 logdir = new File(ld);
351 if(!logdir.exists()) {
357 protected int count(String str, char c) {
358 if (str==null || str.isEmpty()) {
362 for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) {
369 public final void close(AuthzTrans trans) {
375 if(cluster!=null && !cluster.isClosed()) {
380 public static void main(String[] args) {
381 // Use a StringBuilder to save off logs until a File can be setup
382 StringBuilderOutputStream sbos = new StringBuilderOutputStream();
383 PropAccess access = new PropAccess(new PrintStream(sbos),args);
384 access.log(Level.INIT, "------- Starting Batch ------\n Args: ");
385 for(String s: args) {
386 sbos.getBuffer().append(s);
387 sbos.getBuffer().append(' ');
390 InputStream is = null;
396 if(access.getProperty(Config.CADI_PROP_FILES)==null) {
397 File f = new File("authBatch.props");
400 filename = f.getAbsolutePath();
401 is = new FileInputStream(f);
402 propLoc = f.getPath();
404 URL rsrc = ClassLoader.getSystemResource("authBatch.props");
405 filename = rsrc.toString();
406 is = rsrc.openStream();
407 propLoc = rsrc.getPath();
412 System.err.println("authBatch.props must exist in current dir, or in Classpath");
417 if (filename != null) {
418 access.log(Level.INFO,"Instantiated properties from", filename);
421 // Log where Config found
422 access.log(Level.INFO,"Configuring from", propLoc);
426 env = new AuthzEnv(access);
428 transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization");
430 // Be able to change Environments
431 // load extra properties, i.e.
432 // PERF.cassandra.clusters=....
433 batchEnv = env.getProperty(CASS_ENV);
435 batchEnv = batchEnv.trim();
438 File logFile = new File(logDir() + "/batch" + Chrono.dateOnlyStamp(new Date()) + ".log" );
439 PrintStream batchLog = new PrintStream(new FileOutputStream(logFile,true));
441 access.setStreamLogIt(batchLog);
443 batchLog.print(sbos.getBuffer());
445 Logger.getRootLogger().addAppender(new Log4JAccessAppender(access));
448 AuthzTrans trans = env.newTrans();
450 TimeTaken tt = trans.start("Total Run", Env.SUB);
452 int len = args.length;
454 String toolName = args[0];
458 String nargs[] = new String[len];
460 System.arraycopy(args, 1, nargs, 0, len);
463 env.put(ssargs = env.staticSlot("ARGS"), nargs);
466 * Add New Batch Programs (inherit from Batch) here
469 // Might be a Report, Update or Temp Batch
471 String classifier = "";
473 String[] pkgs = new String[] {
474 "org.onap.aaf.auth.batch.update",
475 "org.onap.aaf.auth.batch.reports",
476 "org.onap.aaf.auth.batch.temp"
479 String ebp = env.getProperty("EXTRA_BATCH_PKGS");
481 String[] ebps = Split.splitTrim(':', ebp);
482 String[] temp = new String[ebps.length + pkgs.length];
483 System.arraycopy(pkgs,0, temp, 0, pkgs.length);
484 System.arraycopy(ebps,0,temp,pkgs.length,ebps.length);
488 for(String p : pkgs) {
490 cls = ClassLoader.getSystemClassLoader().loadClass(p + '.' + toolName);
491 int lastDot = p.lastIndexOf('.');
492 if(p.length()>0 || p.length()!=lastDot) {
493 StringBuilder sb = new StringBuilder();
494 sb.append(Character.toUpperCase(p.charAt(++lastDot)));
495 while(++lastDot<p.length()) {
496 sb.append(p.charAt(lastDot));
499 classifier = sb.toString();
502 } catch (ClassNotFoundException e) {
507 Constructor<?> cnst = cls.getConstructor(AuthzTrans.class);
508 batch = (Batch) cnst.newInstance(trans);
509 env.info().log("Begin", classifier, toolName);
514 trans.error().log("No Batch named", toolName, "found");
517 * End New Batch Programs (inherit from Batch) here
524 } catch (Exception e) {
525 if(cluster!=null && !cluster.isClosed()) {
528 trans.error().log(e);
536 StringBuilder sb = new StringBuilder("Task Times\n");
537 trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE);
538 trans.info().log(sb);
544 } catch (Exception e) {
545 if(cluster!=null && !cluster.isClosed()) {
548 e.printStackTrace(System.err);