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