Java Code Examples for com.google.common.base.Throwables#throwIfInstanceOf()

The following examples show how to use com.google.common.base.Throwables#throwIfInstanceOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoadingCacheFileHashCache.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
    throws IOException {
  Path relativeFilePath = archiveRelativePath.normalize();
  try {
    JarHashCodeAndFileType fileHashCodeAndFileType =
        (JarHashCodeAndFileType) loadingCache.get(relativeFilePath);
    HashCodeAndFileType memberHashCodeAndFileType =
        fileHashCodeAndFileType.getContents().get(memberPath);
    if (memberHashCodeAndFileType == null) {
      throw new NoSuchFileException(archiveRelativePath.toString());
    }

    return memberHashCodeAndFileType.getHashCode();
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
    throw new RuntimeException(e.getCause());
  }
}
 
Example 2
Source File: OptionsParser.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link OptionsData} associated with the given list of options classes.
 */
static synchronized OptionsData getOptionsDataInternal(
    List<Class<? extends OptionsBase>> optionsClasses) throws ConstructionException {
  ImmutableList<Class<? extends OptionsBase>> immutableOptionsClasses =
      ImmutableList.copyOf(optionsClasses);
  OptionsData result = optionsData.get(immutableOptionsClasses);
  if (result == null) {
    try {
      result = OptionsData.from(immutableOptionsClasses);
    } catch (Exception e) {
      Throwables.throwIfInstanceOf(e, ConstructionException.class);
      throw new ConstructionException(e.getMessage(), e);
    }
    optionsData.put(immutableOptionsClasses, result);
  }
  return result;
}
 
Example 3
Source File: LegacyDynamicSpawnStrategy.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public final DynamicExecutionResult call() throws InterruptedException {
  taskFinished.register();
  try {
    List<SpawnResult> spawnResults = callImpl();
    return DynamicExecutionResult.create(strategyIdentifier, fileOutErr, null, spawnResults);
  } catch (Exception e) {
    Throwables.throwIfInstanceOf(e, InterruptedException.class);
    return DynamicExecutionResult.create(
        strategyIdentifier,
        fileOutErr,
        e instanceof ExecException
            ? (ExecException) e
            : new UserExecException(
                e, createFailureDetail(Strings.nullToEmpty(e.getMessage()), Code.RUN_FAILURE)),
        /*spawnResults=*/ ImmutableList.of());
  } finally {
    try {
      fileOutErr.close();
    } catch (IOException ignored) {
      // Nothing we can do here.
    }
    taskFinished.arriveAndDeregister();
  }
}
 
Example 4
Source File: Deserializer.java    From buck with Apache License 2.0 6 votes vote down vote up
private <T extends AddsToRuleKey> void initialize(T instance, ClassInfo<? super T> classInfo)
    throws IOException {
  if (classInfo.getSuperInfo().isPresent()) {
    initialize(instance, classInfo.getSuperInfo().get());
  }

  ImmutableCollection<FieldInfo<?>> fields = classInfo.getFieldInfos();
  for (FieldInfo<?> info : fields) {
    try {
      Object value = createForField(info);
      setField(info.getField(), instance, value);
    } catch (Exception e) {
      Throwables.throwIfInstanceOf(e, IOException.class);
      throw new BuckUncheckedExecutionException(
          e,
          "When trying to initialize %s.%s.",
          instance.getClass().getName(),
          info.getField().getName());
    }
  }
}
 
Example 5
Source File: S3FileSystem.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private S3Client getSyncClient(String bucket) throws IOException {
  try {
    return syncClientCache.get(bucket);
  } catch (ExecutionException | SdkClientException e ) {
    final Throwable cause = e.getCause();
    final Throwable toChain;
    if (cause == null) {
      toChain = e;
    } else {
      Throwables.throwIfInstanceOf(cause, UserException.class);
      Throwables.throwIfInstanceOf(cause, IOException.class);

      toChain = cause;
    }

    throw new IOException(String.format("Unable to create a sync S3 client for bucket %s", bucket), toChain);
  }
}
 
