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;
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.GregorianCalendar;
37 import java.util.HashSet;
38 import java.util.List;
40 import java.util.TimeZone;
42 import org.onap.aaf.auth.common.Define;
43 import org.onap.aaf.auth.dao.CassAccess;
44 import org.onap.aaf.auth.dao.cass.RoleDAO;
45 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
46 import org.onap.aaf.auth.dao.hl.Question;
47 import org.onap.aaf.auth.env.AuthzEnv;
48 import org.onap.aaf.auth.env.AuthzTrans;
49 import org.onap.aaf.auth.layer.Result;
50 import org.onap.aaf.auth.org.Organization;
51 import org.onap.aaf.auth.org.Organization.Identity;
52 import org.onap.aaf.auth.org.OrganizationException;
53 import org.onap.aaf.auth.org.OrganizationFactory;
54 import org.onap.aaf.cadi.PropAccess;
55 import org.onap.aaf.cadi.Access.Level;
56 import org.onap.aaf.cadi.config.Config;
57 import org.onap.aaf.misc.env.APIException;
58 import org.onap.aaf.misc.env.Env;
59 import org.onap.aaf.misc.env.StaticSlot;
60 import org.onap.aaf.misc.env.TimeTaken;
62 import com.datastax.driver.core.Cluster;
63 import com.datastax.driver.core.ResultSet;
64 import com.datastax.driver.core.Row;
65 import com.datastax.driver.core.Session;
66 import com.datastax.driver.core.Statement;
68 public abstract class Batch {
70 private static String rootNs;
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 boolean dryRun;
81 protected static String batchEnv;
83 public static final String CASS_ENV = "CASS_ENV";
84 public static final String LOG_DIR = "LOG_DIR";
85 protected static final String PUNT="punt";
86 protected static final String MAX_EMAILS="MAX_EMAILS";
87 protected static final String VERSION="VERSION";
88 public static final String GUI_URL="GUI_URL";
90 protected final Organization org;
94 protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException {
95 // Be able to change Environments
96 // load extra properties, i.e.
97 // PERF.cassandra.clusters=....
98 batchEnv = env.getProperty(CASS_ENV);
99 if (batchEnv != null) {
100 batchEnv = batchEnv.trim();
101 env.info().log("Redirecting to ",batchEnv,"environment");
103 for (String key : new String[]{
104 CassAccess.CASSANDRA_CLUSTERS,
105 CassAccess.CASSANDRA_CLUSTERS_PORT,
106 CassAccess.CASSANDRA_CLUSTERS_USER_NAME,
107 CassAccess.CASSANDRA_CLUSTERS_PASSWORD,
108 VERSION,GUI_URL,PUNT,MAX_EMAILS,
112 if ((str = env.getProperty(batchEnv+'.'+key))!=null) {
113 env.setProperty(key, str);
119 cluster = CassAccess.cluster(env,batchEnv);
120 env.info().log("cluster name - ",cluster.getClusterName());
121 String dryRunStr = env.getProperty( "DRY_RUN" );
122 if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) {
126 env.info().log("dryRun set to TRUE");
129 org = OrganizationFactory.init(env);
130 org.setTestMode(dryRun);
132 // Special names to allow behaviors beyond normal rules
133 specialNames = new HashSet<>();
134 String names = env.getProperty( "SPECIAL_NAMES" );
137 env.info().log("Loading SPECIAL_NAMES");
138 for (String s :names.split(",") )
140 env.info().log("\tspecial: " + s );
141 specialNames.add( s.trim() );
146 protected abstract void run(AuthzTrans trans);
147 protected abstract void _close(AuthzTrans trans);
149 public String[] args() {
150 return env.get(ssargs);
153 public boolean isDryRun()
158 public boolean isSpecial(String user) {
159 if (specialNames != null && specialNames.contains(user)) {
160 env.info().log("specialName: " + user);
169 protected PrintStream fallout(PrintStream inFallout, String logType)
171 PrintStream fallout = inFallout;
172 if (fallout == null) {
173 File dir = new File("logs");
179 long uniq = System.currentTimeMillis();
181 f = new File(dir, getClass().getSimpleName() + "_" + logType + "_"
184 fallout = new PrintStream(new FileOutputStream(f, true));
189 public Organization getOrgFromID(AuthzTrans trans, String user) {
190 Organization organization;
192 organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase());
193 } catch (OrganizationException e1) {
194 trans.error().log(e1);
198 if (organization == null) {
199 PrintStream fallout = null;
202 fallout = fallout(fallout, "Fallout");
203 fallout.print("INVALID_ID,");
204 fallout.println(user);
205 } catch (Exception e) {
206 env.error().log("Could not write to Fallout File", e);
211 return (organization);
214 public static Row executeDeleteQuery(Statement stmt) {
217 row = session.execute(stmt).one();
224 public static int acquireRunLock(String className) {
225 Boolean testEnv = true;
226 String envStr = env.getProperty("AFT_ENVIRONMENT");
228 if (envStr != null) {
229 if ("AFTPRD".equals(envStr)) {
234 .log("AFT_ENVIRONMENT property is required and was not found. Exiting.");
239 env.info().log("TESTMODE: skipping RunLock");
243 String hostname = null;
245 hostname = InetAddress.getLocalHost().getHostName();
246 } catch (UnknownHostException e) {
248 env.warn().log("Unable to get hostname");
252 ResultSet existing = session.execute(String.format(
253 "select * from authz.run_lock where class = '%s'", className));
255 for (Row row : existing) {
256 long curr = System.currentTimeMillis();
257 ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field
260 long interval = (1 * 60 * 1000); // @@ Create a value in props file
262 long prev = lastRun.getLong();
264 if ((curr - prev) <= interval) {
266 String.format("Too soon! Last run was %d minutes ago.",
267 ((curr - prev) / 1000) / 60));
269 String.format("Min time between runs is %d minutes ",
270 (interval / 1000) / 60));
272 String.format("Last ran on machine: %s at %s",
273 row.getString("host"), row.getDate("start")));
276 env.info().log("Delete old lock");
277 deleteLock(className);
281 GregorianCalendar current = new GregorianCalendar();
283 // We want our time in UTC, hence "+0000"
284 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000");
285 fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
288 .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS",
289 className, hostname, fmt.format(current.getTime()));
293 Row row = session.execute(cql).one();
294 if (!row.getBool("[applied]")) {
295 env.warn().log("Lightweight Transaction failed to write lock.");
297 String.format("host with lock: %s, running at %s",
298 row.getString("host"), row.getDate("start")));
304 private static void deleteLock( String className) {
305 Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one();
306 if (! row.getBool("[applied]")) {
307 env.info().log( "delete failed" );
311 private static void transferVMProps(AuthzEnv env, String ... props) {
313 for (String key : props) {
314 if ((value = System.getProperty(key))!=null) {
315 env.setProperty(key, value);
320 // IMPORTANT! VALIDATE Organization isUser method
321 protected void checkOrganizationAcccess(AuthzTrans trans, Question q) throws APIException, OrganizationException {
322 Set<String> testUsers = new HashSet<>();
323 Result<List<RoleDAO.Data>> rrd = q.roleDAO.readNS(trans, rootNs);
325 for (RoleDAO.Data r : rrd.value) {
326 Result<List<UserRoleDAO.Data>> rur = q.userRoleDAO.readByRole(trans, r.fullName());
330 for (UserRoleDAO.Data udd : rur.value) {
331 testUsers.add(udd.user);
334 if (testUsers.size() < 2) {
335 throw new APIException("Not enough Users in Roles for " + rootNs + " to Validate");
339 for (String user : testUsers) {
340 if ((iden = org.getIdentity(trans, user)) == null) {
341 throw new APIException("Failed Organization Entity Validation Check: " + user);
343 trans.info().log("Organization Validation Check: " + iden.id());
349 protected static String logDir() {
350 String ld = env.getProperty(LOG_DIR);
352 if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir
355 ld = "logs/"+batchEnv;
360 protected int count(String str, char c) {
361 if (str==null || str.isEmpty()) {
365 for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) {
372 public final void close(AuthzTrans trans) {
377 public static void main(String[] args) {
378 PropAccess access = new PropAccess(args);
379 InputStream is = null;
384 rootNs =Define.ROOT_NS();
385 if(access.getProperty(Config.CADI_PROP_FILES)==null) {
386 File f = new File("authBatch.props");
389 filename = f.getAbsolutePath();
390 is = new FileInputStream(f);
391 propLoc = f.getPath();
393 URL rsrc = ClassLoader.getSystemResource("authBatch.props");
394 filename = rsrc.toString();
395 is = rsrc.openStream();
396 propLoc = rsrc.getPath();
401 System.err.println("authBatch.props must exist in current dir, or in Classpath");
406 if (filename != null) {
407 access.log(Level.INFO,"Instantiated properties from", filename);
410 // Log where Config found
411 access.log(Level.INFO,"Configuring from", propLoc);
414 env = new AuthzEnv(access);
416 transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization");
418 // Flow all Env Logs to Log4j, with ENV
421 // lfn = new LogFileNamer(logDir(),"").noPID();
422 // lfn.setAppender("authz-batch");
423 // lfn.setAppender("aspr|ASPR");
424 // lfn.setAppender("sync");
425 // lfn.setAppender("jobchange");
426 // lfn.setAppender("validateuser");
427 // aspr = Logger.getLogger("aspr");
428 // Log4JLogTarget.setLog4JEnv("authz-batch", env);
432 // setup ATTUser and Organization Slots before starting this:
434 // env.slot(ATT.ATT_USERSLOT);
436 // OrganizationFactory.setDefaultOrg(env, ATT.class.getName());
437 AuthzTrans trans = env.newTrans();
439 TimeTaken tt = trans.start("Total Run", Env.SUB);
441 int len = args.length;
443 String toolName = args[0];
447 String nargs[] = new String[len];
449 System.arraycopy(args, 1, nargs, 0, len);
452 env.put(ssargs = env.staticSlot("ARGS"), nargs);
455 * Add New Batch Programs (inherit from Batch) here
458 // Might be a Report, Update or Temp Batch
460 String classifier = "";
462 cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.update." + toolName);
463 classifier = "Update:";
464 } catch (ClassNotFoundException e) {
466 cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.reports." + toolName);
467 classifier = "Report:";
468 } catch (ClassNotFoundException e2) {
470 cls = ClassLoader.getSystemClassLoader()
471 .loadClass("org.onap.aaf.auth.temp." + toolName);
472 classifier = "Temp Utility:";
473 } catch (ClassNotFoundException e3) {
479 Constructor<?> cnst = cls.getConstructor(new Class[] { AuthzTrans.class });
480 batch = (Batch) cnst.newInstance(trans);
481 env.info().log("Begin", classifier, toolName);
486 trans.error().log("No Batch named", toolName, "found");
489 * End New Batch Programs (inherit from Batch) here
501 StringBuilder sb = new StringBuilder("Task Times\n");
502 trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE);
503 trans.info().log(sb);
505 } catch (Exception e) {
506 e.printStackTrace(System.err);
507 // Exceptions thrown by DB aren't stopping the whole process.