source: TOOLS/ConsoGENCMIP6/bin/conso_gencmip6.py @ 2421

Last change on this file since 2421 was 2421, checked in by labetoulle, 9 years ago

copy plots on dods

  • Property svn:executable set to *
File size: 9.6 KB
RevLine 
[2412]1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
[2411]3
[2412]4# this must come first
5from __future__ import print_function, unicode_literals, division
[2411]6
[2412]7# standard library imports
8from argparse import ArgumentParser
[2413]9import json
10import shutil
11import os
[2412]12import os.path
[2413]13import subprocess
14# import datetime as dt
[2411]15
[2413]16# Application library imports
17from gencmip6 import *
18from gencmip6_path import *
[2411]19
[2413]20
[2412]21########################################
[2413]22def get_storedir(login):
[2411]23
[2413]24  command = ["ccc_home", "-A", "-u", login]
25  try :
26    res = subprocess.check_output(command)
[2421]27  except Exception as rc:
28    print(rc)
[2413]29    res = None
30
31  return res
32
33
34########################################
35def get_dirsize(dirname):
36
37  command = ["du", "-sbh", dirname]
38  try :
[2421]39    res = subprocess.check_output(command)
40    res = res.split()[0]
41
[2413]42  except Exception as rc :
43    print(rc)
44    res = None
45
46  return res
47
48
49# ########################################
50# def get_dirlist(dirname):
51
52
53#   return output
54
55
56########################################
57def parse_myproject(filename):
58
59  project = {}
60  project["project"] = "gencmip6"
[2412]61  logins  = {}
[2411]62
[2413]63  if where_we_run() == "curie":
64    try :
65      res = subprocess.check_output("ccc_myproject")
66    except Exception as rc :
67      print(rc)
68      exit()
[2421]69    with open(os.path.join(DIR["DATA"], OUT["CCCMP"]), "w") as fileout:
[2413]70      fileout.write(res)
71
[2412]72  with open(filename, "r") as filein:
73    # Skip lines until we find project name.
74    # Then extract script date
75    for ligne in filein:
76      if project["project"] in ligne:
77        today = ligne.split()[-1]
[2413]78        today = string_to_date(today)
79
[2412]80        break
[2411]81
[2412]82    # Skip next two lines : first is blank and second is login titles
83    for _ in xrange(1):
84      next(filein)
[2411]85
[2413]86    # Login list, until blank line
[2412]87    for ligne in filein:
88      if not ligne.strip():
89        break
90      login, conso = ligne.split()
91      logins[login] = float(conso)
[2411]92
[2413]93    # Skip until we find consumed time (hours)
[2412]94    for ligne in filein:
95      if "Total" in ligne:
96        total = float(ligne.split()[-1])
97        break
[2411]98
[2413]99    # Skip until we find allocated time (hours)
[2412]100    for ligne in filein:
101      if "Allocated" in ligne:
102        project["alloc"] = float(ligne.split()[-1])
103        break
[2411]104
[2413]105    # Skip until we find theoratical use (%)
[2412]106    for ligne in filein:
107      if "Suggested use at this time" in ligne:
108        utheo = float(ligne.split()[-1].strip("%"))
109        break
[2411]110
[2413]111    # Skip until we find real use (%)
[2412]112    for ligne in filein:
113      if "Real use at this time" in ligne:
114        ureal = float(ligne.split()[-1].strip("%"))
115        break
[2411]116
[2413]117    # Skip until we find deadline
[2412]118    for ligne in filein:
119      if "Project deadline" in ligne:
120        project["deadline"] = ligne.split()[-1]
121        break
[2411]122
[2413]123  return project, logins, today, total, utheo, ureal
[2411]124
125
[2412]126########################################
127def write_param(filename, project):
[2411]128
[2412]129  if args.dryrun:
130    print(json.dumps(project, indent=2))
131  else:
132    with open(filename, "w") as fileout:
133      json.dump(project, fileout, indent=2)
[2411]134
135
[2412]136########################################
137def write_bilan(filename, today, total, ureal, utheo):
138  """
139  Conso totale par jour
140  ---------------------
141  on garde le total, date en tete en accumulant dans le fichier :
142  OUT_CONSO_BILAN
143  """
[2411]144
[2412]145  title_str  = "{:10s} {:12s} {:11s} {:11s}\n".format(
146                 "date",
147                 "conso(hours)",
148                 "real_use(%)",
149                 "theo_use(%)",
150               )
[2413]151  result_str = "{:%Y-%m-%d} {:12.2f} {:11.2f} {:11.2f}\n".format(
[2412]152                 today,
153                 total,
154                 ureal,
155                 utheo,
156               )
157
158  if args.dryrun:
159    print(title_str.strip())
160    print(result_str.strip())
161  else:
162    if not os.path.isfile(filename):
163      with open(filename, "w") as fileout:
164        fileout.write(title_str)
165    with open(filename, "a") as fileout:
166      fileout.write(result_str)
167
168
169########################################
170def write_utheo(filename, today, utheo):
171  """
172  Conso théorique par jour
173  ------------------------
174  OUT_CONSO_THEO
175  """
176
177  title_str  = "{:10s} {:11s}\n".format(
178                 "date",
179                 "theo_use(%)",
180               )
[2413]181  result_str = "{:%Y-%m-%d} {:11.2f}\n".format(
[2412]182                 today,
183                 utheo,
184               )
185
186  if args.dryrun:
187    print(title_str.strip())
188    print(result_str.strip())
189  else:
190    if not os.path.isfile(filename):
191      with open(filename, "w") as fileout:
192        fileout.write(title_str)
193    with open(filename, "a") as fileout:
194      fileout.write(result_str)
195
196
197########################################
198def write_login(filename, today, logins):
199  """
200  Conso par login (HOME)
201  ----------------------
202  on garde la trace de chaque login, date en tete, en remplacant
203  le fichier a chaque fois : OUT_CONSO_LOGIN
204  """
205
206  title_str  = "{:10s} {:10s} {:12s}\n".format(
207                 "date",
208                 "login",
209                 "conso(hours)",
210               )
211
212  with open(filename, "w") as fileout:
213    if args.dryrun:
214      print(title_str.strip())
215    else:
216      fileout.write(title_str)
217
218    for key in sorted(logins):
[2413]219      result_str = "{:%Y-%m-%d} {:10s} {:12.2f}\n".format(
[2412]220                     today,
221                     key,
222                     logins[key],
223                   )
224      if args.dryrun:
225        print(result_str.strip())
226      else:
227        fileout.write(result_str)
228
229
230########################################
[2417]231def write_store(filename, today, logins):
[2412]232  """
233  volume cree sur STORE
234  ---------------------
235  par login qui a consomme, en remplacant le fichier a chaque fois :
236  OUT_CONSO_STORE
237  """
238
[2413]239  items = (login for login, conso in logins.iteritems()
240                  if conso > 0.)
[2412]241
[2417]242  title_str  = "{:10s} {:10s} {:>7s} {:s}\n".format(
243                 "date",
244                 "login",
245                 "dirsize",
246                 "dirname",
247               )
[2412]248
[2417]249  with open(filename, "w") as fileout:
250    if args.dryrun:
251      print(title_str.strip())
252    else:
253      fileout.write(title_str)
[2413]254
[2417]255    for login in items:
256      if args.verbose:
257        print(login)
258      storedir = get_storedir(login)
259      if not storedir:
260        break
261      igcm_out = os.path.join(storedir, "IGCM_OUT")
[2413]262
[2421]263      if not os.path.isdir(igcm_out):
264        break
[2417]265
[2421]266      dirlist = []
267      try:
268        dirlist = os.listdir(igcm_out)
269      except OSError as rc:
270        print("Error on os.listdir({}):\n{}".format(igcm_out, rc))
271
272      for dirname in dirlist:
[2417]273        result_str = "{:%Y-%m-%d} {:10s} {:>7s} {:s}\n".format(
274                       today,
275                       login,
[2421]276                       get_dirsize(os.path.join(igcm_out, dirname)),
277                       os.path.join(igcm_out, dirname)
[2417]278                     )
[2421]279
280        if args.dryrun or args.verbose:
[2417]281          print(result_str.strip())
[2421]282
283        if not args.dryrun:
[2417]284          fileout.write(result_str)
285
286
[2412]287########################################
[2417]288def save_files(OUT, today):
289
290  if not args.dryrun:
291    suffix = "{:%Y%m%d}".format(today)
292    for filename in OUT.itervalues():
293      filein  = os.path.join(DIR["DATA"], filename)
294      if os.path.isfile(filein):
295        fileout = os.path.join(DIR["SAVE"],
296                               "_".join((filename, suffix)))
297        shutil.copy(filein, fileout)
298
299
300########################################
[2412]301if __name__ == '__main__':
302
303  # Get arguments from command line
304  # ===============================
305  parser = ArgumentParser()
306  parser.add_argument("-v", "--verbose", action="store_true",
307                      help="Verbose mode")
308  parser.add_argument("-d", "--dryrun", action="store_true",
309                      help="dry run, no file produced")
310  parser.add_argument("-a", "--all", action="store_false",
311                      help="produce all files (default)")
312  parser.add_argument("-b", "--bilan", action="store_true",
313                      help="produce all files (default)")
314  parser.add_argument("-l", "--login", action="store_true",
315                      help="produce all files (default)")
316  parser.add_argument("-s", "--store", action="store_true",
317                      help="produce all files (default)")
318
319  args = parser.parse_args()
320  if args.verbose:
321    print(os.path.basename(__file__))
[2413]322    print(where_we_run())
[2412]323    print(args)
324
[2417]325  if args.bilan or args.login or args.store:
326    args.all = False
[2412]327
328  if args.verbose:
[2413]329    print(DIR["DATA"])
330    print(DIR["SAVE"])
[2412]331
[2413]332  (project, logins, today, total, utheo, ureal) = \
[2417]333      parse_myproject(os.path.join(DIR["DATA"], OUT["CCCMP"]))
[2412]334
335  if args.verbose:
336    print(today, utheo, ureal)
337    print(project)
338    print(logins)
339
340  # Produce files
341  # =============
342
343  # 1- Parametres du projet
344  # -----------------------
[2417]345  if args.verbose:
346    print("=> write_param")
[2412]347
[2417]348  write_param(os.path.join(DIR["DATA"], OUT["PARAM"]), project)
349
[2412]350  # 2- Conso totale par jour
351  # ------------------------
[2417]352  if args.verbose:
353    print("=> write_bilan")
354
[2412]355  write_bilan(
[2417]356    os.path.join(DIR["DATA"], OUT["BILAN"]),
[2412]357    today,
358    total,
359    ureal,
360    utheo
361  )
362
363  # 2b- Conso théorique par jour
364  # ----------------------------
[2417]365  if args.verbose:
366    print("=> write_utheo")
[2412]367
[2417]368  write_utheo(os.path.join(DIR["DATA"], OUT["UTHEO"]), today, utheo)
369
[2412]370  # 3- Conso par login (HOME)
371  # -------------------------
[2417]372  if args.verbose:
373    print("=> write_login")
[2412]374
[2417]375  write_login(os.path.join(DIR["DATA"], OUT["LOGIN"]), today, logins)
376
[2412]377  # 4- volume cree sur STORE
378  # ------------------------
[2417]379  if args.verbose:
380    print("=> write_store")
381
[2413]382  # if where_we_run() == "curie":
[2417]383  #   write_store(os.path.join(DIR["DATA"], OUT["STORE"]))
384  write_store(os.path.join(DIR["DATA"], OUT["STORE"]), today, logins)
[2412]385
386  # Save files (on WORKDIR)
387  # =======================
[2417]388  if args.verbose:
389    print("=> Save files")
390
[2412]391  if not args.dryrun:
[2417]392    save_files(OUT, today)
Note: See TracBrowser for help on using the repository browser.