Example 6
Source File: CcToolchainFeatures.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Given a list of {@code requestedSelectables}, returns all features that are enabled by the
 * toolchain configuration.
 *
 * <p>A requested feature will not be enabled if the toolchain does not support it (which may
 * depend on other requested features).
 *
 * <p>Additional features will be enabled if the toolchain supports them and they are implied by
 * requested features.
 *
 * <p>If multiple threads call this method we may do additional work in initializing the cache.
 * This reinitialization is benign.
 */
public FeatureConfiguration getFeatureConfiguration(ImmutableSet<String> requestedSelectables)
    throws CollidingProvidesException {
  try {
    if (configurationCache == null) {
      configurationCache = buildConfigurationCache();
    }
    return configurationCache.get(requestedSelectables);
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), CollidingProvidesException.class);
    Throwables.throwIfUnchecked(e.getCause());
    throw new IllegalStateException("Unexpected checked exception encountered", e);
  }
}
 
Example 7
Source File: Retrier.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a {@link Callable}, retrying execution in case of failure and returning the result in
 * case of success.
 *
 * <p>{@link InterruptedException} is not retried.
 *
 * @param call the {@link Callable} to execute.
 * @throws Exception if the {@code call} didn't succeed within the framework specified by {@code
 *     backoffSupplier} and {@code shouldRetry}.
 * @throws CircuitBreakerException in case a call was rejected because the circuit breaker
 *     tripped.
 * @throws InterruptedException if the {@code call} throws an {@link InterruptedException} or the
 *     current thread's interrupted flag is set.
 */
public <T> T execute(Callable<T> call) throws Exception {
  final Backoff backoff = newBackoff();
  while (true) {
    final State circuitState;
    circuitState = circuitBreaker.state();
    if (State.REJECT_CALLS.equals(circuitState)) {
      throw new CircuitBreakerException();
    }
    try {
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      T r = call.call();
      circuitBreaker.recordSuccess();
      return r;
    } catch (Exception e) {
      circuitBreaker.recordFailure();
      Throwables.throwIfInstanceOf(e, InterruptedException.class);
      if (State.TRIAL_CALL.equals(circuitState)) {
        throw e;
      }
      if (!shouldRetry.test(e)) {
        throw e;
      }
      final long delayMillis = backoff.nextDelayMillis();
      if (delayMillis < 0) {
        throw e;
      }
      sleeper.sleep(delayMillis);
    }
  }
}
 
Example 8
Source File: BuildEventServiceGrpcClient.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOverStream(PublishBuildToolEventStreamRequest buildEvent)
    throws InterruptedException {
  throwIfInterrupted();
  try {
    stream.onNext(buildEvent);
  } catch (StatusRuntimeException e) {
    Throwables.throwIfInstanceOf(Throwables.getRootCause(e), InterruptedException.class);
    streamStatus.set(Status.fromThrowable(e));
  }
}
 
Example 9
Source File: SmartDexingStep.java    From buck with Apache License 2.0 5 votes vote down vote up
private void runDxCommands(ExecutionContext context, Multimap<Path, Path> outputToInputs)
    throws StepFailedException, InterruptedException {
  // Invoke dx commands in parallel for maximum thread utilization.  In testing, dx revealed
  // itself to be CPU (and not I/O) bound making it a good candidate for parallelization.
  Stream<ImmutableList<Step>> dxSteps = generateDxCommands(filesystem, outputToInputs);

  ImmutableList<Callable<Unit>> callables =
      dxSteps
          .map(
              steps ->
                  (Callable<Unit>)
                      () -> {
                        for (Step step : steps) {
                          StepRunner.runStep(context, step, Optional.of(buildTarget));
                        }
                        return Unit.UNIT;
                      })
          .collect(ImmutableList.toImmutableList());

  try {
    MoreFutures.getAll(executorService, callables);
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    Throwables.throwIfInstanceOf(cause, StepFailedException.class);

    // Programmer error.  Boo-urns.
    throw new RuntimeException(cause);
  }
}
 
