aboutsummaryrefslogtreecommitdiff
path: root/bigtop-tests/smoke-tests/odpi-runtime/src/main/java/org/odpi/specs/runtime/hadoop/ApiExaminer.java
blob: d95c010d880b4e63c242c4564a967de47273e551 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.odpi.specs.runtime.hadoop;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A tool that generates API conformance tests for Hadoop libraries
 */
public class ApiExaminer {

  private static final Log LOG = LogFactory.getLog(ApiExaminer.class.getName());

  static private Set<String> unloadableClasses;

  private List<String> errors;
  private List<String> warnings;

  static {
    unloadableClasses = new HashSet<>();
    unloadableClasses.add("org.apache.hadoop.security.JniBasedUnixGroupsMapping");
    unloadableClasses.add("org.apache.hadoop.security.JniBasedUnixGroupsNetgroupMapping");
    unloadableClasses.add("org.apache.hadoop.io.compress.lz4.Lz4Compressor");
    unloadableClasses.add("org.apache.hadoop.record.compiler.ant.RccTask");

  }

  public static void main(String[] args) {
    Options options = new Options();

    options.addOption("c", "compare", true,
        "Compare against a spec, argument is the json file containing spec");
    options.addOption("h", "help", false, "You're looking at it");
    options.addOption("j", "jar", true, "Jar to examine");
    options.addOption("p", "prepare-spec", true,
        "Prepare the spec, argument is the directory to write the spec to");

    try {
      CommandLine cli = new GnuParser().parse(options, args);

      if (cli.hasOption('h')) {
        usage(options);
        return;
      }

      if ((!cli.hasOption('c') && !cli.hasOption('p')) ||
          (cli.hasOption('c') && cli.hasOption('p'))) {
        System.err.println("You must choose either -c or -p");
        usage(options);
        return;
      }

      if (!cli.hasOption('j')) {
        System.err.println("You must specify the jar to prepare or compare");
        usage(options);
        return;
      }

      String jar = cli.getOptionValue('j');
      ApiExaminer examiner = new ApiExaminer();

      if (cli.hasOption('c')) {
        examiner.compareAgainstStandard(cli.getOptionValue('c'), jar);
      } else if (cli.hasOption('p')) {
        examiner.prepareExpected(jar, cli.getOptionValue('p'));
      }
    } catch (Exception e) {
      System.err.println("Received exception while processing");
      e.printStackTrace();
    }
  }

  private static void usage(Options options) {
    HelpFormatter help = new HelpFormatter();
    help.printHelp("api-examiner", options);

  }

  private ApiExaminer() {
  }

  private void prepareExpected(String jarFile, String outputDir) throws IOException,
      ClassNotFoundException {
    JarInfo jarInfo = new JarInfo(jarFile, this);
    jarInfo.dumpToFile(new File(outputDir));
  }

  private void compareAgainstStandard(String json, String jarFile) throws IOException,
      ClassNotFoundException {
    errors = new ArrayList<>();
    warnings = new ArrayList<>();
    JarInfo underTest = new JarInfo(jarFile, this);
    JarInfo standard = jarInfoFromFile(new File(json));
    standard.compareAndReport(underTest);

    if (errors.size() > 0) {
      System.err.println("Found " + errors.size() + " incompatibilities:");
      for (String error : errors) {
        System.err.println(error);
      }
    }

    if (warnings.size() > 0) {
      System.err.println("Found " + warnings.size() + " possible issues: ");
      for (String warning : warnings) {
        System.err.println(warning);
      }
    }


  }

