source: TOOLS/ConsoGENCI/trunk/bin/libconso_cpt.py @ 4035

Last change on this file since 4035 was 3083, checked in by labetoulle, 7 years ago

Overall update (typos, get_project_list.py, ...)

  • Property svn:executable set to *
File size: 8.3 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# ==================================================================== #
5# Author: Sonia Labetoulle                                             #
6# Contact: sonia.labetoulle _at_ ipsl.jussieu.fr                       #
7# Created: 2016                                                        #
8# History:                                                             #
9# Modification:                                                        #
10# ==================================================================== #
11
12# =================================================================== #
13# ssh readonly@prodiguer-test-db.ipsl.upmc.fr                         #
14# psql -U prodiguer_db_user prodiguer                                 #
15#                                                                     #
16# ssh readonly@prodiguer-test-db.ipsl.upmc.fr -L 5432:localhost:5432  #
17# =================================================================== #
18
19
20# This must come first
21# from __future__ import print_function, unicode_literals, division
22from __future__ import print_function, division
23
24# Standard library imports
25import os
26import glob
27import pprint
28
29# Application library imports
30
31pp = pprint.PrettyPrinter(indent=2)
32
33
34#######################################################################
35class ProjectBloc(object):
36
37  #--------------------------------------------------------------------
38  def __init__(
39    self,
40    name,
41    center,
42    machine=None,
43    node=None,
44    date_beg=None,
45    date_end=None,
46    alloc=None,
47    line_beg=None,
48    line_end=None,
49  ):
50    self.name     = name
51    self.center   = center
52    self.machine  = machine
53    self.node     = node
54    self.date_beg = date_beg
55    self.date_end = date_end
56    self.alloc    = alloc
57    self.line_beg = line_beg
58    self.line_end = line_end
59    self.alloc_id = None
60
61  #--------------------------------------------------------------------
62  def __repr__(self):
63    return "{}/{} = {}".format(
64      self.name,
65      self.center,
66      self.alloc,
67    )
68
69
70#######################################################################
71class ConsoItem(object):
72
73  #--------------------------------------------------------------------
74  def __init__(self, login, date, conso):
75    self.login = login
76    self.date  = date
77    self.conso = conso
78
79  #--------------------------------------------------------------------
80  def __repr__(self):
81    return "{}/{:%Y%m%d} = {}".format(
82      self.login,
83      self.date,
84      self.conso,
85    )
86
87
88#######################################################################
89class AllocRow(object):
90
91  #--------------------------------------------------------------------
92  def __init__(self, row):
93    self.name     = row["project"]
94    self.alloc_id = row["id"]
95    self.machine  = row["machine"]
96    self.centre   = row["centre"]
97    self.node     = row["node_type"]
98    self.date_beg = row["start_date"]
99    self.date_end = row["end_date"]
100    self.alloc    = row["total_hrs"]
101
102  #--------------------------------------------------------------------
103  def __repr__(self):
104    return "{}/{}/{:%Y%m%d}/{:%Y%m%d} ({})".format(
105      self.machine,
106      self.node,
107      self.date_beg,
108      self.date_end,
109      self.alloc_id,
110    )
111
112
113#######################################################################
114def get_project_id(bloc, allocs):
115
116  res = None
117
118  for alloc in allocs:
119    # print(
120    #   bloc.cpt_date,
121    #   alloc.date_end,
122    #   bloc.cpt_date <= alloc.date_end
123    # )
124    if bloc.machine == alloc.machine   and \
125       bloc.node == alloc.node         and \
126       bloc.cpt_date >= alloc.date_beg and \
127       bloc.cpt_date <= alloc.date_end:
128      res = alloc.alloc_id
129      break
130
131  return res
132
133
134#######################################################################
135def cpt_pattern(project, center):
136
137  return "cpt_{}_{}_*.dat".format(center, project)
138
139
140#######################################################################
141def parse_input_cpt(filename, project, center, mode_conso=False):
142
143  if center == "idris":
144    return parse_idris_cpt(filename, project)
145  elif center == "tgcc":
146    return parse_tgcc_cpt(filename, project, mode_conso)
147  else:
148    print("Unknown center {}".format(center))
149    exit(9)
150
151
152#######################################################################
153def parse_tgcc_cpt(filename, project, mode_conso=False):
154
155  import datetime as dt
156
157  # Determine first and last lines of project bloc(s),
158  # and basic project info
159  blocs = []
160  with open(filename, "r") as filein:
161    for num, ligne in enumerate(filein):
162      if "Accounting" in ligne:
163        _, _, _, name, _, machine, node, _, day = ligne.split()
164        bloc = ProjectBloc(
165          name.lower(),
166          "tgcc",
167          machine.lower(),
168          node.lower(),
169        )
170        bloc.cpt_date = dt.datetime.strptime(
171          "{} {}".format(day, "23:59"), "%Y-%m-%d %H:%M"
172        )
173        bloc.line_beg = num + 1
174      if "Allocated" in ligne:
175        bloc.alloc = float(ligne.split()[-1])
176      if "deadline" in ligne:
177        bloc.date_end = dt.datetime.strptime(
178          "{}".format(ligne.split()[-1]), "%Y-%m-%d"
179        )
180        bloc.date_end = dt.date(
181          bloc.date_end.year,
182          bloc.date_end.month,
183          bloc.date_end.day,
184        )
185        bloc.line_end = num + 1
186        if bloc.name == project:
187          blocs.append(bloc)
188
189  if mode_conso:
190    for bloc in blocs:
191      bloc.consos = set()
192      with open(filename, "r") as filein:
193        for _ in xrange(bloc.line_beg - 1):
194          next(filein)
195        for num, ligne in enumerate(filein):
196          if num > bloc.line_end - bloc.line_beg:
197            break
198          if len(ligne.split()) == 2 and \
199             ligne.split()[0] != "Allocated":
200            login, conso = ligne.lower().split()
201            conso = float(conso)
202            # bloc["consos"].add((login.lower(), conso))
203            bloc.consos.add(
204              ConsoItem(
205                login.lower(),
206                bloc.cpt_date,
207                conso,
208              )
209            )
210
211  return blocs[0].cpt_date, blocs
212
213
214#######################################################################
215def parse_idris_cpt(filename, project):
216
217  import datetime as dt
218
219  print(filename)
220
221  blocs = []
222
223  with open(filename, "r") as filein:
224    # bloc = {}
225    bloc = ProjectBloc(
226      project,
227      "idris",
228    )
229    bloc.consos = set()
230    for num, ligne in enumerate(filein):
231      if "mise a jour" in ligne:
232        jour, heure = ligne.strip().split()[-2:]
233        bloc.cpt_date = dt.datetime.strptime(
234          "{} {}".format(jour, heure), "%d/%m/%Y %H:%M"
235        )
236        bloc.date_end = dt.date(bloc.cpt_date.year, 12, 31)
237        # bloc["date_end"] = dt.datetime.strptime(
238        #   "{} {}".format(jour, heure), "%d/%m/%Y %H:%M"
239        # )
240      elif "Comptabilite" in ligne:
241        bloc.machine = ligne.strip().split()[-1].strip(".")
242        bloc.node = "standard"
243      elif "Heures" in ligne:
244        bloc.alloc = int(ligne.strip().split()[-1])
245      elif "Totaux" in ligne:
246        conso = float(ligne.strip().split()[1])
247        # bloc.consos.add(("total", conso))
248        bloc.consos.add(
249          ConsoItem(
250            "total",
251            bloc.cpt_date,
252            conso,
253          )
254        )
255      elif project in ligne:
256        login = ligne.strip().split()[0]
257        try:
258          conso = float(ligne.strip().split()[2])
259        except ValueError:
260          conso = float("nan")
261        # bloc.consos.add((login, conso))
262        bloc.consos.add(
263          ConsoItem(
264            login.lower(),
265            bloc.cpt_date,
266            conso,
267          )
268        )
269
270    blocs.append(bloc)
271
272  return blocs[0].cpt_date, blocs
273
274
275#######################################################################
276def date_from_filename(filename):
277  """
278  """
279  return os.path.basename(filename).split("_")[-2]
280
281
282#######################################################################
283def find_input_files(data_dir, pattern, date_range):
284  """
285  """
286  file_list = glob.glob(os.path.join(data_dir, pattern))
287
288  if date_range:
289    res = []
290    for filename in file_list:
291      file_date = date_from_filename(filename)
292      if file_date >= min(date_range) and \
293         file_date <= max(date_range):
294        res.append(filename)
295  else:
296    res = file_list
297
298  # return set(res)
299  return sorted(res)
300
301
302#######################################################################
303if __name__ == "__main__":
304  pass
Note: See TracBrowser for help on using the repository browser.