<commit_before>/*
 * Copyright 2016-present Facebook, 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.facebook.buck.distributed;

import com.facebook.buck.command.Builder;
import com.facebook.buck.command.BuilderArgs;
import com.facebook.buck.command.LocalBuilder;
import com.facebook.buck.config.ActionGraphParallelizationMode;
import com.facebook.buck.distributed.build_client.BuildSlaveTimingStatsTracker.SlaveEvents;
import com.facebook.buck.distributed.thrift.BuildJob;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.BuildTargetParser;
import com.facebook.buck.parser.DefaultParserTargetNodeFactory;
import com.facebook.buck.parser.ParserTargetNodeFactory;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.rules.ActionGraphAndResolver;
import com.facebook.buck.rules.CachingBuildEngineDelegate;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.LocalCachingBuildEngineDelegate;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetGraphAndBuildTargets;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.TargetNodeFactory;
import com.facebook.buck.rules.coercer.ConstructorArgMarshaller;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.PathTypeCoercer;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.ExecutorPool;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.facebook.buck.util.cache.impl.DefaultFileHashCache;
import com.facebook.buck.util.cache.impl.StackedFileHashCache;
import com.facebook.buck.versions.VersionException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;

public class DistBuildSlaveExecutor {

  private static final Logger LOG = Logger.get(DistBuildSlaveExecutor.class);
  private static final String LOCALHOST_ADDRESS = "localhost";
  private static final boolean KEEP_GOING = true;

  private final DistBuildSlaveExecutorArgs args;

  @Nullable private TargetGraph targetGraph;

  @Nullable private ActionGraphAndResolver actionGraphAndResolver;

  @Nullable private CachingBuildEngineDelegate cachingBuildEngineDelegate;

  public DistBuildSlaveExecutor(DistBuildSlaveExecutorArgs args) {
    this.args = args;
  }

  public int buildAndReturnExitCode() throws IOException, InterruptedException {
    BuilderArgs builderArgs = args.createBuilderArgs();
    try (ExecutionContext executionContext = LocalBuilder.createExecutionContext(builderArgs)) {
      Builder localBuilder =
          new LocalBuilder(
              builderArgs,
              executionContext,
              Preconditions.checkNotNull(actionGraphAndResolver),
              Preconditions.checkNotNull(cachingBuildEngineDelegate),
              args.getArtifactCache(),
              args.getExecutorService(),
              KEEP_GOING,
              Optional.empty(),
              Optional.empty(),
              Optional.empty());

      DistBuildModeRunner runner = null;
      switch (args.getDistBuildMode()) {
        case REMOTE_BUILD:
          runner =
              new RemoteBuildModeRunner(
                  localBuilder,
                  args.getState().getRemoteState().getTopLevelTargets(),
                  exitCode ->
                      args.getDistBuildService()
                          .setFinalBuildStatus(
                              args.getStampedeId(),
                              BuildStatusUtil.exitCodeToBuildStatus(exitCode)));
          break;

        case COORDINATOR:
          runner = newCoordinatorMode(getFreePortForCoordinator(), false);
          break;

        case MINION:
          runner =
              newMinionMode(
                  localBuilder,
                  args.getRemoteCoordinatorAddress(),
                  args.getRemoteCoordinatorPort());
          break;

        case COORDINATOR_AND_MINION:
          int localCoordinatorPort = getFreePortForCoordinator();
          runner =
              new CoordinatorAndMinionModeRunner(
                  newCoordinatorMode(localCoordinatorPort, true),
                  newMinionMode(localBuilder, LOCALHOST_ADDRESS, localCoordinatorPort));
          break;

        default:
          LOG.error("Unknown distributed build mode [%s].", args.getDistBuildMode().toString());
          return -1;
      }

      return runner.runAndReturnExitCode();
    }
  }

  private MinionModeRunner newMinionMode(
      Builder localBuilder, String coordinatorAddress, int coordinatorPort) {
    MinionModeRunner.BuildCompletionChecker checker =
        () -> {
          BuildJob job = args.getDistBuildService().getCurrentBuildJobState(args.getStampedeId());
          return BuildStatusUtil.isBuildComplete(job.getStatus());
        };

    return new MinionModeRunner(
        coordinatorAddress,<commit_msg>Do not create a LocalBuilder when only running in Coordinator mode.<commit_after>/*
 * Copyright 2016-present Facebook, 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.facebook.buck.distributed;

import com.facebook.buck.command.Builder;
import com.facebook.buck.command.BuilderArgs;
import com.facebook.buck.command.LocalBuilder;
import com.facebook.buck.config.ActionGraphParallelizationMode;
import com.facebook.buck.distributed.build_client.BuildSlaveTimingStatsTracker.SlaveEvents;
import com.facebook.buck.distributed.thrift.BuildJob;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.BuildTargetParser;
import com.facebook.buck.parser.DefaultParserTargetNodeFactory;
import com.facebook.buck.parser.ParserTargetNodeFactory;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.rules.ActionGraphAndResolver;
import com.facebook.buck.rules.CachingBuildEngineDelegate;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.LocalCachingBuildEngineDelegate;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetGraphAndBuildTargets;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.TargetNodeFactory;
import com.facebook.buck.rules.coercer.ConstructorArgMarshaller;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.PathTypeCoercer;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.ExecutorPool;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.facebook.buck.util.cache.impl.DefaultFileHashCache;
import com.facebook.buck.util.cache.impl.StackedFileHashCache;
import com.facebook.buck.versions.VersionException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;

public class DistBuildSlaveExecutor {

  private static final Logger LOG = Logger.get(DistBuildSlaveExecutor.class);
  private static final String LOCALHOST_ADDRESS = "localhost";
  private static final boolean KEEP_GOING = true;

  private final DistBuildSlaveExecutorArgs args;

  @Nullable private TargetGraph targetGraph;

  @Nullable private ActionGraphAndResolver actionGraphAndResolver;

  @Nullable private CachingBuildEngineDelegate cachingBuildEngineDelegate;

  public DistBuildSlaveExecutor(DistBuildSlaveExecutorArgs args) {
    this.args = args;
  }

  public int buildAndReturnExitCode() throws IOException, InterruptedException {
    if (DistBuildMode.COORDINATOR == args.getDistBuildMode()) {
      return newCoordinatorMode(getFreePortForCoordinator(), false).runAndReturnExitCode();
    }

    DistBuildModeRunner runner = null;
    BuilderArgs builderArgs = args.createBuilderArgs();
    try (ExecutionContext executionContext = LocalBuilder.createExecutionContext(builderArgs)) {
      Builder localBuilder =
          new LocalBuilder(
              builderArgs,
              executionContext,
              Preconditions.checkNotNull(actionGraphAndResolver),
              Preconditions.checkNotNull(cachingBuildEngineDelegate),
              args.getArtifactCache(),
              args.getExecutorService(),
              KEEP_GOING,
              Optional.empty(),
              Optional.empty(),
              Optional.empty());

      switch (args.getDistBuildMode()) {
        case REMOTE_BUILD:
          runner =
              new RemoteBuildModeRunner(
                  localBuilder,
                  args.getState().getRemoteState().getTopLevelTargets(),
                  exitCode ->
                      args.getDistBuildService()
                          .setFinalBuildStatus(
                              args.getStampedeId(),
                              BuildStatusUtil.exitCodeToBuildStatus(exitCode)));
          break;

        case MINION:
          runner =
              newMinionMode(
                  localBuilder,
                  args.getRemoteCoordinatorAddress(),
                  args.getRemoteCoordinatorPort());
          break;

        case COORDINATOR_AND_MINION:
          int localCoordinatorPort = getFreePortForCoordinator();
          runner =
              new CoordinatorAndMinionModeRunner(
                  newCoordinatorMode(localCoordinatorPort, true),
                  newMinionMode(localBuilder, LOCALHOST_ADDRESS, localCoordinatorPort));
          break;

        case COORDINATOR:
          throw new IllegalStateException("COORDINATOR mode should have already been handled.");

        default:
          LOG.error("Unknown distributed build mode [%s].", args.getDistBuildMode().toString());
          return -1;
      }
    }
    return runner.runAndReturnExitCode();
  }

  private MinionModeRunner newMinionMode(
      Builder localBuilder, String coordinatorAddress, int coordinatorPort) {
    MinionModeRunner.BuildCompletionChecker checker =
        () -> {
          BuildJob job = args.getDistBuildService().getCurrentBuildJobState(args.getStampedeId());
          return BuildStatusUtil.isBuildComplete(job.getStatus());
        };

    return new MinionModeRunner(
        coordinatorAddress,
{'fraction_non_alphanumeric': 0.08179354520817936, 'fraction_numerical': 0.0014781966001478197, 'mean_word_length': 3.4624404543788936, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6270778', 'n_tokens_mistral': 3219, 'n_tokens_neox': 3090, 'n_words': 658}