  private JarInfo jarInfoFromFile(File inputFile) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JarInfo jarInfo = mapper.readValue(inputFile, JarInfo.class);
    jarInfo.patchUpClassBackPointers(this);
    return jarInfo;
  }

  private static class JarInfo {
    String name;
    String version;
    ApiExaminer container;
    Map<String, ClassInfo> classes;

    // For use by Jackson
    public JarInfo() {

    }

    JarInfo(String jarFile, ApiExaminer container) throws IOException, ClassNotFoundException {
      this.container = container;
      LOG.info("Processing jar " + jarFile);
      File f = new File(jarFile);
      Pattern pattern = Pattern.compile("(hadoop-[a-z\\-]+)-([0-9]\\.[0-9]\\.[0-9]).*");
      Matcher matcher = pattern.matcher(f.getName());
      if (!matcher.matches()) {
        String msg = "Unable to determine name and version from " + f.getName();
        LOG.error(msg);
        throw new RuntimeException(msg);
      }
      name = matcher.group(1);
      version = matcher.group(2);
      classes = new HashMap<>();

      JarFile jar = new JarFile(jarFile);
      Enumeration<JarEntry> entries = jar.entries();
      while (entries.hasMoreElements()) {
        String name = entries.nextElement().getName();
        if (name.endsWith(".class")) {
          name = name.substring(0, name.length() - 6);
          name = name.replace('/', '.');
          if (!unloadableClasses.contains(name)) {
            LOG.debug("Processing class " + name);
            Class<?> clazz = Class.forName(name);
            if (clazz.getAnnotation(InterfaceAudience.Public.class) != null &&
                clazz.getAnnotation(InterfaceStability.Stable.class) != null) {
              classes.put(name, new ClassInfo(this, clazz));
            }
          }
        }
      }
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getVersion() {
      return version;
    }

    public void setVersion(String version) {
      this.version = version;
    }

    public Map<String, ClassInfo> getClasses() {
      return classes;
    }

    public void setClasses(Map<String, ClassInfo> classes) {
      this.classes = classes;
    }

    void compareAndReport(JarInfo underTest) {
      Set<ClassInfo> underTestClasses = new HashSet<>(underTest.classes.values());
      for (ClassInfo classInfo : classes.values()) {
        if (underTestClasses.contains(classInfo)) {
          classInfo.compareAndReport(underTest.classes.get(classInfo.name));
          underTestClasses.remove(classInfo);
        } else {
          container.errors.add(underTest + " does not contain class " + classInfo);
        }
      }

      if (underTestClasses.size() > 0) {
        for (ClassInfo extra : underTestClasses) {
          container.warnings.add(underTest + " contains extra class " + extra);
        }
      }
    }

    void dumpToFile(File outputDir) throws IOException {
      File output = new File(outputDir, name + "-" + version + "-api-report.json");
      ObjectMapper mapper = new ObjectMapper();
      mapper.writeValue(output, this);
    }

    void patchUpClassBackPointers(ApiExaminer container) {
      this.container = container;
      for (ClassInfo classInfo : classes.values()) {
        classInfo.setJar(this);
        classInfo.patchUpBackMethodBackPointers();
      }
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof JarInfo)) return false;
      JarInfo that = (JarInfo)other;
      return name.equals(that.name) && version.equals(that.version);
    }

    @Override
    public String toString() {
      return name + "-" + version;
    }
  }

  private static class ClassInfo {
    @JsonIgnore JarInfo jar;
    String name;
    Map<String, MethodInfo> methods;

    // For use by Jackson
    public ClassInfo() {

    }

    ClassInfo(JarInfo jar, Class<?> clazz) {
      this.jar = jar;
      this.name = clazz.getName();
      methods = new HashMap<>();

      for (Method method : clazz.getMethods()) {
        if (method.getDeclaringClass().equals(clazz)) {
          LOG.debug("Processing method " + method.getName());
          MethodInfo mi = new MethodInfo(this, method);
          methods.put(mi.toString(), mi);
        }
      }
    }

    public JarInfo getJar() {
      return jar;
    }

    public void setJar(JarInfo jar) {
      this.jar = jar;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public Map<String, MethodInfo> getMethods() {
      return methods;
    }

    public void setMethods(Map<String, MethodInfo> methods) {
      this.methods = methods;
    }

    void compareAndReport(ClassInfo underTest) {
      // Make a copy so we can remove them as we match them, making it easy to find additional ones
      Set<MethodInfo> underTestMethods = new HashSet<>(underTest.methods.values());
      for (MethodInfo methodInfo : methods.values()) {
        if (underTestMethods.contains(methodInfo)) {
          methodInfo.compareAndReport(underTest.methods.get(methodInfo.toString()));
          underTestMethods.remove(methodInfo);
        } else {
          jar.container.errors.add(underTest + " does not contain method " + methodInfo);
        }
      }

      if (underTestMethods.size() > 0) {
        for (MethodInfo extra : underTestMethods) {
          jar.container.warnings.add(underTest + " contains extra method " + extra);
        }
      }
    }

    void patchUpBackMethodBackPointers() {
      for (MethodInfo methodInfo : methods.values()) methodInfo.setContainingClass(this);
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof ClassInfo)) return false;
      ClassInfo that = (ClassInfo)other;
      return name.equals(that.name);  // Classes can be compared just on names
    }

    @Override
    public int hashCode() {
      return name.hashCode();
    }

    @Override
    public String toString() {
      return jar + " " + name;
    }
  }

  private static class MethodInfo {
    @JsonIgnore ClassInfo containingClass;
    String name;
    String returnType;
    List<String> args;
    Set<String> exceptions;

    // For use by Jackson
    public MethodInfo() {

    }

    MethodInfo(ClassInfo containingClass, Method method) {
      this.containingClass = containingClass;
      this.name = method.getName();
      args = new ArrayList<>();
      for (Class<?> argClass : method.getParameterTypes()) {
        args.add(argClass.getName());
      }
      returnType = method.getReturnType().getName();
      exceptions = new HashSet<>();
      for (Class<?> exception : method.getExceptionTypes()) {
        exceptions.add(exception.getName());
      }
    }

    public ClassInfo getContainingClass() {
      return containingClass;
    }

    public void setContainingClass(ClassInfo containingClass) {
      this.containingClass = containingClass;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getReturnType() {
      return returnType;
    }

    public void setReturnType(String returnType) {
      this.returnType = returnType;
    }

    public List<String> getArgs() {
      return args;
    }

    public void setArgs(List<String> args) {
      this.args = args;
    }

    public Set<String> getExceptions() {
      return exceptions;
    }

    public void setExceptions(Set<String> exceptions) {
      this.exceptions = exceptions;
    }

    void compareAndReport(MethodInfo underTest) {
      // Check to see if they've added or removed exceptions
      // Make a copy so I can remove them as I check them off and easily find any that have been
      // added.
      Set<String> underTestExceptions = new HashSet<>(underTest.exceptions);
      for (String exception : exceptions) {
        if (underTest.exceptions.contains(exception)) {
          underTestExceptions.remove(exception);
        } else {
          containingClass.jar.container.warnings.add(underTest.containingClass.jar + " " +
              underTest.containingClass + "." + name + " removes exception " + exception);
        }
      }
      if (underTestExceptions.size() > 0) {
        for (String underTestException : underTest.exceptions) {
          containingClass.jar.container.warnings.add(underTest.containingClass.jar + " " +
              underTest.containingClass + "." + name + " adds exception " + underTestException);
        }
      }
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof MethodInfo)) return false;
      MethodInfo that = (MethodInfo)other;

      return containingClass.equals(that.containingClass) && name.equals(that.name) &&
          returnType.equals(that.returnType) && args.equals(that.args);
    }

    @Override
    public int hashCode() {
      return ((containingClass.hashCode() * 31 + name.hashCode()) * 31 + returnType.hashCode()) * 31 +
          args.hashCode();
    }

    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(returnType)
          .append(" ")
          .append(name)
          .append('(');
      boolean first = true;
      for (String arg : args) {
        if (first) first = false;
        else buf.append(", ");
        buf.append(arg);
      }
      buf.append(")");
      if (exceptions.size() > 0) {
        buf.append(" throws ");
        first = true;
        for (String exception : exceptions) {
          if (first) first = false;
          else buf.append(", ");
          buf.append(exception);
        }
      }
      return buf.toString();
    }
  }
}