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

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

put all path definitions in a seperate file

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