Example 10
Source File: RetryUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Throws an appropriate exception when all attempts failed.
 *
 * @param e                 the retry exception
 * @param actionDescription a description of the action being performed
 * @throws InterruptedException if the action was interrupted
 * @throws E                    if the action timed out
 */
private static <E extends CcmException> void handleAllAttemptsFailed(
        RetryException e, String actionDescription, Class<E> exceptionClass, Supplier<E> exceptionSupplier, Logger logger) throws InterruptedException, E {
    logger.info("Failed to {}", actionDescription);
    Attempt<?> lastFailedAttempt = e.getLastFailedAttempt();
    if (lastFailedAttempt.hasException()) {
        Throwable cause = lastFailedAttempt.getExceptionCause();
        Throwables.throwIfInstanceOf(cause, exceptionClass);
        Throwables.throwIfInstanceOf(cause, InterruptedException.class);
        Throwables.throwIfUnchecked(cause);
        throw new IllegalStateException(cause);
    } else {
        throw exceptionSupplier.get();
    }
}
 
Example 11
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void encrypt(String sourceFile, String targetFile, Collection<Key> recipients,
		ProgressHandler optionalProgressHandler, InputStreamSupervisor optionalInputStreamSupervisor,
		OutputStreamSupervisor optionalOutputStreamSupervisor) throws UserRequestedCancellationException {
	try {
		InputStreamSupervisor inputStreamSupervisor = optionalInputStreamSupervisor != null
				? optionalInputStreamSupervisor
				: new InputStreamSupervisorImpl();
		OutputStreamSupervisor outputStreamSupervisor = optionalOutputStreamSupervisor != null
				? optionalOutputStreamSupervisor
				: new OutputStreamSupervisorImpl();

		Updater progress = null;
		if (optionalProgressHandler != null) {
			progress = Progress.create("action.encrypt", optionalProgressHandler);
			progress.updateStepInfo("progress.preparingKeys");
		}

		PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
				buildKeysListForEncryption(recipients));

		OutputStream out = new BufferedOutputStream(outputStreamSupervisor.get(targetFile));
		InputStream in = inputStreamSupervisor.get(sourceFile);
		doEncryptFile(in, SourceInfo.fromFile(sourceFile), out, dataGenerator, progress, PGPLiteralData.BINARY);
		out.close();
		in.close();
	} catch (Throwable t) {
		File fileToDelete = new File(targetFile);
		if (fileToDelete.exists() && !fileToDelete.delete()) {
			log.warn("Failed to delete file after failed encryption: " + targetFile);
		}
		Throwables.throwIfInstanceOf(t, UserRequestedCancellationException.class);
		throw new RuntimeException("Encryption failed", t);
	}
}
 
Example 12
Source File: EtcdClusterConfig.java    From etcd-java with Apache License 2.0 5 votes vote down vote up
public static EtcdClient getClient(EtcdClusterConfig config) throws IOException, CertificateException {
    try {
        return clientCache.get(new CacheKey(config), config::newClient);
    } catch (ExecutionException ee) {
        Throwables.throwIfInstanceOf(ee.getCause(), IOException.class);
        Throwables.throwIfInstanceOf(ee.getCause(), CertificateException.class);
        Throwables.throwIfUnchecked(ee.getCause());
        throw new RuntimeException(ee.getCause());
    }
}
 
