Class: OodCore::Job::Adapters::Slurm::Batch Private

Inherits:
Object
  • Object
show all
Defined in:
lib/ood_core/job/adapters/slurm.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Object used for simplified communication with a Slurm batch server

Defined Under Namespace

Classes: Error, SlurmTimeoutError

Constant Summary collapse

UNIT_SEPARATOR =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

"\x1F"
RECORD_SEPARATOR =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

"\x1E"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cluster: nil, bin: nil, conf: nil, bin_overrides: {}, submit_host: "", strict_host_checking: true, id: 'unknown') ⇒ Batch

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Batch.

Parameters:

  • cluster (#to_s, nil) (defaults to: nil) —

    the cluster name

  • conf (#to_s, nil) (defaults to: nil) —

    path to the slurm conf

  • bin (#to_s) (defaults to: nil) —

    path to slurm installation binaries

  • bin_overrides (#to_h) (defaults to: {}) —

    a hash of bin ovverides to be used in job

  • submit_host (#to_s) (defaults to: "") —

    Submits the job on a login node via ssh

  • strict_host_checking (Bool) (defaults to: true) —

    Whether to use strict host checking when ssh to submit_host



152
153
154
155
156
157
158
159
160
# File 'lib/ood_core/job/adapters/slurm.rb', line 152

def initialize(cluster: nil, bin: nil, conf: nil, bin_overrides: {}, submit_host: "", strict_host_checking: true, id: 'unknown')
  @cluster              = cluster && cluster.to_s
  @conf                 = conf    && Pathname.new(conf.to_s)
  @bin                  = Pathname.new(bin.to_s)
  @bin_overrides        = bin_overrides
  @submit_host          = submit_host.to_s
  @strict_host_checking = strict_host_checking
  @id                   = id.to_s
end

Instance Attribute Details

#bin ⇒ Pathname (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The path to the Slurm client installation binaries

Examples:

For Slurm 10.0.0

my_batch.bin.to_s #=> "/usr/local/slurm/10.0.0/bin

Returns:

  • (Pathname) —

    path to slurm binaries



116
117
118
# File 'lib/ood_core/job/adapters/slurm.rb', line 116

def bin
  @bin
end

#bin_overrides ⇒ Object (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Optional overrides for Slurm client executables

Examples:

{'sbatch' => '/usr/local/bin/sbatch'}


122
123
124
# File 'lib/ood_core/job/adapters/slurm.rb', line 122

def bin_overrides
  @bin_overrides
end

#cluster ⇒ String? (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The cluster of the Slurm batch server

Examples:

CHPC's kingspeak cluster

my_batch.cluster #=> "kingspeak"

Returns:

  • (String, nil) —

    the cluster name



104
105
106
# File 'lib/ood_core/job/adapters/slurm.rb', line 104

def cluster
  @cluster
end

#conf ⇒ Pathname? (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The path to the Slurm configuration file

Examples:

For Slurm 10.0.0

my_batch.conf.to_s #=> "/usr/local/slurm/10.0.0/etc/slurm.conf

Returns:

  • (Pathname, nil) —

    path to slurm conf



110
111
112
# File 'lib/ood_core/job/adapters/slurm.rb', line 110

def conf
  @conf
end

#id ⇒ String (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The ID of the cluster.

Examples:

oakley

Returns:

  • (String) —

    ; The ID of the cluster.



137
138
139
# File 'lib/ood_core/job/adapters/slurm.rb', line 137

def id
  @id
end

#strict_host_checking ⇒ Bool (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Wheter to use strict host checking when ssh to submit_host

Examples:

false

Returns:

  • (Bool) —

    ; true if empty



132
133
134
# File 'lib/ood_core/job/adapters/slurm.rb', line 132

def strict_host_checking
  @strict_host_checking
end

#submit_host ⇒ String (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The login node where the job is submitted via ssh

Examples:

owens.osc.edu

Returns:

  • (String) —

    The login node



127
128
129
# File 'lib/ood_core/job/adapters/slurm.rb', line 127

def submit_host
  @submit_host
end

Instance Method Details

#accounts ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



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
# File 'lib/ood_core/job/adapters/slurm.rb', line 244

def accounts
  user = Etc.getlogin
  args = [ 
          '-nP', 'show', 'users', 'withassoc', 'format=account,qos', 
          'where', "user=#{user}", "cluster=#{id}"
         ]

  [].tap do |associations|
    call('sacctmgr', *args).each_line do |line|
      acct, qos = line.split('|')
      next if acct.nil? || acct.chomp.empty?

      associations << {
        name: acct,
        qos: qos.to_s.chomp.split(','),
        cluster: id
      }
    end
  end.group_by do |x|
    [x[:name], x[:cluster]]
  end.map do |(name, cluster), assocs|
    OodCore::Job::AccountInfo.new(
      name: name,
      cluster: cluster,
      qos: (assocs.flat_map { |x| x[:qos] }).uniq,
    )
  end
end

#all_sinfo_node_fields ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



448
449
450
451
452
453
454
# File 'lib/ood_core/job/adapters/slurm.rb', line 448

def all_sinfo_node_fields
  {
    procs: '%c',
    name: '%n',
    features: '%f'
  }
end

#all_squeue_fields ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Fields requested from a formatted squeue call Note that the order of these fields is important



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/ood_core/job/adapters/slurm.rb', line 341

def all_squeue_fields
  {
    account: 'Account',
    job_id: 'JobID',
    exec_host: 'BatchHost',
    min_cpus: 'MinCpus',
    cpus: 'NumCPUs',
    min_tmp_disk: 'MinTmpDisk',
    nodes: 'NumNodes',
    end_time: 'EndTime',
    dependency: 'Dependency',
    features: 'Feature',
    array_job_id: 'ArrayJobID',
    group_name: 'GroupName',
    group_id: 'GroupID',
    over_subscribe: 'OverSubscribe',
    sockets_per_node: 'Sockets',
    array_job_task_id: 'JobArrayID',
    cores_per_socket: 'Cores',
    job_name: 'Name',
    threads_per_core: 'Threads',
    comment: 'Comment',
    array_task_id: 'ArrayTaskID',
    time_limit: 'TimeLimit',
    time_left: 'TimeLeft',
    min_memory: 'MinMemory',
    time_used: 'TimeUsed',
    req_node: 'ReqNodes',
    node_list: 'NodeList',
    command: 'Command',
    contiguous: 'Contiguous',
    qos: 'QOS',
    partition: 'Partition',
    priority: 'PriorityLong',
    reason: 'Reason',
    start_time: 'StartTime',
    state_compact: 'StateCompact',
    state: 'State',
    user: 'UserName',
    user_id: 'UserID',
    reservation: 'Reservation',
    submit_time: 'SubmitTime',
    wckey: 'WCKey',
    licenses: 'Licenses',
    excluded_nodes: 'ExcNodes',
    core_specialization: 'CoreSpec',
    nice: 'Nice',
    scheduled_nodes: 'SchedNodes',
    sockets_cores_threads: 'SCT',
    work_dir: 'WorkDir',
    tres_alloc: 'tres-alloc',
    gres: 'tres-per-node',  # must come at the end to fix a bug with Slurm 18
  }
end

#delete_job(id) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Delete a specified job from batch server

Examples:

Delete job "1234"

my_batch.delete_job("1234")

Parameters:

  • id (#to_s) —

    the id of the job

Raises:

  • (Error) —

    if scancel command exited unsuccessfully



323
324
325
# File 'lib/ood_core/job/adapters/slurm.rb', line 323

def delete_job(id)
  call("scancel", id.to_s)
end

#get_cluster_info ⇒ ClusterInfo

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Get a ClusterInfo object containing information about the given cluster

Returns:



164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/ood_core/job/adapters/slurm.rb', line 164

def get_cluster_info
  node_cpu_info = call("sinfo", "-aho %F/%C").strip.split('/').map(&:to_i)
  gres_lines = call("sinfo", "-ahNO", "nodehost:100,gres:512,gresused:512,statelong")
               .lines.uniq.reject { |line| line.match?(/maint|drain|down/i) }.map(&:split)

  node_info = sinfo_headers.zip(node_cpu_info).to_h
  ClusterInfo.new(active_nodes: node_info['nodes_allocated'],
                  total_nodes: node_info['nodes_total'],
                  active_processors: node_info['cpus_allocated'],
                  total_processors: node_info['cpus_total'],
                  active_gpus: gres_lines.sum { |line| Slurm.gpus_from_gres(line[2]) },
                  total_gpus: gres_lines.sum { |line| Slurm.gpus_from_gres(line[1]) }
  )
end

#get_jobs(id: "", owner: nil, attrs: nil) ⇒ Array<Hash>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Get a list of hashes detailing each of the jobs on the batch server

Examples:

Status info for all jobs

my_batch.get_jobs
#=>
#[
#  {
#    :account => "account",
#    :job_id => "my_job",
#    ...
#  },
#  {
#    :account => "account",
#    :job_id => "my_other_job",
#    ...
#  },
#  ...
#]

Parameters:

  • id (#to_s) (defaults to: "") —

    the id of the job

  • owner (String) (defaults to: nil) —

    the owner(s) of the job

  • attrs (Array<Symbol>, nil) (defaults to: nil) —

    list of attributes request when calling squeue

Returns:

  • (Array<Hash>) —

    list of details for jobs

Raises:

  • (Error) —

    if squeue command exited unsuccessfully



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
# File 'lib/ood_core/job/adapters/slurm.rb', line 208

def get_jobs(id: "", owner: nil, attrs: nil)
  fields = squeue_fields(attrs)
  args = squeue_args(id: id, owner: owner, options: fields.values)

  #TODO: switch mock of Open3 to be the squeue mock script
  # then you can use that for performance metrics
  StringIO.open(call("squeue", *args)) do |output|
    advance_past_squeue_header!(output)

    jobs = []
    output.each_line do |line|
      # TODO: once you can do performance metrics you can test zip against some other tools
      # or just small optimizations
      # for example, fields is ALREADY A HASH and we are setting the VALUES to
      # "line.strip.split(unit_separator)" array
      #
      # i.e. store keys in an array, do Hash[[keys, values].transpose]
      #
      # or
      #
      # job = {}
      # keys.each_with_index { |key, index| [key] = values[index] }
      # jobs << job
      #
      # assuming keys and values are same length! if not we have an error!
      line = line.encode('UTF-8', invalid: :replace, undef: :replace)
      values = line.chomp("\n").split(UNIT_SEPARATOR)
      jobs << Hash[fields.keys.zip(values)] unless values.empty?
    end
    jobs
  end
rescue SlurmTimeoutError
  # TODO: could use a log entry here
  return [{ id: id, state: 'undetermined' }]
end

#hold_job(id) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Put a specified job on hold

Examples:

Put job "1234" on hold

my_batch.hold_job("1234")

Parameters:

  • id (#to_s) —

    the id of the job

Raises:

  • (Error) —

    if scontrol command exited unsuccessfully



303
304
305
# File 'lib/ood_core/job/adapters/slurm.rb', line 303

def hold_job(id)
  call("scontrol", "hold", id.to_s)
end

#nodes ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/ood_core/job/adapters/slurm.rb', line 456

def nodes
  args = all_sinfo_node_fields.values.join(UNIT_SEPARATOR)
  output = call('sinfo', '-ho', "#{RECORD_SEPARATOR}#{args}")

  output.each_line(RECORD_SEPARATOR).map do |line|
    values = line.chomp(RECORD_SEPARATOR).strip.split(UNIT_SEPARATOR)

    next if values.empty?

    data = Hash[all_sinfo_node_fields.keys.zip(values)]
    data[:name] = data[:name].to_s.split(',').first
    data[:features] = data[:features].to_s.split(',')
    NodeInfo.new(**data)
  end.compact
end

#queues ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



438
439
440
441
442
443
444
445
446
# File 'lib/ood_core/job/adapters/slurm.rb', line 438

def queues
  info_raw = call('scontrol', 'show', 'part', '-o')

  [].tap do |ret_arr|
    info_raw.each_line do |line|
      ret_arr << str_to_queue_info(line)
    end
  end
end

#release_job(id) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Release a specified job that is on hold

Examples:

Release job "1234" from on hold

my_batch.release_job("1234")

Parameters:

  • id (#to_s) —

    the id of the job

Raises:

  • (Error) —

    if scontrol command exited unsuccessfully



313
314
315
# File 'lib/ood_core/job/adapters/slurm.rb', line 313

def release_job(id)
  call("scontrol", "release", id.to_s)
end

#sacct_info(job_ids, states, from, to, show_steps) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/ood_core/job/adapters/slurm.rb', line 472

def sacct_info(job_ids, states, from, to, show_steps)
  # https://slurm.schedmd.com/sacct.html
  fields = sacct_info_fields
  args = ['-P'] # Output will be delimited
  args.concat ['--delimiter', UNIT_SEPARATOR]
  args.concat ['-n'] # No header
  args.concat ['--units', 'G'] # Memory units in GB
  args.concat ['--allocations'] unless show_steps # Show statistics relevant to the job, not taking steps into consideration
  args.concat ['-o', fields.values.join(',')] # Required data
  args.concat ['--state', states.join(',')] unless states.empty? # Filter by these states
  args.concat ['-j', job_ids.join(',')] unless job_ids.empty? # Filter by these job ids
  args.concat ['-S', from] if from # Filter from This date
  args.concat ['-E', to] if to # Filter until this date

  jobs_info = []
  StringIO.open(call('sacct', *args)) do |output|
    output.each_line do |line|
      # Replace blank values with nil
      values = line.strip.split(UNIT_SEPARATOR).map{ |value| value.to_s.empty? ? nil : value }
      jobs_info << Hash[fields.keys.zip(values)] unless values.empty?
    end
  end
  jobs_info
end

#sacct_info_fields ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Job info fields requested from a formatted sacct call



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/ood_core/job/adapters/slurm.rb', line 397

def sacct_info_fields
  {
    # The user name of the user who ran the job.
    user: 'User',
    # The group name of the user who ran the job.
    group_name: 'Group',
    # Job Id for reference
    job_id: 'JobId',
    # The name of the job or job step
    job_name: 'JobName',
    # The job's elapsed time.
    elapsed: 'Elapsed',
    # Minimum required memory for the job
    req_mem: 'ReqMem',
    # Count of allocated CPUs
    alloc_cpus: 'AllocCPUS',
    # Number of requested CPUs.
    req_cpus: 'ReqCPUS',
    # What the timelimit was/is for the job
    time_limit: 'Timelimit',
    # Displays the job status, or state
    state: 'State',
    # The sum of the SystemCPU and UserCPU time used by the job or job step
    total_cpu: 'TotalCPU',
    # Maximum resident set size of all tasks in job.
    max_rss: 'MaxRSS',
    # Identifies the partition on which the job ran.
    partition: 'Partition',
    # The time the job was submitted. In the same format as End.
    submit_time: 'Submit',
    # Initiation time of the job. In the same format as End.
    start_time: 'Start',
    # Termination time of the job.
    end: 'End',
    # Trackable resources. These are the minimum resource counts requested by the job/step at submission time.
    gres: 'ReqTRES',
    # Trackable resources actually allocated to the job/step.
    tres_alloc: 'AllocTRES'
  }
end

#sinfo_headers ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



179
180
181
182
183
184
# File 'lib/ood_core/job/adapters/slurm.rb', line 179

def sinfo_headers
  [
    'nodes_allocated', 'nodes_idle', 'nodes_other', 'nodes_total',
    'cpus_allocated', 'cpus_idle', 'cpus_other', 'cpus_total'
  ]
end

#squeue_args(id: "", owner: nil, options: []) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

TODO: write some barebones test for this? like 2 options and id or no id



289
290
291
292
293
294
295
# File 'lib/ood_core/job/adapters/slurm.rb', line 289

def squeue_args(id: "", owner: nil, options: [])
  args  = ["--all", "--states=all", "--noconvert"]
  args.concat ["-O", options.push(nil).join(":#{UNIT_SEPARATOR},")]
  args.concat ["-u", owner.to_s] unless owner.to_s.empty?
  args.concat ["-j", id.to_s] unless id.to_s.empty?
  args
end

#squeue_fields(attrs) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



273
274
275
276
277
278
279
# File 'lib/ood_core/job/adapters/slurm.rb', line 273

def squeue_fields(attrs)
  if attrs.nil?
    all_squeue_fields
  else
    all_squeue_fields.slice(*squeue_attrs_for_info_attrs(Array.wrap(attrs) + squeue_required_fields))
  end
end

#squeue_required_fields ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



281
282
283
284
285
286
# File 'lib/ood_core/job/adapters/slurm.rb', line 281

def squeue_required_fields
  #TODO: does this need to include ::array_job_task_id?
  #TODO: does it matter that order of the output can vary depending on the arguments and if "squeue_required_fields" are included?
  # previously the order was "fields.keys"; i don't think it does
  [:job_id, :state_compact]
end

#submit_string(str, args: [], env: {}) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Submit a script expanded as a string to the batch server

Parameters:

  • str (#to_s) —

    script as a string

  • args (Array<#to_s>) (defaults to: []) —

    arguments passed to sbatch command

  • env (Hash{#to_s => #to_s}) (defaults to: {}) —

    environment variables set

Returns:

  • (String) —

    the id of the job that was created

Raises:

  • (Error) —

    if sbatch command exited unsuccessfully



333
334
335
336
337
# File 'lib/ood_core/job/adapters/slurm.rb', line 333

def submit_string(str, args: [], env: {})
  args = args.map(&:to_s) + ["--parsable"]
  env = env.to_h.each_with_object({}) { |(k, v), h| h[k.to_s] = v.to_s }
  call("sbatch", *args, env: env, stdin: str.to_s).strip.split(";").first
end