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