Salome HOME
b61ab1edb50dcfef6768dfd7c1ce39862148c9ee
[modules/adao.git] / src / daComposant / daCore / PlatformInfo.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 EDF R&D
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 __doc__ = """
24     Informations sur le code et la plateforme, et mise à jour des chemins
25     
26     La classe "PlatformInfo" permet de récupérer les informations générales sur
27     le code et la plateforme sous forme de strings, ou d'afficher directement
28     les informations disponibles par les méthodes. L'impression directe d'un
29     objet de cette classe affiche les informations minimales. Par exemple :
30         print PlatformInfo()
31         print PlatformInfo().getVersion()
32         created = PlatformInfo().getDate()
33
34     La classe "PathManagement" permet de mettre à jour les chemins système pour
35     ajouter les outils numériques, matrices... On l'utilise en instanciant
36     simplement cette classe, sans meme récupérer d'objet :
37         PathManagement()
38 """
39 __author__ = "Jean-Philippe ARGAUD"
40
41 import os
42
43 # ==============================================================================
44 class PlatformInfo:
45     """
46     Rassemblement des informations sur le code et la plateforme
47     """
48     def getName(self):
49         "Retourne le nom de l'application"
50         import version
51         return version.name
52
53     def getVersion(self):
54         "Retourne le numéro de la version"
55         import version
56         return version.version
57
58     def getDate(self):
59         "Retourne la date de création de la version"
60         import version
61         return version.date
62     
63     def getPythonVersion(self):
64         "Retourne la version de python utilisée"
65         import sys
66         return ".".join(map(str,sys.version_info[0:3]))
67
68     def getNumpyVersion(self):
69         "Retourne la version de numpy utilisée"
70         import numpy.version
71         return numpy.version.version
72
73     def getScipyVersion(self):
74         "Retourne la version de scipy utilisée"
75         import scipy.version
76         return scipy.version.version
77
78     def getMatplotlibVersion(self):
79         "Retourne la version de matplotlib utilisée"
80         try:
81             import matplotlib
82             return matplotlib.__version__
83         except:
84             return "0.0.0"
85
86     def getGnuplotVersion(self):
87         "Retourne la version de gnuplotpy utilisée"
88         try:
89             import Gnuplot
90             return Gnuplot.__version__
91         except:
92             return "0.0"
93
94     def getCurrentMemorySize(self):
95         "Retourne la taille mémoire courante utilisée"
96         return 1
97
98     def __str__(self):
99         import version
100         return "%s %s (%s)"%(version.name,version.version,version.date)
101
102 # ==============================================================================
103 def uniq(sequence):
104     """
105     Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
106     """
107     __seen = set()
108     return [x for x in sequence if x not in __seen and not __seen.add(x)]
109
110 # ==============================================================================
111 class PathManagement:
112     """
113     Mise à jour du path système pour les répertoires d'outils
114     """
115     def __init__(self):
116         import sys
117         parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
118         self.__paths = {}
119         self.__paths["daExternals"] = os.path.join(parent,"daExternals")
120         self.__paths["daMatrices"]  = os.path.join(parent,"daMatrices")
121         self.__paths["daNumerics"]  = os.path.join(parent,"daNumerics")
122         #
123         for v in self.__paths.values():
124             sys.path.insert(0, v )
125         #
126         # Conserve en unique exemplaire chaque chemin
127         sys.path = uniq( sys.path )
128         del parent
129
130     def getpaths(self):
131         """
132         Renvoie le dictionnaire des chemins ajoutés
133         """
134         return self.__paths
135
136 # ==============================================================================
137 class SystemUsage:
138     """
139     Permet de récupérer les différentes tailles mémoires du process courant
140     """
141     #
142     # Le module resource renvoie 0 pour les tailles mémoire. On utilise donc
143     # plutôt : http://code.activestate.com/recipes/286222/ et Wikipedia
144     #
145     _proc_status = '/proc/%d/status' % os.getpid()
146     _memo_status = '/proc/meminfo'
147     _scale = {
148         'o':     1.0, 'ko' : 1.e3,   'Mo' : 1.e6,          'Go' : 1.e9,                 # Multiples SI de l'octet
149                       'kio': 1024.0, 'Mio': 1024.0*1024.0, 'Gio': 1024.0*1024.0*1024.0, # Multiples binaires de l'octet
150         'B':     1.0, 'kB' : 1024.0, 'MB' : 1024.0*1024.0, 'GB' : 1024.0*1024.0*1024.0, # Multiples binaires du byte=octet
151              }
152     #
153     def _VmA(self, VmKey, unit):
154         try:
155             t = open(self._memo_status)
156             v = t.read()
157             t.close()
158         except:
159             return 0.0           # non-Linux?
160         i = v.index(VmKey)       # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
161         v = v[i:].split(None, 3) # whitespace
162         if len(v) < 3:
163             return 0.0           # invalid format?
164         # convert Vm value to bytes
165         mem = float(v[1]) * self._scale[v[2]]
166         return mem / self._scale[unit]
167     #
168     def getAvailablePhysicalMemory(self, unit="o"):
169         "Renvoie la mémoire physique utilisable en octets"
170         return self._VmA('MemTotal:', unit)
171     #
172     def getAvailableSwapMemory(self, unit="o"):
173         "Renvoie la mémoire swap utilisable en octets"
174         return self._VmA('SwapTotal:', unit)
175     #
176     def getAvailableMemory(self, unit="o"):
177         "Renvoie la mémoire totale (physique+swap) utilisable en octets"
178         return self._VmA('MemTotal:', unit) + self._VmA('SwapTotal:', unit)
179     #
180     def getUsableMemory(self, unit="o"):
181         """Renvoie la mémoire utilisable en octets
182         Rq : il n'est pas sûr que ce décompte soit juste...
183         """
184         return self._VmA('MemFree:', unit) + self._VmA('SwapFree:', unit) + \
185                self._VmA('Cached:', unit) + self._VmA('SwapCached:', unit)
186     #
187     def _VmB(self, VmKey, unit):
188         try:
189             t = open(self._proc_status)
190             v = t.read()
191             t.close()
192         except:
193             return 0.0           # non-Linux?
194         i = v.index(VmKey)       # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
195         v = v[i:].split(None, 3) # whitespace
196         if len(v) < 3:
197             return 0.0           # invalid format?
198         # convert Vm value to bytes
199         mem = float(v[1]) * self._scale[v[2]]
200         return mem / self._scale[unit]
201     #
202     def getUsedMemory(self, unit="o"):
203         "Renvoie la mémoire résidente utilisée en octets"
204         return self._VmB('VmRSS:', unit)
205     #
206     def getVirtualMemory(self, unit="o"):
207         "Renvoie la mémoire totale utilisée en octets"
208         return self._VmB('VmSize:', unit)
209     #
210     def getUsedStacksize(self, unit="o"):
211         "Renvoie la taille du stack utilisé en octets"
212         return self._VmB('VmStk:', unit)
213     #
214     def getMaxUsedMemory(self, unit="o"):
215         "Renvoie la mémoire résidente maximale mesurée"
216         return self._VmB('VmHWM:', unit)
217     #
218     def getMaxVirtualMemory(self, unit="o"):
219         "Renvoie la mémoire totale maximale mesurée"
220         return self._VmB('VmPeak:', unit)
221
222 # ==============================================================================
223 if __name__ == "__main__":
224     print '\n AUTODIAGNOSTIC \n'