Aggiunta possibilità di creare un grafico di quanti

Leonardo Robol [2010-04-18 13:56]
Aggiunta possibilità di creare un grafico di quanti
client erano accesi nell'ultima settimana.
Filename
phcstats.py
diff --git a/phcstats.py b/phcstats.py
index f27ed5f..4f91f48 100755
--- a/phcstats.py
+++ b/phcstats.py
@@ -4,7 +4,9 @@
 # Monitora se i computer dell'aula studenti sono accesi
 # e restituisce delle statistiche a proposito.

-import subprocess, time, os
+import subprocess, time, os, matplotlib
+matplotlib.use ('Agg')
+import numpy as np, pylab
 from optparse import OptionParser

 # Qualche variabile globale
@@ -113,6 +115,76 @@ def PrintStats(client):
     print "IsOnline: %s" % is_online
     print "Uptime: %3.2f %% " % uptime
     print "----------------------------------------------------"
+
+def UptimePlot(filename):
+    """
+    Crea un png con l'uptime dei vari client
+    """
+    # Per ora usiamo come backend gnuplot perché matplotlib
+    # non è installato su poisson e presumibilmente non avrò
+    # voglia di installarlo.
+    clients = LoadClients()
+    samples = 100
+
+    # Mi interesso solo dell'ultima settimana, e prendo un sample
+    # ogni 10 minuti.
+    plot_time = np.linspace(0,-7, samples)
+
+    # Mi servono i dati in secondi
+    plot_time = 86400 * plot_time + float(time.time())
+
+    # Inizializziamo i dati a zero
+    plot_data = np.zeros(samples)
+
+    for client in clients:
+        client_data = ClientUptime(plot_time, client)
+        plot_data += client_data
+
+    # Scriviamo i dati su un file
+    #f_handle = open('/tmp/phcstats.table', 'w')
+    #f_handle.write ("# File generato da PHCStats\n")
+    #for index, t in enumerate(np.linspace(0,-7,samples)):
+    #    f_handle.write(str(t) + " " + str(plot_data[index]) + "\n")
+    #f_handle.close ()
+
+    pylab.title("Client accesi nell'ultima settimana")
+    pylab.xlabel("Giorni passati")
+    pylab.ylabel("Numero di client")
+    pylab.plot (np.linspace(0,-7,samples)[::-1], plot_data)
+    pylab.axis([-7.5, 0, -0.5, 10])
+    f = open(filename, "w")
+    pylab.savefig(f, format='png')
+    f.close()
+
+
+def ClientUptime(times, client):
+    """
+    Ritorna un vettore della stessa lunghezza di times con
+    il valore 1 se il client era acceso e 0 se era spento
+    """
+    data = LoadClientData(client)
+    data = data.items()
+    data.sort()
+    iterator = data.__iter__()
+    item = iterator.next()
+    values = np.zeros(len(times))
+    i = 0
+    for t in times[::-1]:
+        if item[0] > t:
+            values[i] = 0
+            i += 1
+            continue
+        try:
+            while (item[0] < t):
+                item = iterator.next()
+        except StopIteration:
+            return values
+        if (item[1] == True):
+            values[i] = 1
+        else:
+            values[i] = 0
+        i += 1
+    return values



@@ -127,19 +199,24 @@ if __name__ == "__main__":
                       action = "store_true", default = False)
     parser.add_option("-g", "--group-file", dest="group_file",
                       help="The dsh group file to use", default='/etc/dsh/group/all')
+    parser.add_option("-p", "--plot", dest="plot", action="store_true",
+                      help="Plot the data to a png file", default=False)

     (options, args) = parser.parse_args()
     group = os.path.expanduser(options.group_file)

     # Se non mi chiedi di fare niente non hai capito
     # come funziono, molto probabilmente.
-    if not (options.check or options.stats):
+    if not (options.check or options.stats or options.plot):
         parser.print_help()

     if options.check:
         for client in LoadClients():
             UpdateClientsData(client, IsAlive(client))

+    if options.plot:
+        UptimePlot("/home/robol/public_html/files/up-clients.png")
+
     if options.stats:
         try:
             for client in LoadClients():
ViewGit