<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.beam.runners.jobsubmission;

import java.io.IOException;
import java.nio.file.Paths;
import org.apache.beam.model.pipeline.v1.Endpoints;
import org.apache.beam.runners.fnexecution.GrpcFnServer;
import org.apache.beam.runners.fnexecution.ServerFactory;
import org.apache.beam.runners.fnexecution.artifact.ArtifactStagingService;
import org.apache.beam.sdk.expansion.service.ExpansionServer;
import org.apache.beam.sdk.expansion.service.ExpansionService;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.ExplicitBooleanOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Shared code for starting and serving an {@link InMemoryJobService}. */
@SuppressWarnings({
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public abstract class JobServerDriver implements Runnable {

  private static final Logger LOG = LoggerFactory.getLogger(JobServerDriver.class);

  @VisibleForTesting public ServerConfiguration configuration;

  private final ServerFactory jobServerFactory;
  private final ServerFactory artifactServerFactory;
  private final JobInvokerFactory jobInvokerFactory;

  private volatile GrpcFnServer<InMemoryJobService> jobServer;
  private volatile GrpcFnServer<ArtifactStagingService> artifactStagingServer;
  private volatile ExpansionServer expansionServer;

  public interface JobInvokerFactory {
    JobInvoker create();
  }

  protected InMemoryJobService createJobService() throws IOException {
    artifactStagingServer = createArtifactStagingService();
    expansionServer = createExpansionService();

    JobInvoker invoker = jobInvokerFactory.create();
    return InMemoryJobService.create(
        artifactStagingServer,
        this::createSessionToken,
        (String stagingSessionToken) -> {
          if (configuration.cleanArtifactsPerJob) {
            artifactStagingServer.getService().removeStagedArtifacts(stagingSessionToken);
          }
        },
        invoker,
        configuration.getMaxInvocationHistory());
  }

  /** Configuration for the jobServer. */
  public static class ServerConfiguration {
    @Option(name = "--job-host", usage = "The job server host name")
    private String host = "localhost";

    @Option(
        name = "--job-port",
        usage = "The job service port. 0 to use a dynamic port. (Default: 8099)")
    private int port = 8099;

    @Option(
        name = "--artifact-port",
        usage = "The artifact service port. 0 to use a dynamic port. (Default: 8098)")
    private int artifactPort = 8098;

    @Option(
        name = "--expansion-port",
        usage = "The Java expansion service port. 0 to use a dynamic port. (Default: 8097)")
    private int expansionPort = 8097;

    @Option(name = "--artifacts-dir", usage = "The location to store staged artifact files")
    private String artifactStagingPath =
        Paths.get(System.getProperty("java.io.tmpdir"), "beam-artifact-staging").toString();

    @Option(
        name = "--clean-artifacts-per-job",
        usage = "When true, remove each job's staged artifacts when it completes",
        // Allows setting boolean parameters to false which default to true
        handler = ExplicitBooleanOptionHandler.class)
    private boolean cleanArtifactsPerJob = true;

    @Option(name = "--history-size", usage = "The maximum number of completed jobs to keep.")
    private int maxInvocationHistory = 10;

    public String getHost() {
      return host;
    }

    public int getPort() {
      return port;
    }

    public int getArtifactPort() {
      return artifactPort;
    }

    public int getExpansionPort() {<commit_msg>[BEAM-12089] Clarify usage of --artifacts-dir for job servers.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.beam.runners.jobsubmission;

import java.io.IOException;
import java.nio.file.Paths;
import org.apache.beam.model.pipeline.v1.Endpoints;
import org.apache.beam.runners.fnexecution.GrpcFnServer;
import org.apache.beam.runners.fnexecution.ServerFactory;
import org.apache.beam.runners.fnexecution.artifact.ArtifactStagingService;
import org.apache.beam.sdk.expansion.service.ExpansionServer;
import org.apache.beam.sdk.expansion.service.ExpansionService;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.ExplicitBooleanOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Shared code for starting and serving an {@link InMemoryJobService}. */
@SuppressWarnings({
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public abstract class JobServerDriver implements Runnable {

  private static final Logger LOG = LoggerFactory.getLogger(JobServerDriver.class);

  @VisibleForTesting public ServerConfiguration configuration;

  private final ServerFactory jobServerFactory;
  private final ServerFactory artifactServerFactory;
  private final JobInvokerFactory jobInvokerFactory;

  private volatile GrpcFnServer<InMemoryJobService> jobServer;
  private volatile GrpcFnServer<ArtifactStagingService> artifactStagingServer;
  private volatile ExpansionServer expansionServer;

  public interface JobInvokerFactory {
    JobInvoker create();
  }

  protected InMemoryJobService createJobService() throws IOException {
    artifactStagingServer = createArtifactStagingService();
    expansionServer = createExpansionService();

    JobInvoker invoker = jobInvokerFactory.create();
    return InMemoryJobService.create(
        artifactStagingServer,
        this::createSessionToken,
        (String stagingSessionToken) -> {
          if (configuration.cleanArtifactsPerJob) {
            artifactStagingServer.getService().removeStagedArtifacts(stagingSessionToken);
          }
        },
        invoker,
        configuration.getMaxInvocationHistory());
  }

  /** Configuration for the jobServer. */
  public static class ServerConfiguration {
    @Option(name = "--job-host", usage = "The job server host name")
    private String host = "localhost";

    @Option(
        name = "--job-port",
        usage = "The job service port. 0 to use a dynamic port. (Default: 8099)")
    private int port = 8099;

    @Option(
        name = "--artifact-port",
        usage = "The artifact service port. 0 to use a dynamic port. (Default: 8098)")
    private int artifactPort = 8098;

    @Option(
        name = "--expansion-port",
        usage = "The Java expansion service port. 0 to use a dynamic port. (Default: 8097)")
    private int expansionPort = 8097;

    @Option(
        name = "--artifacts-dir",
        usage =
            "The location to store staged artifact files. "
                + "If artifact staging is needed, this directory must be accessible by the execution engine's workers.")
    private String artifactStagingPath =
        Paths.get(System.getProperty("java.io.tmpdir"), "beam-artifact-staging").toString();

    @Option(
        name = "--clean-artifacts-per-job",
        usage = "When true, remove each job's staged artifacts when it completes",
        // Allows setting boolean parameters to false which default to true
        handler = ExplicitBooleanOptionHandler.class)
    private boolean cleanArtifactsPerJob = true;

    @Option(name = "--history-size", usage = "The maximum number of completed jobs to keep.")
    private int maxInvocationHistory = 10;

    public String getHost() {
      return host;
    }

    public int getPort() {
      return port;
    }

    public int getArtifactPort() {
      return artifactPort;
    }

    public int getExpansionPort() {
{'fraction_non_alphanumeric': 0.08808401200171453, 'fraction_numerical': 0.010394342048864124, 'mean_word_length': 3.7017632241813603, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2282496', 'n_tokens_mistral': 2615, 'n_tokens_neox': 2452, 'n_words': 783}