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
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# this must come first
5from __future__ import print_function, unicode_literals, division
6
7# standard library imports
8from argparse import ArgumentParser
9import json
10import shutil
11import os
12import os.path
13import subprocess
14# import datetime as dt
15
16# Application library imports
17from gencmip6 import *
18from gencmip6_path import *
19
20
21########################################
22def get_storedir(login):
23
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"
59  logins  = {}
60
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
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]
76        today = string_to_date(today)
77
78        break
79
80    # Skip next two lines : first is blank and second is login titles
81    for _ in xrange(1):
82      next(filein)
83
84    # Login list, until blank line
85    for ligne in filein:
86      if not ligne.strip():
87        break
88      login, conso = ligne.split()
89      logins[login] = float(conso)
90
91    # Skip until we find consumed time (hours)
92    for ligne in filein:
93      if "Total" in ligne:
94        total = float(ligne.split()[-1])
95        break
96
97    # Skip until we find allocated time (hours)
98    for ligne in filein:
99      if "Allocated" in ligne:
100        project["alloc"] = float(ligne.split()[-1])
101        break
102
103    # Skip until we find theoratical use (%)
104    for ligne in filein:
105      if "Suggested use at this time" in ligne:
106        utheo = float(ligne.split()[-1].strip("%"))
107        break
108
109    # Skip until we find real use (%)
110    for ligne in filein:
111      if "Real use at this time" in ligne:
112        ureal = float(ligne.split()[-1].strip("%"))
113        break
114
115    # Skip until we find deadline
116    for ligne in filein:
117      if "Project deadline" in ligne:
118        project["deadline"] = ligne.split()[-1]
119        break
120
121  return project, logins, today, total, utheo, ureal
122
123
124########################################
125def write_param(filename, project):
126
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)
132
133
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  """
142
143  title_str  = "{:10s} {:12s} {:11s} {:11s}\n".format(
144                 "date",
145                 "conso(hours)",
146                 "real_use(%)",
147                 "theo_use(%)",
148               )
149  result_str = "{:%Y-%m-%d} {:12.2f} {:11.2f} {:11.2f}\n".format(
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               )
179  result_str = "{:%Y-%m-%d} {:11.2f}\n".format(
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):
217      result_str = "{:%Y-%m-%d} {:10s} {:12.2f}\n".format(
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########################################
229def write_store(filename, today, logins):
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
237  items = (login for login, conso in logins.iteritems()
238                  if conso > 0.)
239
240  title_str  = "{:10s} {:10s} {:>7s} {:s}\n".format(
241                 "date",
242                 "login",
243                 "dirsize",
244                 "dirname",
245               )
246
247  with open(filename, "w") as fileout:
248    if args.dryrun:
249      print(title_str.strip())
250    else:
251      fileout.write(title_str)
252
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")
260
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
276########################################
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########################################
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__))
311    print(where_we_run())
312    print(args)
313
314  if args.bilan or args.login or args.store:
315    args.all = False
316
317  if args.verbose:
318    print(DIR["DATA"])
319    print(DIR["SAVE"])
320
321  (project, logins, today, total, utheo, ureal) = \
322      parse_myproject(os.path.join(DIR["DATA"], OUT["CCCMP"]))
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  # -----------------------
334  if args.verbose:
335    print("=> write_param")
336
337  write_param(os.path.join(DIR["DATA"], OUT["PARAM"]), project)
338
339  # 2- Conso totale par jour
340  # ------------------------
341  if args.verbose:
342    print("=> write_bilan")
343
344  write_bilan(
345    os.path.join(DIR["DATA"], OUT["BILAN"]),
346    today,
347    total,
348    ureal,
349    utheo
350  )
351
352  # 2b- Conso théorique par jour
353  # ----------------------------
354  if args.verbose:
355    print("=> write_utheo")
356
357  write_utheo(os.path.join(DIR["DATA"], OUT["UTHEO"]), today, utheo)
358
359  # 3- Conso par login (HOME)
360  # -------------------------
361  if args.verbose:
362    print("=> write_login")
363
364  write_login(os.path.join(DIR["DATA"], OUT["LOGIN"]), today, logins)
365
366  # 4- volume cree sur STORE
367  # ------------------------
368  if args.verbose:
369    print("=> write_store")
370
371  # if where_we_run() == "curie":
372  #   write_store(os.path.join(DIR["DATA"], OUT["STORE"]))
373  write_store(os.path.join(DIR["DATA"], OUT["STORE"]), today, logins)
374
375  # Save files (on WORKDIR)
376  # =======================
377  if args.verbose:
378    print("=> Save files")
379
380  if not args.dryrun:
381    save_files(OUT, today)
Note: See TracBrowser for help on using the repository browser.