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 * 10 / 3 / 60 # ~ 10 giorni
  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. LockDatabase()
  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. UnlockDatabase()
  128. return data
  129.  
  130.  
  131. def AppendClientData(client, t, alive):
  132. LockDatabase()
  133. f = open(database_directory + client, 'a')
  134. f.write(str(t) + ":" + str(alive) + "\n")
  135. f.close ()
  136. UnlockDatabase()
  137.  
  138. def UpdateClientsData(client, alive):
  139. """
  140. Aggiorna i dati relativi al client inserendo l'informazione
  141. che in questo momento è acceso.
  142. """
  143. n = " not"
  144. if alive:
  145. n = ""
  146. Verbose ("Appending new data: %s is%s alive" % (client, n))
  147. AppendClientData(client, time.time(), alive)
  148.  
  149. def Availability(client):
  150. """
  151. Return availability of the client
  152. """
  153. data = LoadClientData(client)
  154. d = data.items()
  155. d.sort()
  156. ss = 0
  157. old_time = d[0][0]
  158.  
  159. # Un piccolo integrale sul tempo della funzione
  160. # up(client)
  161. for (time_entry, up) in d[1:]:
  162. if up:
  163. ss += (time_entry - old_time)
  164. old_time = time_entry
  165. ss = ss / (d[-1:][0][0] - d[0][0])
  166.  
  167. uptime = 100.0 * ss
  168. return uptime
  169.  
  170.  
  171. def PrintStats(client):
  172. """
  173. Stampa le statistiche sul client prescelto
  174. """
  175. uptime = Availability(client)
  176. if IsLastAlive(client):
  177. is_online = "yes"
  178. else:
  179. is_online = "no"
  180. print "Client: %s" % client
  181. print "IsOnline: %s" % is_online
  182. print "Uptime: %3.2f %% " % uptime
  183. print "----------------------------------------------------"
  184.  
  185. def UptimePlot(filename, days):
  186. """
  187. Crea un png con l'uptime dei vari client
  188. """
  189.  
  190. clients = LoadClients()
  191. samples = 100
  192.  
  193. # Mi interesso solo dell'ultima days giorni, e prendo un sample
  194. # ogni 10 minuti.
  195. plot_time = np.linspace(0, (-1) * days, samples)
  196.  
  197. # Mi servono i dati in secondi, ma cominciamo da un'ora fa
  198. # per evitare che il grafico vada a 0 per mancanza di dati.
  199. plot_time = 86400 * plot_time + float(time.time()) - 360
  200.  
  201. # Inizializziamo i dati a zero
  202. plot_data = np.zeros(samples)
  203.  
  204. for client in clients:
  205. client_data = ClientUptime(plot_time, client)
  206. plot_data += client_data
  207.  
  208. # Plot vero e proprio
  209. pylab.title("Client accesi negli ultimi %d giorni" % days)
  210. pylab.xlabel("Giorni passati")
  211. pylab.ylabel("Numero di client")
  212. pylab.plot (np.linspace(0,(-1) * days,samples)[::-1], plot_data)
  213. pylab.axis([-0.5 - days, 0, -0.5, len(clients) + 1])
  214. f = open(filename, "w")
  215. pylab.savefig(f, format='png')
  216. f.close()
  217.  
  218. def AvailabilityPlot(filename):
  219. """
  220. Plot an histogram of the availability of the clients
  221. """
  222. clients = LoadClients()
  223. av = []
  224. for client in clients:
  225. av.append (Availability(client))
  226.  
  227. # Istogramma con i dati
  228. pylab.title("Uptime dei client")
  229. pylab.xticks(3 * np.array(range(0,len(av))) + 1.7, clients)
  230. pylab.xlabel("")
  231. pylab.ylabel("% of uptime")
  232. pylab.bar(3 * np.array(range(0, len(av))) + 1, av, width=0.8)
  233. pylab.axis([0 , 2*len(av), 0, 102])
  234. f = open(filename, "w")
  235. pylab.savefig(f, format='png')
  236. f.close()
  237.  
  238.  
  239. def ClientUptime(times, client):
  240. """
  241. Ritorna un vettore della stessa lunghezza di times con
  242. il valore 1 se il client era acceso e 0 se era spento
  243. """
  244. data = LoadClientData(client)
  245. data = data.items()
  246. data.sort()
  247. iterator = data.__iter__()
  248. item = iterator.next()
  249. values = np.zeros(len(times))
  250. i = 0
  251. for t in times[::-1]:
  252. if item[0] > t:
  253. values[i] = 0
  254. i += 1
  255. continue
  256. try:
  257. while (item[0] < t):
  258. item = iterator.next()
  259. except StopIteration:
  260. return values
  261. if (item[1] == True):
  262. values[i] = 1
  263. else:
  264. values[i] = 0
  265. i += 1
  266. return values
  267.  
  268.  
  269.  
  270. if __name__ == "__main__":
  271.  
  272. parser = OptionParser()
  273. parser.add_option("-c", "--check", dest="check",
  274. help = "Check if clients are up and update database",
  275. action = "store_true", default=False)
  276. parser.add_option("-s", "--stats", dest="stats",
  277. help = "Print stats about collected informations",
  278. action = "store_true", default = False)
  279. parser.add_option("-g", "--group-file", dest="group_file",
  280. help="The dsh group file to use", default='/etc/dsh/group/all')
  281. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  282. help="Be verbose", default=False)
  283. parser.add_option("-p", "--plot", dest="plot", action="store_true",
  284. help="Plot the data to a png file", default=False)
  285. parser.add_option("-a", "--availability", dest="availability", action="store_true",
  286. help="Plot the data of availability a png file", default=False)
  287.  
  288.  
  289. (options, args) = parser.parse_args()
  290. group = os.path.expanduser(options.group_file)
  291. verbose = options.verbose
  292.  
  293. # Se non mi chiedi di fare niente non hai capito
  294. # come funziono, molto probabilmente.
  295. if not (options.check or options.stats or
  296. options.plot or options.availability):
  297. parser.print_help()
  298.  
  299. if options.check:
  300. for client in LoadClients():
  301. UpdateClientsData(client, IsAlive(client))
  302.  
  303. if options.plot:
  304. UptimePlot("/home/robol/public_html/files/up-clients.png", 5)
  305.  
  306. if options.availability:
  307. AvailabilityPlot("/home/robol/public_html/files/av-clients.png")
  308.  
  309. if options.stats:
  310. try:
  311. for client in LoadClients():
  312. PrintStats(client)
  313. except Exception, e:
  314. print "Errore durante l'esecuzione!\n ==> %s" % e