Example 13
Source File: KeyGeneratorServicePgpImpl.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Key createNewKey(CreateKeyParams params) throws FieldValidationException {
	try {
		Preconditions.checkArgument(params != null, "params must not be null");
		assertParamsValid(params);

		// Create Master key
		KeyPair masterKey = getOrGenerateKeyPair(getMasterKeyParameters());
		PGPKeyPair masterKeyBc = new JcaPGPKeyPair(algorithmNameToTag(masterKeyPurpose), masterKey, new Date());
		BcPGPContentSignerBuilder keySignerBuilderBc = new BcPGPContentSignerBuilder(
				algorithmNameToTag(masterKeyPurpose), hashAlgorithmNameToTag(masterKeySignerHashingAlgorithm));

		// Setup seret key encryption
		PGPDigestCalculator digestCalc = new BcPGPDigestCalculatorProvider()
				.get(hashAlgorithmNameToTag(secretKeyHashingAlgorithm));
		BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder(
				symmetricKeyAlgorithmNameToTag(secretKeyEncryptionAlgorithm), digestCalc);
		PBESecretKeyEncryptor keyEncryptorBc = encryptorBuilderBC.build(params.getPassphrase().toCharArray());

		// Key pair generator
		String userName = params.getFullName() + " <" + params.getEmail() + ">";
		PGPKeyRingGenerator keyPairGeneratorBc = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
				masterKeyBc, userName, digestCalc, null, null, keySignerBuilderBc, keyEncryptorBc);

		// Add Sub-key for encryption
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(encryptionKeyAlgorithm, PROVIDER);
		if ("ELGAMAL".equals(encryptionKeyAlgorithm)) {
			keyPairGenerator.initialize(new DHParameterSpec(dhParamsPrimeModulus, dhParamsBaseGenerator));
		} else if ("RSA".equals(encryptionKeyAlgorithm)) {
			// Re-using master key size.
			keyPairGenerator.initialize(new RSAKeyGenParameterSpec(masterKeySize, RSAKeyGenParameterSpec.F4));
		} else {
			throw new IllegalArgumentException(
					"Hanlding of parameter creation for " + encryptionKeyAlgorithm + " is not implemented");
		}
		KeyPair encryptionSubKey = keyPairGenerator.generateKeyPair();
		PGPKeyPair encryptionSubKeyBc = new JcaPGPKeyPair(algorithmNameToTag(encryptionKeyPurpose),
				encryptionSubKey, new Date());
		keyPairGeneratorBc.addSubKey(encryptionSubKeyBc);

		// TBD-191: Also add a sub-key for signing
		// KeyPair signatureSubKey = keyPairGenerator.generateKeyPair();
		// PGPKeyPair signatureSubKeyBc = new
		// TBD-191: RSA_SIGN must not be hardcoded
		// JcaPGPKeyPair(algorithmNameToTag("RSA_SIGN"), signatureSubKey,
		// new Date());
		// keyPairGeneratorBc.addSubKey(signatureSubKeyBc);

		// building ret
		return buildKey(keyPairGeneratorBc);
	} catch (Throwable t) {
		Throwables.throwIfInstanceOf(t, FieldValidationException.class);
		throw new RuntimeException("Failed to generate key", t);
	}
}
 
Example 14
Source File: IncludeScanningModule.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public void extractSwigIncludes(
    Set<Artifact> includes,
    ActionExecutionMetadata actionExecutionMetadata,
    ActionExecutionContext actionExecContext,
    Artifact source,
    ImmutableSet<Artifact> legalOutputPaths,
    ImmutableList<PathFragment> swigIncludePaths,
    Artifact grepIncludes)
    throws IOException, ExecException, InterruptedException {
  SwigIncludeScanner scanner =
      new SwigIncludeScanner(
          includePool.get(),
          spawnScannerSupplier.get(),
          cache,
          swigIncludePaths,
          env.getDirectories(),
          env.getSkyframeBuildView().getArtifactFactory(),
          env.getExecRoot(),
          useAsyncIncludeScanner);
  ImmutableMap.Builder<PathFragment, Artifact> pathToLegalOutputArtifact =
      ImmutableMap.builder();
  for (Artifact path : legalOutputPaths) {
    pathToLegalOutputArtifact.put(path.getExecPath(), path);
  }
  try {
    scanner
        .processAsync(
            source,
            ImmutableList.of(source),
            // For Swig include scanning just point to the output file in the map.
            new IncludeScanningHeaderData.Builder(
                    pathToLegalOutputArtifact.build(), /*modularHeaders=*/ ImmutableSet.of())
                .build(),
            ImmutableList.of(),
            includes,
            actionExecutionMetadata,
            actionExecContext,
            grepIncludes)
        .get();
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), ExecException.class);
    Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
    if (e.getCause() instanceof IORuntimeException) {
      throw ((IORuntimeException) e.getCause()).getCauseIOException();
    }
    Throwables.throwIfUnchecked(e.getCause());
    throw new IllegalStateException(e.getCause());
  }
}
 
