
cluster_name: {{cluster_name}}

# The maximum number of workers nodes to launch in addition to the head node.
max_workers: {{num_nodes - 1}}
upscaling_speed: {{num_nodes - 1}}
idle_timeout_minutes: 60

provider:
  # We use a custom node provider for GCP to support instance stop and reuse.
  type: external  # type: gcp
  module: sky.skylet.providers.gcp.GCPNodeProvider
  region: {{region}}
  availability_zone: {{zones}}
  # Keep (otherwise cannot reuse when re-provisioning).
  # teardown(terminate=True) will override this.
  cache_stopped_nodes: True
  # The GCP project ID.
  project_id: {{gcp_project_id}}
{%- if ports %}
  ports:
{%- for port in ports %}
    - {{port}}
{%- endfor %}
{%- endif %}
{%- if tpu_vm %}
  _has_tpus: True
{%- endif %}
  # Disable launch config check for worker nodes as it can cause resource
  # leakage.
  # Reference: https://github.com/ray-project/ray/blob/cd1ba65e239360c8a7b130f991ed414eccc063ce/python/ray/autoscaler/_private/autoscaler.py#L1115
  # The upper-level SkyPilot code has make sure there will not be resource
  # leakage.
  disable_launch_config_check: true

auth:
  ssh_user: gcpuser
  ssh_private_key: {{ssh_private_key}}

available_node_types:
  ray_head_default:
    resources: {}
    node_config:
      labels:
        skypilot-user: {{ user }}
      {%- if specific_reservations %}
      reservationAffinity:
        consumeReservationType: SPECIFIC_RESERVATION
        key: compute.googleapis.com/reservation-name
        values: {{ specific_reservations }}
      {%- endif %}
{%- if tpu_vm %}
      acceleratorType: {{tpu_type}}
      runtimeVersion: {{runtime_version}}
      metadata:
        # TPU VM's metadata has different format than normal VMs.
        # After replacing the variables, this will become username:ssh_public_key_content.
        # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
        ssh-keys: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
  {%- if use_spot %}
      schedulingConfig:
        preemptible: true
  {%- endif %}
{%- else %}
      machineType: {{instance_type}}
    {%- if machine_image is not none %}
      sourceMachineImage: {{machine_image}}
    {%- endif %}
      disks:
        - boot: true
          autoDelete: true
          type: PERSISTENT
          initializeParams:
            diskSizeGb: {{disk_size}}
            # See https://cloud.google.com/deep-learning-vm/docs/images
          {%- if machine_image is none %}
            sourceImage: {{image_id}}
          {%- endif %}
            diskType: zones/{{zones}}/diskTypes/{{disk_tier}}
  {%- if gpu is not none %}
      guestAccelerators:
        - acceleratorType: projects/{{gcp_project_id}}/zones/{{zones}}/acceleratorTypes/{{gpu}}
          acceleratorCount: {{gpu_count}}
  {%- endif %}
      metadata:
        items:
          - key: ssh-keys
            # After replacing the variables, this will become username:ssh_public_key_content.
            # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
            value: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
  {%- if gpu is not none %}
          - key: install-nvidia-driver
            value: "True"
  {%- endif %}
      scheduling:
  {%- if use_spot %}
        - preemptible: true
  {%- endif %}
  {%- if gpu is not none %}
        - onHostMaintenance: TERMINATE  # Required for GPU-attached VMs.
  {%- endif %}
{%- endif %}
{% if num_nodes - 1 - num_specific_reserved_workers > 0 %}
  ray_worker_default:
    min_workers: {{num_nodes - 1 - num_specific_reserved_workers}}
    max_workers: {{num_nodes - 1 - num_specific_reserved_workers}}
    resources: {}
    node_config:
      labels:
        skypilot-user: {{ user }}
  {%- if tpu_vm %}
      acceleratorType: {{tpu_type}}
      runtimeVersion: {{runtime_version}}
      metadata:
        # TPU VM's metadata has different format than normal VMs.
        # After replacing the variables, this will become username:ssh_public_key_content.
        # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
        ssh-keys: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
    {%- if use_spot %}
      schedulingConfig:
        preemptible: true
    {%- endif %}
  {%- else %}
      machineType: {{instance_type}}
    {%- if machine_image is not none %}
      sourceMachineImage: {{machine_image}}
    {%- endif %}
      disks:
        - boot: true
          autoDelete: true
          type: PERSISTENT
          initializeParams:
            diskSizeGb: {{disk_size}}
            # See https://cloud.google.com/deep-learning-vm/docs/images
          {%- if machine_image is none %}
            sourceImage: {{image_id}}
          {%- endif %}
            diskType: zones/{{zones}}/diskTypes/{{disk_tier}}
    {%- if gpu is not none %}
      guestAccelerators:
        - acceleratorType: projects/{{gcp_project_id}}/zones/{{zones}}/acceleratorTypes/{{gpu}}
          acceleratorCount: {{gpu_count}}
    {%- endif %}
      metadata:
        items:
          - key: ssh-keys
            # After replacing the variables, this will become username:ssh_public_key_content.
            # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
            value: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
    {%- if gpu is not none %}
          - key: install-nvidia-driver
            value: "True"
    {%- endif %}
      scheduling:
    {%- if use_spot %}
        - preemptible: true
    {%- endif %}
    {%- if gpu is not none %}
        - onHostMaintenance: TERMINATE  # Required for GPU-attached VMs.
    {%- endif %}
  {%- endif %}
{%- endif %}

