pika_slurm_env_redis.py 6.71 KB
Newer Older
Frank Winkler's avatar
Frank Winkler committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#!/usr/bin/env python

import redis
import _pickle as cPickle
import sys
import ast
import os
import time
import pwd

import argparse

from time import sleep
from itertools import count, groupby

def list_to_ranges(L):
   G=(list(x) for _,x in groupby(L, lambda x,c=count(): next(c)-x))
   return ",".join("-".join(map(str,(g[0],g[-1])[:len(g)])) for g in G)

def main(job_id, debug_path, env_file, force):

  redis_host = os.environ["REDIS_HOST"]
  connection = redis.StrictRedis(host=redis_host, port=6379, socket_timeout=10, socket_connect_timeout=10)

  debug_file = None
  if debug_path:
    debug_file_path = debug_path + "/memcache_" + str(job_id)
    debug_file = open(debug_file_path,'w')
    debug_file.write("debug before: {0} {1}\n".format(job_id, time.time()))

31 32 33 34 35 36 37
  slurm_env_string = None
  haveConnectionError = False
  try:
    slurm_env_string = connection.get("prope_" + str(job_id))
  except: # redis.exceptions.TimeoutError:
    haveConnectionError = True
    
Frank Winkler's avatar
Frank Winkler committed
38 39
  t = 0
  while slurm_env_string == None and t < 10:
40 41 42 43 44 45
    try:
      slurm_env_string = connection.get("prope_" + str(job_id))
    except: # redis.exceptions.TimeoutError:
      haveConnectionError = True
      continue
    
Frank Winkler's avatar
Frank Winkler committed
46
    sleep(1)
47
    t = t + 1    
Frank Winkler's avatar
Frank Winkler committed
48 49

  #pprint(slurm_env_string)
50 51 52 53
  if debug_file:
    if haveConnectionError:
      debug_file.write("Redis connection error ocurred!\n")
    debug_file.write("Connection attemps = {:d}\n".format(t))
Frank Winkler's avatar
Frank Winkler committed
54 55 56 57 58 59 60 61
    debug_file.write("debug after: {0} {1}\n".format(job_id, time.time()))
    #f.close()

  # decode the job info
  slurm_env = {}
  if slurm_env_string and len(str(slurm_env_string)) > 0:
    try:
      slurm_env = cPickle.loads(slurm_env_string)
62
      #print(slurm_env)
Frank Winkler's avatar
Frank Winkler committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    except:
      slurm_env = {}

  if debug_path and debug_file:
    if slurm_env:
      debug_file.write(str(slurm_env))
    else:
      debug_file.write(str(slurm_env_string))

  # check if this job is exclusive and no monitoring is requested 
  monitoring_on = -1
  if slurm_env:
    nodes_shared = str(slurm_env['shared'])

    if nodes_shared == "OK":
      monitoring_on = 1
    else:
      #check no_monitoring comment
      slurm_comment = str(slurm_env['comment'])
      if 'no_monitoring' in slurm_comment:
         monitoring_on = 0
      else:
         monitoring_on = 1

  # if env file is given and (forced or job should be monitored)
  if env_file and (force or monitoring_on != 0):
    save_job_env(env_file, slurm_env, connection, debug_file)

  # print result as return value of the script
  print(monitoring_on)

    
def save_job_env(env_file, slurm_env, connection, debug_file):
  # set default values
  start_time = 0
  work_dir = "'n/a'"
  exclusive = 0
  partition_name = "'n/a'"
  job_name = "'n/a'"
  walltime = 0
  walltime_formatted = "'n/a'"
  cpu_allocated = "'n/a'"
  job_array_id = "None"
  account = "'n/a'"
  num_cores = 0

  job_user = None
  if "SLURM_JOB_USER" in os.environ:
    job_user = os.environ["SLURM_JOB_USER"]

  # get selected job information
  if slurm_env:
    start_time = str(slurm_env['start_time'])
    partition_name = str(slurm_env['partition'])
    nodes_shared = str(slurm_env['shared'])
    work_dir = str(slurm_env['work_dir'])

    if nodes_shared == "OK":
        total_cpus_allocated = int(slurm_env['num_cpus'])
        node_count = int(slurm_env['num_nodes'])

        #print "Shared: " + str(total_cpus_allocated / node_count) + " cpus per node on partition " + partition_name

        # get partition data
        partition_data_string = connection.get(partition_name)
        partition_data = cPickle.loads(partition_data_string)
        #partition_data = ast.literal_eval(str(partition_data_string))
