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

Last change on this file since 2413 was 2413, checked in by labetoulle, 10 years ago

Move all scripts to the same dir to use common configuration files

  • 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, 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  for login in items:
241    storedir = get_storedir(login)
242    if not storedir:
243      break
244    igcm_out = os.path.join(storedir, "IGCM_OUT")
245
246    for dirname in os.listdir(igcm_out):
247      print(dirname, get_dirsize(dirname))
248
249
250########################################
251if __name__ == '__main__':
252
253  # Get arguments from command line
254  # ===============================
255  parser = ArgumentParser()
256  parser.add_argument("-v", "--verbose", action="store_true",
257                      help="Verbose mode")
258  parser.add_argument("-d", "--dryrun", action="store_true",
259                      help="dry run, no file produced")
260  parser.add_argument("-a", "--all", action="store_false",
261                      help="produce all files (default)")
262  parser.add_argument("-b", "--bilan", action="store_true",
263                      help="produce all files (default)")
264  parser.add_argument("-l", "--login", action="store_true",
265                      help="produce all files (default)")
266  parser.add_argument("-s", "--store", action="store_true",
267                      help="produce all files (default)")
268
269  args = parser.parse_args()
270  if args.verbose:
271    print(os.path.basename(__file__))
272    print(where_we_run())
273    print(args)
274
275  # # Files and directories
276  # # =====================
277  # if where_we_run() == "curie":
278  #   LOCAL_DIR = os.path.join(
279  #     "/ccc",
280  #     "cont003",
281  #     "home",
282  #     "dsm",
283  #     "p86ipsl",
284  #     "ConsoGENCMIP6",
285  #     "output"
286  #   )
287  #   SAVE_DIR  = os.path.join(
288  #     "/ccc",
289  #     "work",
290  #     "cont003",
291  #     "dsm",
292  #     "p86ipsl",
293  #     "ConsoGENCMIP6",
294  #   )
295  # # elif where_we_run() == "ipsl":
296  # #   LOCAL_DIR = os.path.join(
297  # #     "/home_local",
298  # #     "slipsl",
299  # #     "ConsoGENCMIP6",
300  # #     "output"
301  # #   )
302  # #   SAVE_DIR  = os.path.join(
303  # #     "/home_local",
304  # #     "slipsl",
305  # #     "ConsoGENCMIP6",
306  # #     "save"
307  # #   )
308  # else:
309  #   LOCAL_DIR = os.path.join(
310  #     "..",
311  #     "output"
312  #   )
313  #   SAVE_DIR  = os.path.join(
314  #     "..",
315  #     "save"
316  #   )
317
318  # LOCAL_DIR = os.path.abspath(LOCAL_DIR)
319  # SAVE_DIR  = os.path.abspath(SAVE_DIR)
320
321  OUT_PARAM = "OUT_CONSO_PARAM"
322  OUT_BILAN = "OUT_CONSO_BILAN"
323  OUT_UTHEO = "OUT_CONSO_UTHEO"
324  OUT_LOGIN = "OUT_CONSO_LOGIN"
325  OUT_STORE = "OUT_CONSO_STORE"
326  OUT_CCCMP = "ccc_myproject.dat"
327
328  if args.verbose:
329    # print(LOCAL_DIR)
330    # print(SAVE_DIR)
331    print(DIR["DATA"])
332    print(DIR["SAVE"])
333
334  (project, logins, today, total, utheo, ureal) = \
335      parse_myproject(os.path.join(DIR["DATA"], OUT_CCCMP))
336
337  if args.verbose:
338    print(today, utheo, ureal)
339    print(project)
340    print(logins)
341
342  # Produce files
343  # =============
344
345  # 1- Parametres du projet
346  # -----------------------
347  write_param(os.path.join(DIR["DATA"], OUT_PARAM), project)
348
349  # 2- Conso totale par jour
350  # ------------------------
351  write_bilan(
352    os.path.join(DIR["DATA"], OUT_BILAN),
353    today,
354    total,
355    ureal,
356    utheo
357  )
358
359  # 2b- Conso théorique par jour
360  # ----------------------------
361  write_utheo(os.path.join(DIR["DATA"], OUT_UTHEO), today, utheo)
362
363  # 3- Conso par login (HOME)
364  # -------------------------
365  write_login(os.path.join(DIR["DATA"], OUT_LOGIN), today, logins)
366
367  # 4- volume cree sur STORE
368  # ------------------------
369  # if where_we_run() == "curie":
370  #   write_store(os.path.join(DIR["DATA"], OUT_STORE))
371  write_store(os.path.join(DIR["DATA"], OUT_STORE), logins)
372
373  # Save files (on WORKDIR)
374  # =======================
375  if not args.dryrun:
376    suffix = "{:%Y%m%d}".format(today)
377    file_list = [
378      OUT_PARAM,
379      OUT_BILAN,
380      OUT_UTHEO,
381      OUT_LOGIN,
382      OUT_STORE
383    ]
384    for filename in file_list:
385      filein  = os.path.join(DIR["DATA"], filename)
386      if os.path.isfile(filein):
387        fileout = os.path.join(DIR["SAVE"], "_".join((filename, suffix)))
388        shutil.copy(filein, fileout)
Note: See TracBrowser for help on using the repository browser.