Change agent.sh to work with K8s
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / helpers / Cred.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.helpers;
23
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.GregorianCalendar;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.TreeMap;
32
33 import org.onap.aaf.auth.dao.cass.CredDAO;
34 import org.onap.aaf.auth.dao.hl.Question;
35 import org.onap.aaf.cadi.util.CSV;
36 import org.onap.aaf.misc.env.Env;
37 import org.onap.aaf.misc.env.TimeTaken;
38 import org.onap.aaf.misc.env.Trans;
39 import org.onap.aaf.misc.env.util.Chrono;
40
41 import com.datastax.driver.core.ResultSet;
42 import com.datastax.driver.core.Row;
43 import com.datastax.driver.core.Session;
44 import com.datastax.driver.core.SimpleStatement;
45 import com.datastax.driver.core.Statement;
46
47 public class Cred  {
48     public static final TreeMap<String,Cred> data = new TreeMap<>();
49     public static final TreeMap<String,List<Cred>> byNS = new TreeMap<>();
50
51     public final String id;
52     public final List<Instance> instances;
53     public final String ns;
54     
55     public Cred(String id) {
56         this.id = id;
57         instances = new ArrayList<>();
58         ns=Question.domain2ns(id);
59     }
60     
61     public static class Instance {
62         public final int type;
63         public final Date expires,written;
64         public final Integer other;
65         
66         public Instance(int type, Date expires, Integer other, long written) {
67             this.type = type;
68             this.expires = expires;
69             this.other = other;
70             this.written = new Date(written);
71         }
72         
73         public String toString() {
74                 return expires.toString() + ": " + type;
75         }
76     }
77     
78     public Date last(final int ... types) {
79         Date last = null;
80         for (Instance i : instances) {
81             if (types.length>0) { // filter by types, if requested
82                 boolean quit = true;
83                 for (int t : types) {
84                     if (t==i.type) {
85                         quit=false;
86                         break;
87                     }
88                 }
89                 if (quit) {
90                     continue;
91                 }
92             }
93             if (last==null || i.expires.after(last)) {
94                 last = i.expires;
95             }
96         }
97         return last;
98     }
99
100     
101     public Set<Integer> types() {
102         Set<Integer> types = new HashSet<>();
103         for (Instance i : instances) {
104             types.add(i.type);
105         }
106         return types;
107     }
108
109     public static void load(Trans trans, Session session, int ... types ) {
110         load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred;",types);
111         
112     }
113
114     public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) {
115         load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred WHERE ns='" + ns + "';");
116     }
117
118     private static void load(Trans trans, Session session, String query, int ...types) {
119
120         trans.info().log( "query: " + query );
121         TimeTaken tt = trans.start("Read Creds", Env.REMOTE);
122        
123         ResultSet results;
124         try {
125             Statement stmt = new SimpleStatement( query );
126             results = session.execute(stmt);
127         } finally {
128             tt.done();
129         }
130         int count = 0;
131         try {
132             Iterator<Row> iter = results.iterator();
133             Row row;
134             tt = trans.start("Load Credentials", Env.SUB);
135             try {
136                 while (iter.hasNext()) {
137                     ++count;
138                     row = iter.next();
139                     int type = row.getInt(1);
140                     if (types.length>0) { // filter by types, if requested
141                         boolean quit = true;
142                         for (int t : types) {
143                             if (t==type) {
144                                 break;
145                             }
146                         }
147                         if (quit) {
148                             continue;
149                         }
150                     }
151                     add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4));
152                 }
153             } finally {
154                 tt.done();
155             }
156         } finally {
157             trans.info().log("Found",count,"creds");
158         }
159     }
160
161     public static void add(
162                 final String id, 
163                 final int type,
164                 final Date timestamp,
165                 final int other,
166                 final long written
167                 ) {
168         Cred cred = data.get(id);
169         if (cred==null) {
170             cred = new Cred(id);
171             data.put(id, cred);
172         }
173         cred.instances.add(new Instance(type, timestamp, other, written/1000));
174         
175         List<Cred> lscd = byNS.get(cred.ns);
176         if (lscd==null) {
177             byNS.put(cred.ns, (lscd=new ArrayList<>()));
178         }
179         boolean found = false;
180         for (Cred c : lscd) {
181             if (c.id.equals(cred.id)) {
182                 found=true;
183                 break;
184             }
185         }
186         if (!found) {
187             lscd.add(cred);
188         }
189         }
190
191
192         /** 
193      * Count entries in Cred data.
194      * Note, as opposed to other methods, need to load the whole cred table for the Types.
195      * @param numbuckets 
196      * @return
197      */
198     public static CredCount count(int numbuckets) {
199         CredCount cc = new CredCount(numbuckets);
200         for (Cred c : data.values()) {
201             for (Instance ci : c.instances) {
202                 cc.inc(ci.type,ci.written, ci.expires);
203             }
204         }
205         return cc;
206     }
207
208     public static class CredCount {
209         public int raw[];
210         public int basic_auth[];
211         public int basic_auth_256[];
212         public int cert[];
213         public int x509Added[];
214         public int x509Expired[];
215         public Date dates[];
216         
217         public CredCount(int numbuckets) {
218             raw = new int[numbuckets];
219             basic_auth = new int[numbuckets];
220             basic_auth_256 = new int[numbuckets];
221             cert = new int[numbuckets];
222             x509Added = new int[numbuckets];
223             x509Expired = new int[numbuckets];
224             dates = new Date[numbuckets];
225             GregorianCalendar gc = new GregorianCalendar();
226             dates[0]=gc.getTime(); // now
227             gc.set(GregorianCalendar.DAY_OF_MONTH, 1);
228             gc.set(GregorianCalendar.HOUR, 0);
229             gc.set(GregorianCalendar.MINUTE, 0);
230             gc.set(GregorianCalendar.SECOND,0);
231             gc.set(GregorianCalendar.MILLISECOND,0);
232             gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month
233             for (int i=1;i<numbuckets;++i) {
234                 dates[i] = gc.getTime();
235                 gc.add(GregorianCalendar.MONTH, -1);
236             }
237             
238         }
239         
240         public void inc(int type, Date start, Date expires) {
241             for (int i=0;i<dates.length-1;++i) {
242                 if (start.before(dates[i])) {
243                     if (type==CredDAO.CERT_SHA256_RSA) {
244                         if (start.after(dates[i+1])) {
245                             ++x509Added[i];
246                         }
247                     }
248                     if (expires.after(dates[i])) {
249                         switch(type) {
250                             case CredDAO.RAW:
251                                 ++raw[i];
252                                 break;
253                             case CredDAO.BASIC_AUTH:
254                                 ++basic_auth[i];
255                                 break;
256                             case CredDAO.BASIC_AUTH_SHA256:
257                                 ++basic_auth_256[i];
258                                 break;
259                             case CredDAO.CERT_SHA256_RSA:
260                                 ++cert[i];
261                                 break;
262                         }
263                     }
264                 }
265             }
266         }
267
268         public long authCount(int idx) {
269             return (long)basic_auth[idx]+basic_auth_256[idx];
270         }
271         
272         public long x509Count(int idx) {
273             return cert[idx];
274         }
275
276     }
277     
278     public void row(final CSV.Writer csvw, final Instance inst) {
279         csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires),inst.expires.getTime());
280     }
281
282
283     public static void row(StringBuilder sb, List<String> row) {
284         sb.append("DELETE from authz.cred WHERE id='");
285         sb.append(row.get(1));
286         sb.append("' AND type=");
287         sb.append(Integer.parseInt(row.get(3)));
288         // Note: We have to work with long, because Expires is part of Key... can't easily do date.
289         sb.append(" AND expires=dateof(maxtimeuuid(");
290         sb.append(row.get(5));
291         sb.append("));\n");
292         }
293
294
295         public String toString() {
296         StringBuilder sb = new StringBuilder(id);
297         sb.append('[');
298         for (Instance i : instances) {
299             sb.append('{');
300             sb.append(i.type);
301             sb.append(",\"");
302             sb.append(i.expires);
303             sb.append("\"}");
304         }
305         sb.append(']');
306         return sb.toString();
307     }
308
309     /* (non-Javadoc)
310      * @see java.lang.Object#hashCode()
311      */
312     @Override
313     public int hashCode() {
314         return id.hashCode();
315     }
316
317     /* (non-Javadoc)
318      * @see java.lang.Object#equals(java.lang.Object)
319      */
320     @Override
321     public boolean equals(Object obj) {
322         return id.equals(obj);
323     }
324
325
326         public static String histSubject(List<String> row) {
327                 return row.get(1);
328         }
329
330
331         public static String histMemo(String fmt, String orgName, List<String> row) {
332                 return String.format(fmt, row.get(1),orgName,row.get(4));
333         }
334
335 }