130 131 132 133 134 135
        try:
          cpus_avail = int(partition_data['max_cpus_per_node'])
          #print(str(partition_data))
        except:
          cpus_avail = -1
          #print(str(partition_data))
Frank Winkler's avatar
Frank Winkler committed
136 137 138 139 140 141 142 143 144 145

        if (total_cpus_allocated / node_count) == cpus_avail:
          #print "Exclusive with " + str(total_cpus_allocated / node_count) + " cpus per node on partition " + partition_name
          exclusive = 1
    else:
        #print "Exclusive flag set by user"
        exclusive = 1

    cpu_allocated = ''
    if exclusive == 0:
Frank Winkler's avatar
Frank Winkler committed
146
        for key, value in slurm_env['cpus_alloc_layout'].items():
Frank Winkler's avatar
Frank Winkler committed
147 148 149 150 151 152 153 154 155 156 157 158 159
          cpu_allocated += str(key) + str('[') + str(list_to_ranges(value)) + str('],')

        #remove last comma from string
        cpu_allocated = cpu_allocated[:-1]

    try:
        job_name = str(slurm_env['name'])
    except:
        job_name = 'corrupt'

    #determine job user
    if not job_user:
      job_user = pwd.getpwuid(slurm_env['user_id']).pw_name
fwinkler's avatar
fwinkler committed
160 161 162 163 164 165 166 167
   
    try:
        walltime = slurm_env['time_limit']
    except:
        walltime = 0
    
    #convert walltime from minutes to seconds
    walltime *= 60
Frank Winkler's avatar
Frank Winkler committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    
    walltime_formatted = slurm_env['time_limit_str']
    job_array_id = slurm_env['array_job_id']

    #determine account
    account = str(slurm_env['account'])

    #determine number of cores
    num_cores = str(slurm_env['num_cpus'])

  if env_file:
    f = open(env_file,'w')

    print( "#!/bin/bash", file=f )
    print( "export PIKA_JOB_START=" + str(start_time), file=f )
    print( "export PIKA_JOB_USER=" + str(job_user), file=f )
    print( "export PIKA_JOB_EXCLUSIVE=" + str(exclusive), file=f )
    print( "export PIKA_JOB_PARTITION=" + partition_name, file=f )
    print( "export PIKA_JOB_NAME='" + job_name + "'", file=f )
    print( "export PIKA_JOB_WALLTIME=" + str(walltime), file=f )
    print( "export PIKA_JOB_WALLTIME_FORMATTED=" + str(walltime_formatted), file=f )
    print( "export PIKA_JOB_CPUS_ALLOCATED=" + str(cpu_allocated), file=f )
    print( "export PIKA_JOB_ARRAY_ID=" + str(job_array_id), file=f )
    print( "export PIKA_JOB_ACCOUNT=" + str(account), file=f )
    print( "export PIKA_JOB_NUM_CORES=" + str(num_cores), file=f )
    print( "export PIKA_JOB_WORK_DIR=" + str(work_dir), file=f )

    f.close()

  if debug_file:
    debug_file.write("\nReservation: " + str(exclusive))
    debug_file.write("\nPartition: " + partition_name)
    debug_file.write("\nJob Name: " + str(slurm_env['name']))
    debug_file.write("\nWalltime: " + str(slurm_env['time_limit']))
    #debug_file.write("\n" + str(cpu_allocated))
    debug_file.write("\n\n")

    debug_file.close()

def parse_args():
   parser = argparse.ArgumentParser()
   parser.add_argument('--jobid', type=int, required=True)
   parser.add_argument('--debug_path', type=str, required=False)
   parser.add_argument('--env_file', type=str, required=False)
   parser.add_argument('--force', action="store_true", default=False, help='force request for job meta data')
   
   return parser.parse_args()

if __name__ == '__main__':
   args = parse_args()
   main(job_id=args.jobid,
        debug_path=args.debug_path,
        env_file=args.env_file,
        force=args.force)