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;
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,
110 if ((str = env.getProperty(batchEnv+'.'+key))!=null) {
111 env.setProperty(key, str);
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()) ) {
124 env.info().log("dryRun set to TRUE");
127 org = OrganizationFactory.init(env);
129 throw new OrganizationException("Organization MUST be defined for Batch");
131 org.setTestMode(dryRun);
133 // Special names to allow behaviors beyond normal rules
134 specialNames = new HashSet<>();
135 specialDomains = new ArrayList<>();
136 String names = env.getProperty( "SPECIAL_NAMES" );
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() );
145 specialDomains.add(s.trim());
150 version = env.getProperty(VERSION,Config.AAF_DEFAULT_API_VERSION);
153 protected abstract void run(AuthzTrans trans);
154 protected void _close(AuthzTrans trans) {}
156 public String[] args() {
157 return env.get(ssargs);
160 public boolean isDryRun()
165 public boolean isSpecial(String user) {
169 if (specialNames != null && specialNames.contains(user)) {
170 env.info().log("specialName: " + user);
173 if(specialDomains!=null) {
174 for(String sd : specialDomains) {
175 if(user.endsWith(sd)) {
176 env.info().log("specialDomain: " + user + " matches " + sd);
186 protected PrintStream fallout(PrintStream inFallout, String logType)
188 PrintStream fallout = inFallout;
189 if (fallout == null) {
190 File dir = new File("logs");
196 long uniq = System.currentTimeMillis();
198 f = new File(dir, getClass().getSimpleName() + "_" + logType + "_"
201 fallout = new PrintStream(new FileOutputStream(f, true));
206 public Organization getOrgFromID(AuthzTrans trans, String user) {
207 Organization organization;
209 organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase());
210 } catch (OrganizationException e1) {
211 trans.error().log(e1);
215 if (organization == null) {
216 PrintStream fallout = null;
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);
228 return (organization);
231 public static Row executeDeleteQuery(Statement stmt) {
234 row = session.execute(stmt).one();
241 public static int acquireRunLock(String className) {
242 Boolean testEnv = true;
243 String envStr = env.getProperty("AFT_ENVIRONMENT");
245 if (envStr != null) {
246 if ("AFTPRD".equals(envStr)) {
251 .log("AFT_ENVIRONMENT property is required and was not found. Exiting.");
256 env.info().log("TESTMODE: skipping RunLock");
260 String hostname = null;
262 hostname = InetAddress.getLocalHost().getHostName();
263 } catch (UnknownHostException e) {
265 env.warn().log("Unable to get hostname");
269 ResultSet existing = session.execute(String.format(
270 "select * from authz.run_lock where class = '%s'", className));
272 for (Row row : existing) {
273 long curr = System.currentTimeMillis();
274 ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field
277 long interval = (1 * 60 * 1000); // @@ Create a value in props file
279 long prev = lastRun.getLong();
281 if ((curr - prev) <= interval) {
283 String.format("Too soon! Last run was %d minutes ago.",
284 ((curr - prev) / 1000) / 60));
286 String.format("Min time between runs is %d minutes ",
287 (interval / 1000) / 60));
289 String.format("Last ran on machine: %s at %s",
290 row.getString("host"), row.getDate("start")));
293 env.info().log("Delete old lock");
294 deleteLock(className);
298 GregorianCalendar current = new GregorianCalendar();
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"));
305 .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS",
306 className, hostname, fmt.format(current.getTime()));
310 Row row = session.execute(cql).one();
311 if (!row.getBool("[applied]")) {
312 env.warn().log("Lightweight Transaction failed to write lock.");
314 String.format("host with lock: %s, running at %s",
315 row.getString("host"), row.getDate("start")));
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" );
328 private static void transferVMProps(AuthzEnv env, String ... props) {
330 for (String key : props) {
331 if ((value = System.getProperty(key))!=null) {
332 env.setProperty(key, value);
337 protected static File logDir() {
339 String ld = env.getProperty(LOG_DIR);
341 if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir
344 ld = "logs/"+batchEnv;
347 logdir = new File(ld);
348 if(!logdir.exists()) {
354 protected int count(String str, char c) {
355 if (str==null || str.isEmpty()) {
359 for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) {
366 public final void close(AuthzTrans trans) {
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(' ');
386 InputStream is = null;
392 if(access.getProperty(Config.CADI_PROP_FILES)==null) {
393 File f = new File("authBatch.props");
396 filename = f.getAbsolutePath();
397 is = new FileInputStream(f);
398 propLoc = f.getPath();
400 URL rsrc = ClassLoader.getSystemResource("authBatch.props");
401 filename = rsrc.toString();
402 is = rsrc.openStream();
403 propLoc = rsrc.getPath();
408 System.err.println("authBatch.props must exist in current dir, or in Classpath");
413 if (filename != null) {
414 access.log(Level.INFO,"Instantiated properties from", filename);
417 // Log where Config found
418 access.log(Level.INFO,"Configuring from", propLoc);
422 env = new AuthzEnv(access);
424 transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization");
426 // Be able to change Environments
427 // load extra properties, i.e.
428 // PERF.cassandra.clusters=....
429 batchEnv = env.getProperty(CASS_ENV);
431 batchEnv = batchEnv.trim();
434 File logFile = new File(logDir() + "/batch" + Chrono.dateOnlyStamp(new Date()) + ".log" );
435 PrintStream batchLog = new PrintStream(new FileOutputStream(logFile,true));
437 access.setStreamLogIt(batchLog);
439 batchLog.print(sbos.getBuffer());
441 Logger.getRootLogger().addAppender(new Log4JAccessAppender(access));
444 AuthzTrans trans = env.newTrans();
446 TimeTaken tt = trans.start("Total Run", Env.SUB);
448 int len = args.length;
450 String toolName = args[0];
454 String nargs[] = new String[len];
456 System.arraycopy(args, 1, nargs, 0, len);
459 env.put(ssargs = env.staticSlot("ARGS"), nargs);
462 * Add New Batch Programs (inherit from Batch) here
465 // Might be a Report, Update or Temp Batch
467 String classifier = "";
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"
475 String ebp = env.getProperty("EXTRA_BATCH_PKGS");
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);
484 for(String p : pkgs) {
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));
495 classifier = sb.toString();
498 } catch (ClassNotFoundException e) {
503 Constructor<?> cnst = cls.getConstructor(AuthzTrans.class);
504 batch = (Batch) cnst.newInstance(trans);
505 env.info().log("Begin", classifier, toolName);
510 trans.error().log("No Batch named", toolName, "found");
513 * End New Batch Programs (inherit from Batch) here
525 StringBuilder sb = new StringBuilder("Task Times\n");
526 trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE);
527 trans.info().log(sb);
533 } catch (Exception e) {
534 e.printStackTrace(System.err);
535 // Exceptions thrown by DB aren't stopping the whole process.