{% if num_specific_reserved_workers > 0 %}
  ray_worker_reserved:
    min_workers: {{num_specific_reserved_workers}}
    max_workers: {{num_specific_reserved_workers}}
    resources: {}
    node_config:
      labels:
        skypilot-user: {{ user }}
      reservationAffinity:
        consumeReservationType: SPECIFIC_RESERVATION
        key: compute.googleapis.com/reservation-name
        values: {{ specific_reservations }}
  {%- if tpu_vm %}
      acceleratorType: {{tpu_type}}
      runtimeVersion: {{runtime_version}}
      metadata:
        # TPU VM's metadata has different format than normal VMs.
        # After replacing the variables, this will become username:ssh_public_key_content.
        # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
        ssh-keys: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
    {%- if use_spot %}
      schedulingConfig:
        preemptible: true
    {%- endif %}
  {%- else %}
      machineType: {{instance_type}}
    {%- if machine_image is not none %}
      sourceMachineImage: {{machine_image}}
    {%- endif %}
      disks:
        - boot: true
          autoDelete: true
          type: PERSISTENT
          initializeParams:
            diskSizeGb: {{disk_size}}
            # See https://cloud.google.com/deep-learning-vm/docs/images
          {%- if machine_image is none %}
            sourceImage: {{image_id}}
          {%- endif %}
            diskType: zones/{{zones}}/diskTypes/{{disk_tier}}
    {%- if gpu is not none %}
      guestAccelerators:
        - acceleratorType: projects/{{gcp_project_id}}/zones/{{zones}}/acceleratorTypes/{{gpu}}
          acceleratorCount: {{gpu_count}}
    {%- endif %}
      metadata:
        items:
          - key: ssh-keys
            # After replacing the variables, this will become username:ssh_public_key_content.
            # This is a specific syntax required by GCP https://cloud.google.com/compute/docs/connect/add-ssh-keys
            value: |
              skypilot:ssh_user:skypilot:ssh_public_key_content
    {%- if gpu is not none %}
          - key: install-nvidia-driver
            value: "True"
    {%- endif %}
      scheduling:
    {%- if use_spot %}
        - preemptible: true
    {%- endif %}
    {%- if gpu is not none %}
        - onHostMaintenance: TERMINATE  # Required for GPU-attached VMs.
    {%- endif %}
  {%- endif %}
{%- endif %}