Example 15
Source File: BuildEventServiceModule.java    From bazel with Apache License 2.0 4 votes vote down vote up
private void waitForBuildEventTransportsToClose(
    Map<BuildEventTransport, ListenableFuture<Void>> transportFutures,
    boolean besUploadModeIsSynchronous)
    throws AbruptExitException {
  final ScheduledExecutorService executor =
      Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder().setNameFormat("bes-notify-ui-%d").build());
  ScheduledFuture<?> waitMessageFuture = null;

  try {
    // Notify the UI handler when a transport finished closing.
    transportFutures.forEach(
        (bepTransport, closeFuture) ->
            closeFuture.addListener(
                () -> {
                  reporter.post(new BuildEventTransportClosedEvent(bepTransport));
                },
                executor));

    try (AutoProfiler p = GoogleAutoProfilerUtils.logged("waiting for BES close")) {
      Uninterruptibles.getUninterruptibly(Futures.allAsList(transportFutures.values()));
    }
  } catch (ExecutionException e) {
    // Futures.withTimeout wraps the TimeoutException in an ExecutionException when the future
    // times out.
    if (isTimeoutException(e)) {
      throw createAbruptExitException(
          e,
          "The Build Event Protocol upload timed out.",
          ExitCode.TRANSIENT_BUILD_EVENT_SERVICE_UPLOAD_ERROR,
          BuildProgress.Code.BES_UPLOAD_TIMEOUT_ERROR);
    }

    Throwables.throwIfInstanceOf(e.getCause(), AbruptExitException.class);
    throw new RuntimeException(
        String.format(
            "Unexpected Exception '%s' when closing BEP transports, this is a bug.",
            e.getCause().getMessage()));
  } finally {
    if (besUploadModeIsSynchronous) {
      cancelAndResetPendingUploads();
    }
    if (waitMessageFuture != null) {
      waitMessageFuture.cancel(/* mayInterruptIfRunning= */ true);
    }
    executor.shutdown();
  }
}
 
Example 16
Source File: DaemonicParserState.java    From buck with Apache License 2.0 4 votes vote down vote up
@Subscribe
public void invalidateBasedOn(WatchmanPathEvent event) {
  LOG.verbose("Parser watched event %s %s", event.getKind(), event.getPath());

  filesChangedCounter.inc();

  RelPath path = event.getPath();
  AbsPath fullPath = event.getCellPath().resolve(event.getPath());

  // We only care about creation and deletion events because modified should result in a
  // rule key change.  For parsing, these are the only events we need to care about.
  if (isPathCreateOrDeleteEvent(event)) {
    try (AutoCloseableLock readLock = cellStateLock.readLock()) {
      for (DaemonicCellState state : cellPathToDaemonicState.values()) {
        try {
          Cell cell = state.getCell();
          BuildFileTree buildFiles = buildFileTrees.get(cell);

          if (fullPath.endsWith(cell.getBuckConfigView(ParserConfig.class).getBuildFileName())) {
            LOG.debug(
                "Build file %s changed, invalidating build file tree for cell %s",
                fullPath, cell);
            // If a build file has been added or removed, reconstruct the build file tree.
            buildFileTrees.invalidate(cell);
          }

          // Added or removed files can affect globs, so invalidate the package build file
          // "containing" {@code path} unless its filename matches a temp file pattern.
          if (!cell.getFilesystem().isIgnored(path)) {
            invalidateContainingBuildFile(state, cell, buildFiles, path);
          } else {
            LOG.debug(
                "Not invalidating the owning build file of %s because it is a temporary file.",
                fullPath);
          }
        } catch (ExecutionException | UncheckedExecutionException e) {
          try {
            Throwables.throwIfInstanceOf(e, BuildFileParseException.class);
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
          } catch (BuildFileParseException bfpe) {
            LOG.warn("Unable to parse already parsed build file.", bfpe);
          }
        }
      }
    }
  }

  if (configurationBuildFiles.contains(fullPath) || configurationRulesDependOn(path.getPath())) {
    invalidateAllCaches();
  } else {
    invalidatePath(fullPath);
  }
}
 
