summaryrefslogtreecommitdiffstats
path: root/firstaidkit
blob: 41f7d462d7aa2054c1513cba67bea114ed6ab93c (plain)
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
#!/usr/bin/python -tt
# First Aid Kit - diagnostic and repair tool for Linux
# Copyright (C) 2007 Martin Sivak <msivak@redhat.com>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import sys, getopt, os, pprint, logging
from threading import Thread
from pyfirstaidkit import Tasker
from pyfirstaidkit import Config
from pyfirstaidkit import reporting
from pyfirstaidkit import initLogger

class Flags:
    print_config = False
    main_help = False
    gui_available = False


class Output(Thread):
    def __init__(self, queue, importance = logging.INFO, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        self._running = True
        self._queue = queue
        self._importance = importance
        self.levelstack = []

    def run(self):

        while self._running:
            message = self._queue.get()
            self.process_message(message)

    def process_message(self, message):
            if message["action"]==reporting.END:
                self._running = False
                return
            elif message["action"]==reporting.QUESTION:
                print "FIXME: Questions not implemented yet"
            elif message["action"]==reporting.START:
                if self._importance<=message["importance"]:
                    print "START: %s (%s)" % (message["origin"].name, message["message"])
                self.levelstack.append(message["origin"].name)
            elif message["action"]==reporting.STOP:
                if self._importance<=message["importance"]:
                    print "STOP: %s (%s)" % (message["origin"].name, message["message"])
                if self.levelstack[-1]!=message["origin"].name:
                    print "WARNING: START/STOP ordering mismatch in stack: "+" / ".join(self.levelstack)
                else:
                    self.levelstack.pop()
            elif message["action"]==reporting.PROGRESS:
                if self._importance<=message["importance"]:
                    print "PROGRESS: %d of %d (%s)" % (message["message"][0], message["message"][1], message["origin"].name)
            elif message["action"]==reporting.INFO:
                if self._importance<=message["importance"]:
                    print "INFO: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.ALERT:
                if self._importance<=message["importance"]:
                    print "ALERT: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.EXCEPTION:
                print "EXCEPTION: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.TABLE:
                if self._importance<=message["importance"]:
                    print "TABLE %s FROM %s" % (message["title"], message["origin"].name,)
                    pprint.pprint(message["message"])
            elif message["action"]==reporting.TREE:
                if self._importance<=message["importance"]:
                    print "TREE %s FROM %s" % (message["title"], message["origin"].name,)
                    pprint.pprint(message["message"])
            elif message["action"]==reporting.ISSUE:
                print "ISSUE FROM %s" % (message["origin"].name,)
                pprint.pprint(str(message["message"]))
            else:
                print "FIXME: Unknown message action %d!!" % (message["action"],)
                print message


class GuiOutput(Thread):
    def __init__(self, cfg, tasker, dir, importance = logging.INFO, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        self.w = MainWindow(cfg, tasker, importance = importance, dir=dir)

    def run(self):
        self.w.run()

def usage(name):
    print """Usage:
 %s [params]
 %s [params] -a         - runs the automated default mode [diagnose]
 %s [params] -a <flow>  - runs the automated mode with specified flow
 %s [params] -a fix     - automated fixing sequence [using the fix flows]
 %s [params] -f <plugin> <flow>
 params is none or more items from:
  -c <config file> - location of the config file
  -r <root path>   - location of the root directory
  -P <path>        - add different plugin path
                     it can be used more than once
  -v               - verbose mode
  -l <method>      - select different log method
  -x <plugin>      - exclude plugin from run
  -F <flag>        - set startup flag
  -g <gui>         - frontend to show results
  -h               - help
  --print-config   - print resulting config file
  --flags          - list all known flags
  --list           - list all plugins
  --info <plugin>  - get information about plugin
  --nodeps         - do not use plugin dependencies
""" % (name, name, name, name, name)

if __name__=="__main__":
    try:
        params, rest = getopt.getopt(sys.argv[1:], "aftc:r:vl:x:F:g:P:h",
                ["list", "info=", "auto", "flow", "task", "config=", "root=",
                "verbose", "log=", "exclude=","flag=", "gui=", "plugin-path=",
                "print-config", "help", "flags", "nodeps"])
    except Exception, e:
        print "\nError parsing the argument line: ",e,"\n"
        usage(sys.argv[0])
        sys.exit(1)

    #
    # Preliminary checks before we parse the options.
    #
    if len(params) == 0:
        Flags.main_help = True

    for key,val in params:
        if key in ("-t", "--task"): #currently not implemented and not documented!
            Config.operation.mode = "task"
            Flags.main_help = False
        elif key in ("-a", "--auto"):
            Config.operation.mode = "auto"
            Flags.main_help = False
        elif key in ("-f", "--flow"):
            Config.operation.mode = "flow"
            Flags.main_help = False
        elif key in ("-c", "--config"):
            Config.read(val)
        elif key in ("-v", "--verbose"):
            Config.operation.verbose = "True"
        elif key in ("-l", "--log"):
            Config.log.method = val
        elif key in ("-x", "--exclude"):
            Config.plugin.disabled = Config.plugin.disabled + ' "%s"' % (val.encode("string-escape"))
            print "Excluding plugin %s\n" % (val,)
        elif key in ("-F", "--flag"):
            Config.operation.flags = Config.operation.flags + ' "%s"' % (val.encode("string-escape"))
        elif key in ("-r", "--root"):
            Config.system.root = val
        elif key in ("-g", "--gui"):
            Config.operation.gui = val
        elif key in ("-P", "--plugin-path"):
            if not os.path.isdir(val):
                print "%s is not a valid directory.  Exiting..."% val
                sys.exit(1)
            Config.set("paths", val.strip("/"), val)
        elif key in ("--print-config"):
            Flags.print_config = True
        elif key in ("-h", "--help"):
            Config.operation.help = "True"
            Flags.main_help = True
        elif key in ("--flags"):
            Config.operation.mode = "flags"
        elif key in ("--list"):
            Config.operation.mode = "list"
        elif key in ("--info"):
            Config.operation.mode = "info"
            Config.operation.params = val
        elif key in ("--nodeps"):
            Config.operation.dependencies = "False"

    if Flags.main_help:
        usage(sys.argv[0])
        sys.exit(1)

    if Config.operation.mode == "flow":
        if len(rest) < 1:
            print "Error in the command arguments.\n"
            usage(sys.argv[0])
            sys.exit(1)
        Config.operation.plugin = rest[0].encode("string-escape")
        if len(rest)<=1:
            Config.operation.mode = "plugin"
        else:
            Config.operation.flow = rest[1].encode("string-escape")
    elif Config.operation.mode == "auto":
        if len(rest)>0:
            Config.operation.mode = "auto-flow"
            Config.operation.flow = rest[0].encode("string-escape")
    elif Config.operation.mode == "task":
        Config.operation.plugin = rest[0]
        Config.operation.task = rest[1]

    if Flags.print_config:
        Config.write(sys.stdout)
        sys.exit(0)

    #Add the frontend path to sys.path
    for idx,p in enumerate(Config.system._list("frontend")):
        sys.path.insert(1+idx, p)

    try:
        import frontend_gtk
        MainWindow = frontend_gtk.MainWindow
        Flags.gui_available = True
    except:
        Flags.gui_available = False

    # TUI/GUI detection
    if not Flags.gui_available and Config.operation.gui=="gui":
        print "GUI mode not available"
        Config.operation.gui="console"

    # TUI has to have operation specified
    if Config.operation.mode == "" and Config.operation.gui!="gui":
        print "\nError in command arguments: no mode specified\n"
        usage(sys.argv[0])
        sys.exit(1)

    # initialize log for plugin system.
    try:
        initLogger(Config)
    except IOError, ioe:
        if ioe[0] == 13:
            #This is probably because the user is not root.
            Config.log.filename = "firstaidkit-" + "%s" % os.getpid()
            initLogger(Config)
        else:
            print ioe
            usage(sys.argv[0])
            sys.exit(1)

    report = reporting.Reports(maxsize = 1, round = True)
    singlerun = Tasker(Config, reporting = report)
    
    if Config.operation.verbose=="False":
        outputThread = Output(singlerun.reporting())
        if Config.operation.gui=="gui":
            outputThreadGui = GuiOutput(Config, singlerun, dir = os.path.dirname(frontend_gtk.__file__))
    else:
        outputThread = Output(singlerun.reporting(), importance = 0)
        if Config.operation.gui=="gui":
            outputThreadGui = GuiOutput(Config, singlerun, importance = 0,  dir = os.path.dirname(frontend_gtk.__file__))

    if Config.operation.gui=="gui":
        singlerun.reporting().notify(outputThreadGui.w.update)
    singlerun.reporting().notify(outputThread.process_message)

    print "Starting the Threads"
    #outputThread.start() #not needed, we use the callback method now
    if Config.operation.gui=="gui":
        outputThreadGui.start()

    if Config.operation.gui=="console": #XXX change this to detection if GUI is not used (eg. noninteractive mode)
        print "Do the work!"

        # Lock the Configuration
        Config.lock()

        try:
            singlerun.run()
        except Exception, e:
            print "!!! Impossible happened!! The First Aid Kit crashed in very unsafe way.\n!!! Please report this to the authors along with the following message.\n\n"
            Config.write(sys.stdout)
            print
            print e
        finally:
            singlerun.end()

    print "Waiting for the Threads"
    #outputThread.join() #not needed, we use the callback method now
    if Config.operation.gui=="gui":
        outputThreadGui.join()

    #make sure everything is deleted
    if Config.operation.gui=="gui":
        del outputThreadGui
    del singlerun

    print "Done."