aboutsummaryrefslogtreecommitdiff
path: root/caliper/src/main/java/com/google/caliper/runner/ExperimentingRunnerModule.java
blob: 7abcbd989bdae0fc9946d6c4bebb8084dcda1b30 (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
/*
 * Copyright (C) 2012 Google Inc.
 *
 * 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
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 com.google.caliper.runner;

import com.google.caliper.api.ResultProcessor;
import com.google.caliper.config.CaliperConfig;
import com.google.caliper.config.InstrumentConfig;
import com.google.caliper.model.Host;
import com.google.caliper.options.CaliperOptions;
import com.google.caliper.platform.Platform;
import com.google.caliper.runner.Instrument.Instrumentation;
import com.google.caliper.util.InvalidCommandException;
import com.google.caliper.util.ShortDuration;
import com.google.caliper.util.Stderr;
import com.google.caliper.util.Util;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;

import dagger.MapKey;
import dagger.Module;
import dagger.Provides;
import dagger.Provides.Type;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.Executors;

import javax.inject.Provider;
import javax.inject.Singleton;

/**
 * Configures a {@link CaliperRun} that performs experiments.
 */
@Module
final class ExperimentingRunnerModule {
  private static final String RUNNER_MAX_PARALLELISM_OPTION = "runner.maxParallelism";

  @Provides(type = Type.SET)
  static Service provideServerSocketService(ServerSocketService impl) {
    return impl;
  }

  @Provides(type = Type.SET)
  static Service provideTrialOutputFactoryService(TrialOutputFactoryService impl) {
    return impl;
  }

  @Provides
  static TrialOutputFactory provideTrialOutputFactory(TrialOutputFactoryService impl) {
    return impl;
  }

  @Provides
  static ExperimentSelector provideExperimentSelector(FullCartesianExperimentSelector impl) {
    return impl;
  }

  @Provides
  static ListeningExecutorService provideExecutorService(CaliperConfig config) {
    int poolSize = Integer.parseInt(config.properties().get(RUNNER_MAX_PARALLELISM_OPTION));
    return MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(poolSize));
  }

  @LocalPort
  @Provides
  static int providePortNumber(ServerSocketService serverSocketService) {
    return serverSocketService.getPort();
  }

  /**
   * Specifies the {@link Class} object to use as a key in the map of available
   * {@link ResultProcessor result processors} passed to
   * {@link #provideResultProcessors(CaliperConfig, Map)}.
   */
  @MapKey(unwrapValue = true)
  public @interface ResultProcessorClassKey {
    Class<? extends ResultProcessor> value();
  }

  @Provides(type = Type.MAP)
  @ResultProcessorClassKey(OutputFileDumper.class)
  static ResultProcessor provideOutputFileDumper(OutputFileDumper impl) {
    return impl;
  }

  @Provides(type = Type.MAP)
  @ResultProcessorClassKey(HttpUploader.class)
  static ResultProcessor provideHttpUploader(HttpUploader impl) {
    return impl;
  }

  @Provides static ImmutableSet<ResultProcessor> provideResultProcessors(
      CaliperConfig config,
      Map<Class<? extends ResultProcessor>, Provider<ResultProcessor>> availableProcessors) {
    ImmutableSet.Builder<ResultProcessor> builder = ImmutableSet.builder();
    for (Class<? extends ResultProcessor> processorClass : config.getConfiguredResultProcessors()) {
      Provider<ResultProcessor> resultProcessorProvider = availableProcessors.get(processorClass);
      ResultProcessor resultProcessor = resultProcessorProvider == null
          ? ResultProcessorCreator.createResultProcessor(processorClass)
          : resultProcessorProvider.get();
      builder.add(resultProcessor);
    }
    return builder.build();
  }

  @Provides static UUID provideUuid() {
    return UUID.randomUUID();
  }

  @Provides @BenchmarkParameters
  static ImmutableSetMultimap<String, String> provideBenchmarkParameters(
      BenchmarkClass benchmarkClass, CaliperOptions options) throws InvalidBenchmarkException {
    return benchmarkClass.userParameters().fillInDefaultsFor(options.userParameters());
  }

  @Provides @Singleton
  static Host provideHost(EnvironmentGetter environmentGetter) {
    return environmentGetter.getHost();
  }

  @Provides @Singleton
  static EnvironmentGetter provideEnvironmentGetter() {
    return new EnvironmentGetter();
  }

  /**
   * Specifies the {@link Class} object to use as a key in the map of available
   * {@link Instrument instruments} passed to {@link #provideInstruments},
   */
  @MapKey(unwrapValue = true)
  public @interface InstrumentClassKey {
    Class<? extends Instrument> value();
  }

  @Provides(type = Type.MAP)
  @InstrumentClassKey(ArbitraryMeasurementInstrument.class)
  static Instrument provideArbitraryMeasurementInstrument() {
    return new ArbitraryMeasurementInstrument();
  }

  @Provides(type = Type.MAP)
  @InstrumentClassKey(AllocationInstrument.class)
  static Instrument provideAllocationInstrument() {
    return new AllocationInstrument();
  }

  @Provides(type = Type.MAP)
  @InstrumentClassKey(RuntimeInstrument.class)
  static Instrument provideRuntimeInstrument(
      @NanoTimeGranularity ShortDuration nanoTimeGranularity) {
    return new RuntimeInstrument(nanoTimeGranularity);
  }

  @Provides
  static ImmutableSet<Instrument> provideInstruments(
      CaliperOptions options,
      final CaliperConfig config,
      Map<Class<? extends Instrument>, Provider<Instrument>> availableInstruments,
      Platform platform,
      @Stderr PrintWriter stderr)
      throws InvalidCommandException {

    ImmutableSet.Builder<Instrument> builder = ImmutableSet.builder();
    ImmutableSet<String> configuredInstruments = config.getConfiguredInstruments();
    for (final String instrumentName : options.instrumentNames()) {
      if (!configuredInstruments.contains(instrumentName)) {
        throw new InvalidCommandException("%s is not a configured instrument (%s). "
            + "use --print-config to see the configured instruments.",
            instrumentName, configuredInstruments);
      }
      final InstrumentConfig instrumentConfig = config.getInstrumentConfig(instrumentName);
      String className = instrumentConfig.className();
      try {
        Class<? extends Instrument> clazz =
            Util.lenientClassForName(className).asSubclass(Instrument.class);
        Provider<Instrument> instrumentProvider = availableInstruments.get(clazz);
        if (instrumentProvider == null) {
          throw new InvalidInstrumentException("Instrument %s not supported", className);
        }

        // Make sure that the instrument is supported on the platform.
        if (platform.supports(clazz)) {
          Instrument instrument = instrumentProvider.get();
          InstrumentInjectorModule injectorModule =
              new InstrumentInjectorModule(instrumentConfig, instrumentName);
          InstrumentComponent instrumentComponent = DaggerInstrumentComponent.builder()
              .instrumentInjectorModule(injectorModule)
              .build();
          instrumentComponent.injectInstrument(instrument);
          builder.add(instrument);
        } else {
          stderr.format("Instrument %s not supported on %s, ignoring\n",
              className, platform.name());
        }
      } catch (ClassNotFoundException e) {
        throw new InvalidCommandException("Cannot find instrument class '%s'", className);
      }
    }
    return builder.build();
  }

  @Provides @Singleton static NanoTimeGranularityTester provideNanoTimeGranularityTester() {
    return new NanoTimeGranularityTester();
  }

  @Provides @Singleton @NanoTimeGranularity static ShortDuration provideNanoTimeGranularity(
      NanoTimeGranularityTester tester) {
    return tester.testNanoTimeGranularity();
  }

  @Provides static ImmutableSet<Instrumentation> provideInstrumentations(CaliperOptions options,
      BenchmarkClass benchmarkClass, ImmutableSet<Instrument> instruments)
          throws InvalidBenchmarkException {
    ImmutableSet.Builder<Instrumentation> builder = ImmutableSet.builder();
    ImmutableSet<String> benchmarkMethodNames = options.benchmarkMethodNames();
    Set<String> unusedBenchmarkNames = new HashSet<String>(benchmarkMethodNames);
    for (Instrument instrument : instruments) {
      for (Method method : findAllBenchmarkMethods(benchmarkClass.benchmarkClass(), instrument)) {
        if (benchmarkMethodNames.isEmpty() || benchmarkMethodNames.contains(method.getName())) {
          builder.add(instrument.createInstrumentation(method));
          unusedBenchmarkNames.remove(method.getName());
        }
      }
    }
    if (!unusedBenchmarkNames.isEmpty()) {
      throw new InvalidBenchmarkException(
          "Invalid benchmark method(s) specified in options: " + unusedBenchmarkNames);
    }
    return builder.build();
  }

  private static ImmutableSortedSet<Method> findAllBenchmarkMethods(Class<?> benchmarkClass,
      Instrument instrument) throws InvalidBenchmarkException {
    ImmutableSortedSet.Builder<Method> result = ImmutableSortedSet.orderedBy(
        Ordering.natural().onResultOf(new Function<Method, String>() {
          @Override public String apply(Method method) {
            return method.getName();
          }
        }));
    Set<String> benchmarkMethodNames = new HashSet<String>();
    Set<String> overloadedMethodNames = new TreeSet<String>();
    for (Method method : benchmarkClass.getDeclaredMethods()) {
      if (instrument.isBenchmarkMethod(method)) {
        method.setAccessible(true);
        result.add(method);
        if (!benchmarkMethodNames.add(method.getName())) {
          overloadedMethodNames.add(method.getName());
        }
      }
    }
    if (!overloadedMethodNames.isEmpty()) {
      throw new InvalidBenchmarkException(
          "Overloads are disallowed for benchmark methods, found overloads of %s in benchmark %s",
          overloadedMethodNames,
          benchmarkClass);
    }
    return result.build();
  }
}