Example 17
Source File: SkyframeExecutor.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the configurations corresponding to the given sets of build options. Output order is
 * the same as input order.
 *
 * @throws InvalidConfigurationException if any build options produces an invalid configuration
 */
// TODO(ulfjack): Remove this legacy method after switching to the Skyframe-based implementation.
private ImmutableList<BuildConfiguration> getConfigurations(
    ExtendedEventHandler eventHandler,
    List<BuildOptions> optionsList,
    BuildOptions referenceBuildOptions,
    boolean keepGoing)
    throws InvalidConfigurationException {
  Preconditions.checkArgument(!Iterables.isEmpty(optionsList));

  // Prepare the Skyframe inputs.
  // TODO(gregce): support trimmed configs.
  ImmutableSortedSet<Class<? extends Fragment>> allFragments =
      ruleClassProvider.getConfigurationFragments().stream()
          .map(factory -> factory.creates())
          .collect(
              ImmutableSortedSet.toImmutableSortedSet(BuildConfiguration.lexicalFragmentSorter));

  PlatformMappingValue platformMappingValue =
      getPlatformMappingValue(eventHandler, referenceBuildOptions);

  ImmutableList.Builder<SkyKey> configSkyKeysBuilder = ImmutableList.builder();
  for (BuildOptions options : optionsList) {
    configSkyKeysBuilder.add(toConfigurationKey(platformMappingValue, allFragments, options));
  }

  ImmutableList<SkyKey> configSkyKeys = configSkyKeysBuilder.build();

  // Skyframe-evaluate the configurations and throw errors if any.
  EvaluationResult<SkyValue> evalResult = evaluateSkyKeys(eventHandler, configSkyKeys, keepGoing);
  if (evalResult.hasError()) {
    Map.Entry<SkyKey, ErrorInfo> firstError = Iterables.get(evalResult.errorMap().entrySet(), 0);
    ErrorInfo error = firstError.getValue();
    Throwable e = error.getException();
    // Wrap loading failed exceptions
    if (e instanceof NoSuchThingException) {
      e = new InvalidConfigurationException(e);
    } else if (e == null && !error.getCycleInfo().isEmpty()) {
      getCyclesReporter().reportCycles(error.getCycleInfo(), firstError.getKey(), eventHandler);
      e =
          new InvalidConfigurationException(
              "cannot load build configuration because of this cycle");
    }
    if (e != null) {
      Throwables.throwIfInstanceOf(e, InvalidConfigurationException.class);
    }
    throw new IllegalStateException("Unknown error during configuration creation evaluation", e);
  }

  // Prepare and return the results.
  return configSkyKeys.stream()
      .map(key -> ((BuildConfigurationValue) evalResult.get(key)).getConfiguration())
      .collect(ImmutableList.toImmutableList());
}
 
Example 18
Source File: AsyncVersionedTargetGraphBuilder.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("PMD")
public TargetGraph build() throws TimeoutException, InterruptedException, VersionException {
  LOG.debug(
      "Starting version target graph transformation (nodes %d)",
      unversionedTargetGraphCreationResult.getTargetGraph().getNodes().size());
  long start = System.currentTimeMillis();

  ImmutableSet<VersionTargetGraphKey> rootKeys =
      RichStream.from(
              unversionedTargetGraphCreationResult
                  .getTargetGraph()
                  .getAll(unversionedTargetGraphCreationResult.getBuildTargets()))
          .map(ImmutableVersionTargetGraphKey::of)
          .collect(ImmutableSet.toImmutableSet());

  ImmutableMap<VersionTargetGraphKey, Future<TargetNode<?>>> results =
      asyncTransformationEngine.computeAll(rootKeys);

  // Wait for actions to complete.
  for (Future<TargetNode<?>> futures : results.values()) {
    try {
      futures.get(timeout, timeUnit);
    } catch (ExecutionException e) {
      Throwable rootCause = Throwables.getRootCause(e);
      Throwables.throwIfInstanceOf(rootCause, VersionException.class);
      Throwables.throwIfInstanceOf(rootCause, TimeoutException.class);
      Throwables.throwIfInstanceOf(rootCause, RuntimeException.class);
      throw new IllegalStateException(
          String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e);
    }
  }

  asyncTransformationEngine.close();
  versionInfoAsyncTransformationEngine.close();

  long end = System.currentTimeMillis();

  VersionedTargetGraph graph = versionedTargetGraphTransformer.targetGraphBuilder.build();
  LOG.debug(
      "Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
      (end - start) / 1000.0, graph.getSize(), versionedTargetGraphTransformer.roots.get());

  return graph;
}
 
