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. #
  8. #
  9. #
  10. # INIZIO DELLA CONFIGURAZIONE
  11. #
  12. # Questa cartella è dove verranno salvati i dati relativi ai client
  13. # Deve esistere nel momento in cui lo script è lanciato per la prima
  14. # volta e dovrebbe essere vuota. Serve lo slash alla fine, ad esempio:
  15. #
  16. # database_directory = '/home/pippo/phcstats/'
  17. database_directory = '/home/robol/client_stats/'
  18.  
  19. # max_time controlla il massimo numero di secondi di cui possono
  20. # essere "vecchie" le informazioni conservate dallo script.
  21. max_time = 86400 * 30 # ~ 1 mese
  22.  
  23. # Questo è il gruppo di dsh da cui rilevare le informazioni sui client
  24. # da monitorare. In realtà può essere un qualsiasi file di testo con
  25. # il nome di un client su ogni riga. Sono accettati commenti nelle linee
  26. # che cominciano con '#'
  27. group = '/etc/dsh/group/all'
  28.  
  29. # Questa variabile imposta se lo script deve essere verboso, ma in
  30. # realtà è attualmente ignorata. Il comportamento è gestito solo
  31. # dal parametro -v o --verbose a linea di comando.
  32. verbose = False
  33.  
  34. ## FINE DELLA CONFIGURAZIONE
  35.  
  36.  
  37. ## INIZIO DEL CODICE
  38.  
  39. import subprocess, time, os, matplotlib
  40. matplotlib.use ('Agg')
  41. import numpy as np, pylab
  42. from optparse import OptionParser
  43.  
  44.  
  45. def Verbose(string):
  46. if verbose:
  47. print "\033[32;1m>\033[0m " + string
  48.  
  49. def LoadClients():
  50. """
  51. Ritorna una lista con tutti i client all'interno del
  52. gruppo group di dsh. Il default è 'all'
  53. """
  54. global group
  55. clients = []
  56. try:
  57. for client in open(group, 'r'):
  58. client = client.strip()
  59. if client.strip != '' and client[0] != '#':
  60. clients.append (client)
  61. except IOError:
  62. raise IOError('Il gruppo dsh \'%s\' non esiste, nessun client trovato!' %
  63. group)
  64. Verbose ("Client list loaded from %s" % group)
  65. for client in clients:
  66. Verbose("Client: %s" % client)
  67. return clients
  68.  
  69. def IsAlive(client):
  70. """
  71. Ritorna True se il client è acceso e risponde ai ping
  72. """
  73. alive = subprocess.call(["fping", client], stdout = subprocess.PIPE,
  74. stderr = subprocess.PIPE)
  75. return (alive == 0)
  76.  
  77. def IsLastAlive(client):
  78. """
  79. Ritorna True se il client era acceso durante l'ultimo check
  80. effettuato.
  81. """
  82. data = LoadClientData(client)
  83. data = data.items()
  84. data.sort()
  85. return data[-1:][0][1]
  86.  
  87. def LockDatabase():
  88. """
  89. Effettua il lock del database
  90. """
  91. lockfile = database_directory + ".lock"
  92. counter = 0
  93. while (os.path.exists(lockfile)):
  94. time.sleep(1000)
  95. counter +=1
  96. if (counter > 30):
  97. raise RuntimeError('Impossible to unlock database')
  98. f = open(lockfile, 'w')
  99. f.write(str(time.time()))
  100. f.close()
  101.  
  102. def UnlockDatabase():
  103. """
  104. Sblocca il database
  105. """
  106. lockfile = database_directory + ".lock"
  107. os.remove(lockfile)
  108.  
  109. def LoadClientData(client):
  110. """
  111. Carica i dati relativi a quel determinato client. Questi
  112. sono nella forma di un dizionario con gli oggetti time e
  113. Valori True o False
  114. """
  115.  
  116. data = {}
  117. try:
  118. f = open(database_directory + client, 'r')
  119. except IOError:
  120. return data
  121. for line in f:
  122. if ":" in line:
  123. (time, alive) = line.split(":")
  124. alive = ("True" in alive)
  125. data[float(time)] = alive
  126. f.close()
  127.  
  128. return data
  129.  
  130.  
  131. def AppendClientData(client, t, alive):
  132. """
  133. Aggiunge in coda i dati sul client e controlla che
  134. non ci siano dati troppo vecchi, nel qual caso li
  135. elimina
  136. """
  137. LockDatabase()
  138.  
  139. data = LoadClientData(client)
  140. filtered_data = filter(lambda i: i[0] > float(time.time()) - max_time, data.items())
  141. if len(filtered_data) < len(data):
  142. Verbose ("There are %d of %d records to delete" % (len(data) - len(filtered_data), len(data)))
  143. data = dict(filtered_data)
  144. f = open(database_directory + client, 'w')
  145. for (t, v) in data.items():
  146. f.write(str(t) + ":" + str(v) + "\n")
  147. f.close()
  148. f = open(database_directory + client, 'a')
  149. f.write(str(t) + ":" + str(alive) + "\n")
  150. f.close ()
  151. UnlockDatabase()
  152.  
  153. def UpdateClientsData(client, alive):
  154. """
  155. Aggiorna i dati relativi al client inserendo l'informazione
  156. che in questo momento è acceso.
  157. """
  158. n = " not"
  159. if alive:
  160. n = ""
  161. Verbose ("Appending new data: %s is%s alive" % (client, n))
  162. AppendClientData(client, time.time(), alive)
  163.  
  164. def Availability(client):
  165. """
  166. Return availability of the client
  167. """
  168. data = LoadClientData(client)
  169. d = data.items()
  170. d.sort()
  171. ss = 0
  172. old_time = d[0][0]
  173.  
  174. # Un piccolo integrale sul tempo della funzione
  175. # up(client)
  176. for (time_entry, up) in d[1:]:
  177. if up:
  178. ss += (time_entry - old_time)
  179. old_time = time_entry
  180. ss = ss / (d[-1:][0][0] - d[0][0])
  181.  
  182. uptime = 100.0 * ss
  183. return uptime
  184.  
  185.  
  186. def PrintStats(client):
  187. """
  188. Stampa le statistiche sul client prescelto
  189. """
  190. uptime = Availability(client)
  191. if IsLastAlive(client):
  192. is_online = "yes"
  193. else:
  194. is_online = "no"
  195. print "Client: %s" % client
  196. print "IsOnline: %s" % is_online
  197. print "Uptime: %3.2f %% " % uptime
  198. print "----------------------------------------------------"
  199.  
  200. def UptimePlot(filename, days):
  201. """
  202. Crea un png con l'uptime dei vari client
  203. """
  204.  
  205. clients = LoadClients()
  206. samples = 100
  207.  
  208. # Mi interesso solo dell'ultima days giorni, e prendo un sample
  209. # ogni 10 minuti.
  210. plot_time = np.linspace(0, (-1) * days, samples)
  211.  
  212. # Mi servono i dati in secondi, ma cominciamo da un'ora fa
  213. # per evitare che il grafico vada a 0 per mancanza di dati.
  214. plot_time = 86400 * plot_time + float(time.time()) - 360
  215.  
  216. # Inizializziamo i dati a zero
  217. plot_data = np.zeros(samples)
  218.  
  219. for client in clients:
  220. client_data = ClientUptime(plot_time, client)
  221. plot_data += client_data
  222.  
  223. # Plot vero e proprio
  224. pylab.title("Client accesi negli ultimi %d giorni" % days)
  225. pylab.xlabel("Giorni passati")
  226. pylab.ylabel("Numero di client")
  227. pylab.plot (np.linspace(0,(-1) * days,samples)[::-1], plot_data)
  228. pylab.axis([-0.5 - days, 0, -0.5, len(clients) + 1])
  229. f = open(filename, "w")
  230. pylab.savefig(f, format='png')
  231. f.close()
  232.  
  233. def AvailabilityPlot(filename):
  234. """
  235. Plot an histogram of the availability of the clients
  236. """
  237. clients = LoadClients()
  238. av = []
  239. for client in clients:
  240. av.append (Availability(client))
  241.  
  242. # Istogramma con i dati
  243. pylab.title("Uptime dei client")
  244. pylab.xticks(3 * np.array(range(0,len(av))) + 1.7, clients)
  245. pylab.xlabel("")
  246. pylab.ylabel("% of uptime")
  247. pylab.bar(3 * np.array(range(0, len(av))) + 1, av, width=0.8)
  248. pylab.axis([0 , 2*len(av), 0, 102])
  249. f = open(filename, "w")
  250. pylab.savefig(f, format='png')
  251. f.close()
  252.  
  253.  
  254. def ClientUptime(times, client):
  255. """
  256. Ritorna un vettore della stessa lunghezza di times con
  257. il valore 1 se il client era acceso e 0 se era spento
  258. """
  259. data = LoadClientData(client)
  260. data = data.items()
  261. data.sort()
  262. iterator = data.__iter__()
  263. item = iterator.next()
  264. values = np.zeros(len(times))
  265. i = 0
  266. for t in times[::-1]:
  267. if item[0] > t:
  268. values[i] = 0
  269. i += 1
  270. continue
  271. try:
  272. while (item[0] < t):
  273. item = iterator.next()
  274. except StopIteration:
  275. return values
  276. if (item[1] == True):
  277. values[i] = 1
  278. else:
  279. values[i] = 0
  280. i += 1
  281. return values
  282.  
  283.  
  284.  
  285. if __name__ == "__main__":
  286.  
  287. parser = OptionParser()
  288. parser.add_option("-c", "--check", dest="check",
  289. help = "Check if clients are up and update database",
  290. action = "store_true", default=False)
  291. parser.add_option("-s", "--stats", dest="stats",
  292. help = "Print stats about collected informations",
  293. action = "store_true", default = False)
  294. parser.add_option("-g", "--group-file", dest="group_file",
  295. help="The dsh group file to use", default='/etc/dsh/group/all')
  296. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  297. help="Be verbose", default=False)
  298. parser.add_option("-p", "--plot", dest="plot", action="store_true",
  299. help="Plot the data to a png file", default=False)
  300. parser.add_option("-a", "--availability", dest="availability", action="store_true",
  301. help="Plot the data of availability a png file", default=False)
  302.  
  303.  
  304. (options, args) = parser.parse_args()
  305. group = os.path.expanduser(options.group_file)
  306. verbose = options.verbose
  307.  
  308. # Se non mi chiedi di fare niente non hai capito
  309. # come funziono, molto probabilmente.
  310. if not (options.check or options.stats or
  311. options.plot or options.availability):
  312. parser.print_help()
  313.  
  314. if options.check:
  315. for client in LoadClients():
  316. UpdateClientsData(client, IsAlive(client))
  317.  
  318. if options.plot:
  319. UptimePlot("/home/robol/public_html/files/up-clients.png", 5)
  320.  
  321. if options.availability:
  322. AvailabilityPlot("/home/robol/public_html/files/av-clients.png")
  323.  
  324. if options.stats:
  325. try:
  326. for client in LoadClients():
  327. PrintStats(client)
  328. except Exception, e:
  329. print "Errore durante l'esecuzione!\n ==> %s" % e