~m-buck/+junk/gtk-desktop-info

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# plugin_processinfo.py is a plugin for gnome-desktop-info to retrieve process
# information as defined in a template and display it's output
#
#  Author: Kaivalagi
# Created: 21/04/2009
from optparse import OptionParser
from plugin_common import getTypedValue
import codecs
import fileinput
import logging
import os
import re
import shutil
import socket
import statgrab
import subprocess
import traceback


app_name = "gtk-desktop-info"
app_path = os.path.dirname(os.path.abspath(__file__))
module_name = __file__.replace(os.path.dirname (__file__) + "/", "").replace(".pyc","").replace(".py", "")

class ProcessInfoConfig:
    HEADERTEMPLATE = None
    TEMPLATE = None
    LIMIT = None
    SORTBY = None

class ProcessInfoData:
    def __init__(self, name, id, cpu, memory):
        self.name = name
        self.id = id
        self.cpu = cpu
        self.memory = memory

    def __cmp__(self, other):
        return cmp(self.cpu, other.cpu)

    def __str__(self):
        return str(self.name + " - " + self.cpu + " - " + self.memory)

class Output:

    output = u""
    error = u""
    totalkilobytes = None

    def __init__(self, options):
        self.options = options
        self.logger = logging.getLogger(app_name+"."+module_name)
        self.loadConfigData()

    def loadConfigData(self):
        try:

            self.config = ProcessInfoConfig()

            if self.options.config != None:
                # load the config based on options passed in from the main app
                configfilepath = self.options.config
            else:
                # load plugin config from home directory of the user
                configfilepath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/"+module_name+".config")

            if os.path.exists(configfilepath):

                self.logger.info("Loading config settings from \"%s\""%configfilepath)

                for line in fileinput.input(os.path.expanduser(configfilepath)):
                    line = line.strip()
                    if len(line) > 0 and line[0:1] != "#": # ignore commented lines or empty ones

                        splitpos = line.find("=")
                        name = line[:splitpos-1].strip().upper() # config setting name on the left of =
                        value = line[splitpos+1:].split("#")[0].strip()
                        
                        if len(value) > 0:
                            if name == "HEADERTEMPLATE":
                                self.config.HEADERTEMPLATE = getTypedValue(value, "string")
                            elif name == "TEMPLATE":
                                self.config.TEMPLATE = getTypedValue(value, "string")
                            elif name == "LIMIT":
                                self.config.LIMIT = getTypedValue(value, "integer")
                            elif name == "SORTBY":
                                self.config.SORTBY = getTypedValue(value, "string")
                            else:
                                self.logger.error("Unknown option in config file: " + name)
            else:
                self.logger.info("Config data file %s not found, using defaults and setting up config file for next time" % configfilepath)

                userconfigpath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/")
                configsource = os.path.join(app_path, "config/"+module_name+".config")

                if os.path.exists(userconfigpath) == False:
                    os.makedirs(userconfigpath)

                shutil.copy(configsource, configfilepath)

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())

    def BIGBANGgetOutputData(self):
        try:

            processInfoList = statgrab.sg_get_process_stats()

            currentid = os.getpid()
            processInfoDataList = []
            for processInfo in processInfoList:
                name = processInfo['process_name']
                id = processInfo['pid']
                cpu = processInfo['cpu_percent']
                memory = processInfo['proc_size']

                if currentid != id: # ignore info on this process
                    processInfoData = ProcessInfoData(name,str(id),self.formatCPU(cpu),self.formatMemory(memory))
                    processInfoDataList.append(processInfoData)

            if self.config.SORTBY == "CPU":
                processInfoDataList.sort(lambda x, y: cmp(x.cpu, y.cpu))
            elif self.config.SORTBY == "MEM":
                processInfoDataList.sort(lambda x, y: cmp(x.memory, y.memory))
            else:
                processInfoDataList.sort()

            processInfoDataList.reverse()

            return processInfoDataList

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return []

    def BIGBANGformatCPU(self, value, dp=2):
        if dp == 0:
            return str(int(round(value,dp)))+"%" # lose the dp
        else:
            return str(round(value,dp))+"%"

    def BIGBANGformatMemory(self, value):
        return str(value / 1024)+"KB"

    def getOutputData(self):
        try:

            processInfoDataList = []

            proc = subprocess.Popen("cat /proc/meminfo | grep MemTotal:", shell=True, stdout=subprocess.PIPE)
            self.totalkilobytes = float(proc.communicate()[0][10:].replace("kB","").strip(" "))

            proc = subprocess.Popen("top -n 1 -b | sed '1,7d'", shell=True, stdout=subprocess.PIPE)
            lines = proc.communicate()[0].rstrip("\n").split("\n")

            for line in lines:
                name = line[61:].strip(" ")
                id = int(line[:6].strip(" "))
                cpu = float(line[43:46].strip(" "))
                memory = float(line[47:50].strip(" "))

                if cpu > 0 or memory > 0:
                    processInfoData = ProcessInfoData(name,id,cpu,memory)
                    processInfoDataList.append(processInfoData)

            if self.config.SORTBY == "CPU":
                processInfoDataList.sort(lambda x, y: cmp(x.cpu, y.cpu))
            elif self.config.SORTBY == "MEM":
                processInfoDataList.sort(lambda x, y: cmp(x.memory, y.memory))
            else:
                processInfoDataList.sort()

            processInfoDataList.reverse()

            return processInfoDataList

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return []

    def formatMemory(self, percent, total):

        size = total * (percent / 100)
        unit = "KB"

        if size > 1024:
            size = size / 1024.0
            unit = "MB"

        return str(round(size,2))+unit

    def formatCPU(self, percent):
        return str(round(percent,2))+"%"

    def getOutputFromTemplate(self, template, name, id, cpu, memory):

        try:

            output = template

            if name == None or name.strip() == "":
                name = ""
            output = output.replace("[name]",name)

            if id == None or id.strip() == "":
                id = ""
            output = output.replace("[id]",id)

            if cpu == None or cpu.strip() == "":
                cpu = ""
            output = output.replace("[cpu]",cpu)

            if memory == None or memory.strip() == "":
                memory = ""
            output = output.replace("[memory]",memory)

            # get rid of any excess crlf's and add just one
            #output = output.rstrip(" \n")
            #output = output + "\n"

            return output.encode("utf-8")

        except Exception,e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return ""

    def getOutput(self):

        if self.options.noheader == True:
            headertemplatefilepath = app_path+"/templates/processinfoheader.template"
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        elif self.options.headertemplate != None and os.path.exists(os.path.expanduser(self.options.headertemplate)) == True:
            headertemplatefilepath = self.options.headertemplate
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        elif self.config.HEADERTEMPLATE != None and os.path.exists(os.path.expanduser(self.config.HEADERTEMPLATE)) == True:
            headertemplatefilepath = self.config.HEADERTEMPLATE
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        else:
            headertemplatefilepath = app_path+"/templates/processinfoheader.template"
            self.logger.info("Using default header template")

        # load the file
        try:
            inputfile = codecs.open(os.path.expanduser(headertemplatefilepath), encoding='utf-8')
        except Exception, e:
            self.logger.error("Error loading header template file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            headertemplate = inputfile.read()
        finally:
            inputfile.close()

        if self.options.template != None:
            templatefilepath = self.options.template
            self.logger.info("Using custom template file '%s'"%templatefilepath)
        elif self.config.TEMPLATE != None and os.path.exists(os.path.expanduser(self.config.TEMPLATE)) == True:
            templatefilepath = self.config.TEMPLATE
            self.logger.info("Using custom template file '%s'"%templatefilepath)
        else:
            templatefilepath = app_path+"/templates/processinfo.template"
            self.logger.info("Using default template")

        # load the file
        try:
            inputfile = codecs.open(os.path.expanduser(templatefilepath), encoding='utf-8')
        except Exception, e:
            self.logger.error("Error loading template file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            template = inputfile.read()
        finally:
            inputfile.close()

        output = headertemplate

        count = 0
        processInfoDataList = self.getOutputData()

        if len(processInfoDataList) == 0:
            output = "Failed to retrieve process information"
        else:
            for processInfoData in processInfoDataList:
                count += 1
                output = output + self.getOutputFromTemplate(template, processInfoData.name, str(processInfoData.id), self.formatCPU(processInfoData.cpu), self.formatMemory(processInfoData.memory, self.totalkilobytes))

                if self.config.LIMIT != None and count >= self.config.LIMIT:
                    break

        return output.encode("utf-8")

def getHTML(options):
    output = Output(options)
    html = output.getOutput()
    del output
    return html

# to enable testing in isolation
if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("--noheader", dest="noheader", default=False, action="store_true", help=u"Turn off header output. This will override any header template setting to be nothing")
    parser.add_option("--headertemplate", dest="headertemplate", type="string", metavar="FILE", help=u"Override the header template for the plugin, default or config based template ignored.")
    parser.add_option("--template", dest="template", type="string", metavar="FILE", help=u"Override the template for the plugin, default or config based template ignored.")
    parser.add_option("--verbose", dest="verbose", default=False, action="store_true", help=u"Outputs verbose info to the terminal")
    parser.add_option("--version", dest="version", default=False, action="store_true", help=u"Displays the version of the script.")
    parser.add_option("--logfile", dest="logfile", type="string", metavar="FILE", help=u"If a filepath is set, the script logs to the filepath.")

    (options, args) = parser.parse_args()

    output = Output(options)
    html = output.getOutput()
    del output
    print html