Example 19
Source File: PackageFunction.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Compute the BzlLoadValue for all given keys by "inlining" the BzlLoadFunction and bypassing
 * traditional Skyframe evaluation, returning {@code null} if Skyframe deps were missing and have
 * been requested.
 */
@Nullable
private static List<BzlLoadValue> computeBzlLoadsWithInlining(
    Environment env, List<BzlLoadValue.Key> keys, BzlLoadFunction bzlLoadFunctionForInlining)
    throws InterruptedException, BzlLoadFailedException, InconsistentFilesystemException {
  List<BzlLoadValue> bzlLoads = Lists.newArrayListWithExpectedSize(keys.size());
  Exception deferredException = null;
  boolean valuesMissing = false;
  // Compute BzlLoadValue for each key, sharing the same inlining state, i.e. cache of loaded
  // modules. This ensures that each .bzl is loaded only once, regardless of diamond dependencies
  // or cache eviction. (Multiple loads of the same .bzl would screw up identity equality of some
  // Starlark symbols -- see comments in BzlLoadFunction#computeInline.)
  BzlLoadFunction.InliningState inliningState = BzlLoadFunction.InliningState.create();
  for (BzlLoadValue.Key key : keys) {
    SkyValue skyValue;
    try {
      // Will complete right away if it's already cached in inliningState.
      skyValue = bzlLoadFunctionForInlining.computeInline(key, env, inliningState);
    } catch (BzlLoadFailedException | InconsistentFilesystemException e) {
      // For determinism's sake while inlining, preserve the first exception and continue to run
      // subsequently listed loads to completion/exception, loading all transitive deps anyway.
      deferredException = MoreObjects.firstNonNull(deferredException, e);
      continue;
    }
    if (skyValue == null) {
      checkState(env.valuesMissing(), "no starlark load value for %s", key);
      // We continue making inline calls even if some requested values are missing, to
      // maximize the number of dependent (non-inlined) SkyFunctions that are requested, thus
      // avoiding a quadratic number of restarts.
      valuesMissing = true;
    } else {
      bzlLoads.add((BzlLoadValue) skyValue);
    }
  }
  if (deferredException != null) {
    Throwables.throwIfInstanceOf(deferredException, BzlLoadFailedException.class);
    Throwables.throwIfInstanceOf(deferredException, InconsistentFilesystemException.class);
    throw new IllegalStateException(
        "caught a checked exception of unexpected type", deferredException);
  }
  return valuesMissing ? null : bzlLoads;
}
 
Example 20
Source File: MoreThrowables.java    From buck with Apache License 2.0 2 votes vote down vote up
/**
 * Traverse exception chain by recursively calling {@code getCause()} and throws it if initial
 * exception (the one at the bottom of the stack) is an instance of {@code declaredType}.
 * Example usage:
 *
 * <pre>
 *   try {
 *     future.get()
 *   } catch (ExecutionException) {
 *     MoreThrowables.throwIfInitialCauseInstanceOf(t, BarException.class);
 *   }
 */
public static <X extends Throwable> void throwIfInitialCauseInstanceOf(
    Throwable throwable, Class<X> declaredType) throws X {
  Throwable cause = getInitialCause(throwable);
  Throwables.throwIfInstanceOf(cause, declaredType);
}