viewgit/index.php:465 Only variables should be passed by reference [2048]

viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Monitora se i computer dell'aula studenti sono accesi
  5. # e restituisce delle statistiche a proposito.
  6.  
  7. import subprocess, time, os, matplotlib
  8. matplotlib.use ('Agg')
  9. import numpy as np, pylab
  10. from optparse import OptionParser
  11.  
  12. # Qualche variabile globale
  13. database_directory = '/home/robol/client_stats/' # Il traling slash ci serve
  14. max_time = 86400 * 10 / 3 / 60 # 10 giorni
  15. group = '/etc/dsh/group/all'
  16. verbose = False
  17.  
  18. def Verbose(string):
  19. if verbose:
  20. print "> " + string
  21.  
  22. def LoadClients():
  23. """
  24. Ritorna una lista con tutti i client all'interno del
  25. gruppo group di dsh. Il default è 'all'
  26. """
  27. global group
  28. clients = []
  29. try:
  30. for client in open(group, 'r'):
  31. client = client.strip()
  32. if client.strip != '' and client[0] != '#':
  33. clients.append (client)
  34. except IOError:
  35. raise IOError('Il gruppo dsh \'%s\' non esiste, nessun client trovato!' %
  36. group)
  37. Verbose ("Client loaded!")
  38. for client in clients:
  39. Verbose("Client: %s" % client)
  40. return clients
  41.  
  42. def IsAlive(client):
  43. """
  44. Ritorna True se il client è acceso e risponde ai ping
  45. """
  46. alive = subprocess.call(["fping", client], stdout = subprocess.PIPE,
  47. stderr = subprocess.PIPE)
  48. return (alive == 0)
  49.  
  50. def IsLastAlive(client):
  51. """
  52. Ritorna True se il client era acceso durante l'ultimo check
  53. effettuato.
  54. """
  55. data = LoadClientData(client)
  56. data = data.items()
  57. data.sort()
  58. return data[-1:][0][1]
  59.  
  60. def LockDatabase():
  61. """
  62. Effettua il lock del database
  63. """
  64. lockfile = database_directory + ".lock"
  65. counter = 0
  66. while (os.path.exists(lockfile)):
  67. time.sleep(1000)
  68. counter +=1
  69. if (counter > 30):
  70. raise RuntimeError('Impossible to unlock database')
  71. f = open(lockfile, 'w')
  72. f.write(str(time.time()))
  73. f.close()
  74. # Verbose("Database locked")
  75.  
  76. def UnlockDatabase():
  77. """
  78. Sblocca il database
  79. """
  80. lockfile = database_directory + ".lock"
  81. os.remove(lockfile)
  82. # Verbose("Database unlocked")
  83.  
  84. def LoadClientData(client):
  85. """
  86. Carica i dati relativi a quel determinato client. Questi
  87. sono nella forma di un dizionario con gli oggetti time e
  88. Valori True o False
  89. """
  90. LockDatabase()
  91. data = {}
  92. try:
  93. f = open(database_directory + client, 'r')
  94. except IOError:
  95. return data
  96. for line in f:
  97. if ":" in line:
  98. (time, alive) = line.split(":")
  99. alive = ("True" in alive)
  100. data[float(time)] = alive
  101. f.close()
  102. UnlockDatabase()
  103. return data
  104.  
  105. def DumpClientData(client, data):
  106. """
  107. Salva i dati relativi ad un client, eliminando quelli troppo
  108. vecchi
  109. """
  110. LockDatabase()
  111. data = dict (filter(lambda i: (i[0] > time.time() - max_time),
  112. data.items()))
  113. f = open(database_directory + client, 'w')
  114. f.write ("\n".join( map(lambda i: ":".join(map(str, i)), data.items())))
  115. f.close()
  116. UnlockDatabase()
  117.  
  118. def UpdateClientsData(client, alive):
  119. """
  120. Aggiorna i dati relativi al client inserendo l'informazione
  121. che in questo momento è acceso.
  122. """
  123. data = LoadClientData(client)
  124. data[float(time.time())] = alive
  125. n = " not"
  126. if alive:
  127. n = ""
  128. Verbose ("Appending new data :%s is%s alive" % (client, n))
  129. DumpClientData(client, data)
  130.  
  131. def PrintStats(client):
  132. """
  133. Stampa le statistiche sul client prescelto
  134. """
  135. data = LoadClientData(client)
  136. d = data.items()
  137. d.sort()
  138. ss = 0
  139. old_time = d[0][0]
  140.  
  141. # Un piccolo integrale sul tempo della funzione
  142. # up(client)
  143. for (time_entry, up) in d[1:]:
  144. if up:
  145. ss += (time_entry - old_time)
  146. old_time = time_entry
  147. ss = ss / (d[-1:][0][0] - d[0][0])
  148.  
  149. uptime = 100.0 * ss
  150. if IsLastAlive(client):
  151. is_online = "yes"
  152. else:
  153. is_online = "no"
  154. print "Client: %s" % client
  155. print "IsOnline: %s" % is_online
  156. print "Uptime: %3.2f %% " % uptime
  157. print "----------------------------------------------------"
  158.  
  159. def UptimePlot(filename):
  160. """
  161. Crea un png con l'uptime dei vari client
  162. """
  163. # Per ora usiamo come backend gnuplot perché matplotlib
  164. # non è installato su poisson e presumibilmente non avrò
  165. # voglia di installarlo.
  166. clients = LoadClients()
  167. samples = 100
  168.  
  169. # Mi interesso solo dell'ultima settimana, e prendo un sample
  170. # ogni 10 minuti.
  171. plot_time = np.linspace(0,-7, samples)
  172.  
  173. # Mi servono i dati in secondi, ma cominciamo da un'ora fa
  174. # per evitare che il grafico vada a 0 per mancanza di dati.
  175. plot_time = 86400 * plot_time + float(time.time()) - 360
  176.  
  177. # Inizializziamo i dati a zero
  178. plot_data = np.zeros(samples)
  179.  
  180. for client in clients:
  181. client_data = ClientUptime(plot_time, client)
  182. plot_data += client_data
  183.  
  184. # Scriviamo i dati su un file
  185. #f_handle = open('/tmp/phcstats.table', 'w')
  186. #f_handle.write ("# File generato da PHCStats\n")
  187. #for index, t in enumerate(np.linspace(0,-7,samples)):
  188. # f_handle.write(str(t) + " " + str(plot_data[index]) + "\n")
  189. #f_handle.close ()
  190.  
  191. pylab.title("Client accesi nell'ultima settimana")
  192. pylab.xlabel("Giorni passati")
  193. pylab.ylabel("Numero di client")
  194. pylab.plot (np.linspace(0,-7,samples)[::-1], plot_data)
  195. pylab.axis([-7.5, 0, -0.5, 10])
  196. f = open(filename, "w")
  197. pylab.savefig(f, format='png')
  198. f.close()
  199.  
  200.  
  201. def ClientUptime(times, client):
  202. """
  203. Ritorna un vettore della stessa lunghezza di times con
  204. il valore 1 se il client era acceso e 0 se era spento
  205. """
  206. data = LoadClientData(client)
  207. data = data.items()
  208. data.sort()
  209. iterator = data.__iter__()
  210. item = iterator.next()
  211. values = np.zeros(len(times))
  212. i = 0
  213. for t in times[::-1]:
  214. if item[0] > t:
  215. values[i] = 0
  216. i += 1
  217. continue
  218. try:
  219. while (item[0] < t):
  220. item = iterator.next()
  221. except StopIteration:
  222. return values
  223. if (item[1] == True):
  224. values[i] = 1
  225. else:
  226. values[i] = 0
  227. i += 1
  228. return values
  229.  
  230.  
  231.  
  232. if __name__ == "__main__":
  233.  
  234. parser = OptionParser()
  235. parser.add_option("-c", "--check", dest="check",
  236. help = "Check if clients are up and update database",
  237. action = "store_true", default=False)
  238. parser.add_option("-s", "--stats", dest="stats",
  239. help = "Print stats about collected informations",
  240. action = "store_true", default = False)
  241. parser.add_option("-g", "--group-file", dest="group_file",
  242. help="The dsh group file to use", default='/etc/dsh/group/all')
  243. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  244. help="Be verbose", default=False)
  245. parser.add_option("-p", "--plot", dest="plot", action="store_true",
  246. help="Plot the data to a png file", default=False)
  247.  
  248. (options, args) = parser.parse_args()
  249. group = os.path.expanduser(options.group_file)
  250. verbose = options.verbose
  251.  
  252. # Se non mi chiedi di fare niente non hai capito
  253. # come funziono, molto probabilmente.
  254. if not (options.check or options.stats or options.plot):
  255. parser.print_help()
  256.  
  257. if options.check:
  258. for client in LoadClients():
  259. UpdateClientsData(client, IsAlive(client))
  260.  
  261. if options.plot:
  262. UptimePlot("/home/robol/public_html/files/up-clients.png")
  263.  
  264. if options.stats:
  265. try:
  266. for client in LoadClients():
  267. PrintStats(client)
  268. except Exception, e:
  269. print "Errore durante l'esecuzione!\n ==> %s" % e