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