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

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

Fix typos

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