head_node_type: ray_head_default

# Format: `REMOTE_PATH : LOCAL_PATH`
file_mounts: {
  "{{sky_ray_yaml_remote_path}}": "{{sky_ray_yaml_local_path}}",
  "{{sky_remote_path}}/{{sky_wheel_hash}}": "{{sky_local_path}}",
{%- for remote_path, local_path in credentials.items() %}
  "{{remote_path}}": "{{local_path}}",
{%- endfor %}
}

rsync_exclude: []

initialization_commands: []

# List of shell commands to run to set up nodes.
# NOTE: these are very performance-sensitive. Each new item opens/closes an SSH
# connection, which is expensive. Try your best to co-locate commands into fewer
# items!
#
# Increment the following for catching performance bugs easier:
#   current num items (num SSH connections): 1  (+1 if tpu_vm)
setup_commands:
  # Disable `unattended-upgrades` to prevent apt-get from hanging. It should be called at the beginning before the process started to avoid being blocked. (This is a temporary fix.)
  # Line 'mkdir -p ..': Create ~/.ssh/config file in case the file does not exist in the custom image.
  # Line 'which conda ..': some images (TPU VM) do not install conda by
  # default. 'source ~/.bashrc' is needed so conda takes effect for the next
  # commands.
  # Line 'sudo bash ..': set the ulimit as suggested by ray docs for performance. https://docs.ray.io/en/latest/cluster/vms/user-guides/large-cluster-best-practices.html#system-configuration
  # Line 'sudo grep ..': set the number of threads per process to unlimited to avoid ray job submit stucking issue when the number of running ray jobs increase.
  # Line 'mkdir -p ..': disable host key check
  # Line 'python3 -c ..': patch the buggy ray files and enable `-o allow_other` option for `goofys`
  - function mylsof { p=$(for pid in /proc/{0..9}*; do i=$(basename "$pid"); for file in "$pid"/fd/*; do link=$(readlink -e "$file"); if [ "$link" = "$1" ]; then echo "$i"; fi; done; done); echo "$p"; };
    sudo systemctl stop unattended-upgrades || true;
    sudo systemctl disable unattended-upgrades || true;
    sudo sed -i 's/Unattended-Upgrade "1"/Unattended-Upgrade "0"/g' /etc/apt/apt.conf.d/20auto-upgrades || true;
    p=$(mylsof "/var/lib/dpkg/lock-frontend"); echo "$p";
    sudo kill -9 `echo "$p" | tail -n 1` || true;
    sudo rm /var/lib/dpkg/lock-frontend;
    sudo pkill -9 dpkg;
    sudo pkill -9 apt-get;
    sudo dpkg --configure --force-overwrite -a;
    mkdir -p ~/.ssh; touch ~/.ssh/config;
    {{ conda_installation_commands }}
    (type -a python | grep -q python3) || echo 'alias python=python3' >> ~/.bashrc;
    (type -a pip | grep -q pip3) || echo 'alias pip=pip3' >> ~/.bashrc;
    source ~/.bashrc;
  {%- if tpu_vm %}
    test -f /home/gcpuser/miniconda3/etc/profile.d/conda.sh && source /home/gcpuser/miniconda3/etc/profile.d/conda.sh && conda activate base || true;
    pip3 install --upgrade google-api-python-client;
  {%- endif %}
    (pip3 list | grep "ray " | grep {{ray_version}} 2>&1 > /dev/null || pip3 install --exists-action w -U ray[default]=={{ray_version}}) && mkdir -p ~/sky_workdir && mkdir -p ~/.sky/sky_app;
    (pip3 list | grep "skypilot " && [ "$(cat {{sky_remote_path}}/current_sky_wheel_hash)" == "{{sky_wheel_hash}}" ]) || (pip3 uninstall skypilot -y; pip3 install "$(echo {{sky_remote_path}}/{{sky_wheel_hash}}/skypilot-{{sky_version}}*.whl)[gcp]" && echo "{{sky_wheel_hash}}" > {{sky_remote_path}}/current_sky_wheel_hash || exit 1);
    sudo bash -c 'rm -rf /etc/security/limits.d; echo "* soft nofile 1048576" >> /etc/security/limits.conf; echo "* hard nofile 1048576" >> /etc/security/limits.conf';
    sudo grep -e '^DefaultTasksMax' /etc/systemd/system.conf || (sudo bash -c 'echo "DefaultTasksMax=infinity" >> /etc/systemd/system.conf'); sudo systemctl set-property user-$(id -u $(whoami)).slice TasksMax=infinity; sudo systemctl daemon-reload;
    mkdir -p ~/.ssh; (grep -Pzo -q "Host \*\n  StrictHostKeyChecking no" ~/.ssh/config) || printf "Host *\n  StrictHostKeyChecking no\n" >> ~/.ssh/config;
    python3 -c "from sky.skylet.ray_patches import patch; patch()" || exit 1;
    [ -f /etc/fuse.conf ] && sudo sed -i 's/#user_allow_other/user_allow_other/g' /etc/fuse.conf || (sudo sh -c 'echo "user_allow_other" > /etc/fuse.conf');

# Command to start ray on the head node. You don't need to change this.
# NOTE: these are very performance-sensitive. Each new item opens/closes an SSH
# connection, which is expensive. Try your best to co-locate commands into fewer
# items! The same comment applies for worker_start_ray_commands.
#
# Increment the following for catching performance bugs easier:
#   current num items (num SSH connections): 1
head_start_ray_commands:
  # NOTE: --disable-usage-stats in `ray start` saves 10 seconds of idle wait.
  # Line "which prlimit ..": increase the limit of the number of open files for the raylet process, as the `ulimit` may not take effect at this point, because it requires
  # all the sessions to be reloaded. This is a workaround.
  - export SKYPILOT_NUM_GPUS=0 && which nvidia-smi > /dev/null && SKYPILOT_NUM_GPUS=$(nvidia-smi --query-gpu=index,name --format=csv,noheader | wc -l);
    ray stop; RAY_SCHEDULER_EVENTS=0 RAY_DEDUP_LOGS=0 ray start --disable-usage-stats --head --port={{ray_port}} --dashboard-port={{ray_dashboard_port}} --object-manager-port=8076 --autoscaling-config=~/ray_bootstrap_config.yaml {{"--resources='%s'" % custom_resources if custom_resources}} --num-gpus=$SKYPILOT_NUM_GPUS --temp-dir {{ray_temp_dir}} || exit 1;
    which prlimit && for id in $(pgrep -f raylet/raylet); do sudo prlimit --nofile=1048576:1048576 --pid=$id || true; done;
    {{dump_port_command}};

# Worker commands are needed for TPU VM Pods
{%- if num_nodes > 1 or tpu_vm %}
worker_start_ray_commands:
  - SKYPILOT_NUM_GPUS=0 && which nvidia-smi > /dev/null && SKYPILOT_NUM_GPUS=$(nvidia-smi --query-gpu=index,name --format=csv,noheader | wc -l);
    ray stop; RAY_SCHEDULER_EVENTS=0 RAY_DEDUP_LOGS=0 ray start --disable-usage-stats --address=$RAY_HEAD_IP:{{ray_port}} --object-manager-port=8076 {{"--resources='%s'" % custom_resources if custom_resources}} --num-gpus=$SKYPILOT_NUM_GPUS --temp-dir {{ray_temp_dir}} || exit 1;
    which prlimit && for id in $(pgrep -f raylet/raylet); do sudo prlimit --nofile=1048576:1048576 --pid=$id || true; done;
{%- else %}
worker_start_ray_commands: []
{%- endif %}

head_node: {}
worker_nodes: {}

# These fields are required for external cloud providers.
head_setup_commands: []
worker_setup_commands: []
cluster_synced_files: []
file_mounts_sync_continuously: False
