~ubuntu-branches/ubuntu/raring/hplip/raring

« back to all changes in this revision

Viewing changes to logcapture.py

  • Committer: Package Import Robot
  • Author(s): Mark Purcell
  • Date: 2012-10-06 15:03:44 UTC
  • mfrom: (1.6.1) (20.1.16 quantal)
  • Revision ID: package-import@ubuntu.com-20121006150344-2p3xz26br0t3hu2q
Tags: 3.12.10-1
* New upstream release
  - Fixes "Network scanning fails (Closes: #683033)
* quilt refresh hplip-syslog-fix-debug-messages-to-error.dpatch
* Fix "error in clean build env" updated debian/rules (Closes: #687129)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
# -*- coding: utf-8 -*-
 
3
#
 
4
# (c) Copyright 2003-2014 Hewlett-Packard Development Company, L.P.
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 
19
#
 
20
# Author: Amarnath Chitumalla
 
21
#
 
22
 
 
23
__version__ = '1.0'
 
24
__title__ = 'HPLIP logs capture Utility'
 
25
__mod__ = 'hp-logcapture'
 
26
__doc__ = """Captures the HPLIP log files."""
 
27
 
 
28
import os
 
29
import sys
 
30
import getopt
 
31
import glob
 
32
 
 
33
from base.g import *
 
34
from base import utils,tui,module
 
35
 
 
36
 
 
37
CUPS_FILE='/etc/cups/cupsd.conf'
 
38
CUPS_BACKUP_FILE='/etc/cups/cupsd.conf_orginal'
 
39
LOG_FOLDER_PATH='./'
 
40
LOG_FOLDER_NAME='hplip_troubleshoot_logs'
 
41
LOG_FILES=LOG_FOLDER_PATH + LOG_FOLDER_NAME
 
42
TMP_DIR='/var/log/hp/tmp'
 
43
############ enable_log() function ############
 
44
#This function changes CUPS conf log level to debug and restarts CUPS service.
 
45
 
 
46
def enable_log():
 
47
    result = False
 
48
    cmd='cp -f %s %s'%(CUPS_FILE,CUPS_BACKUP_FILE)
 
49
    log.debug("Backup CUPS conf file. cmd =%s"%cmd)
 
50
    sts,out=utils.run(cmd)
 
51
    if sts != 0:
 
52
        log.error("Failed to take back cups file=%s"%CUPS_FILE)
 
53
 
 
54
    #check if cups is log level enabled or disable
 
55
    cmd="grep 'LogLevel warn' %s"%CUPS_FILE
 
56
    log.debug ("cmd= %s"%cmd)
 
57
    sts,out=utils.run(cmd)
 
58
    if sts == 0:
 
59
        cmd = "vi -c '%s/LogLevel warn/LogLevel debug\rhpLogLevel 15/' -c 'wq' %s"%("%s",CUPS_FILE)
 
60
        log.debug("Changing 'Log level' to debug. cmd=%s"%cmd)
 
61
        sts, cmd = utils.run(cmd)
 
62
        if sts != 0:
 
63
           log.error("Failed to update Loglevel to Debug in cups=%s"%CUPS_FILE)
 
64
 
 
65
        cmd=None
 
66
        path=utils.which('service')
 
67
        if path:
 
68
           cmd = os.path.join(path, 'service')+" cups restart"
 
69
        elif os.path.exists('/etc/init.d/cups'):
 
70
           cmd = "/etc/init.d/cups restart"
 
71
        else:
 
72
           log.error("service command not found.. Please restart cups manually..")
 
73
        
 
74
        if cmd:
 
75
           log.debug("CUPS restart cmd = %s"%cmd)
 
76
           sts,out = utils.run(cmd)
 
77
           if sts == 0:
 
78
               result = True
 
79
 
 
80
    return result
 
81
 
 
82
############ restore_loglevels() function ############
 
83
#This function restores CUPS conf file to previous value and restarts CUPS service.
 
84
 
 
85
def restore_loglevels():
 
86
    cmd='cp -f %s %s'%(CUPS_BACKUP_FILE,CUPS_FILE)
 
87
    log.debug("Restoring CUPS conf file. cmd=%s"%cmd)
 
88
    sts, out = utils.run(cmd)
 
89
    if sts == 0:
 
90
       cmd='rm -f %s'%CUPS_BACKUP_FILE
 
91
       log.debug("Removing Temporary file.. cmd=%s"%cmd)
 
92
       sts,out = utils.run(cmd)
 
93
       if sts != 0:
 
94
            log.warn("Failed to remove the Temporary backup file=%s"%CUPS_BACKUP_FILE)
 
95
    else:
 
96
       log.error("Failed to restore cups config file = %s"%CUPS_FILE)
 
97
    log.debug("Restarting CUPS service")
 
98
    cmd=None
 
99
    path=utils.which('service')
 
100
    if path:
 
101
        cmd = os.path.join(path, 'service')+" cups restart"
 
102
    elif os.path.exists('/etc/init.d/cups'):
 
103
        cmd = "/etc/init.d/cups restart"
 
104
    else:
 
105
        log.error("service command not found.. Please restart cups manually..")
 
106
 
 
107
    if cmd:
 
108
        log.debug("CUPS restart cmd = %s"%cmd)
 
109
        sts,out = utils.run(cmd)
 
110
        if sts == 0:
 
111
           result = True
 
112
 
 
113
    return result
 
114
 
 
115
def usage(typ='text'):
 
116
    if typ == 'text':
 
117
        utils.log_title(__title__, __version__)
 
118
 
 
119
    utils.format_text(USAGE, typ, __title__, __mod__, __version__)
 
120
    sys.exit(0)
 
121
 
 
122
 
 
123
def backup_clearLog(strLog):
 
124
    if os.path.exists(strLog):
 
125
        iArch =1
 
126
        while os.path.exists("%s.%d"%(strLog, iArch)) or os.path.exists("%s.%d.gz"%(strLog, iArch)):
 
127
            iArch +=1
 
128
        sts,out = utils.run('cp %s %s.%d'%(strLog, strLog, iArch))
 
129
        if sts != 0:
 
130
            log.error("Failed to archive %s log file"%strLog)
 
131
        else:
 
132
#            sts,out = utils.run('cp /dev/null %s'%strLog)
 
133
            sts = os.system('cat /dev/null > %s'%strLog)
 
134
            if sts != 0:
 
135
                log.warn("Failed to clear the %s log file"%strLog)
 
136
            if utils.which('gzip'):
 
137
                sts,out = utils.run ('gzip %s.%d'%(strLog, iArch))
 
138
                if sts != 0:
 
139
                    log.info("Existing %s log file copied to %s.%d"%(strLog, strLog, iArch))
 
140
                else:
 
141
                    log.info("Existing %s log file copied to %s.%d.gz"%(strLog, strLog, iArch))
 
142
            else:
 
143
                log.info("Existing %s log file copied to %s.%d"%(strLog, strLog, iArch))
 
144
         
 
145
 
 
146
 
 
147
USAGE = [(__doc__, "", "name", True),
 
148
         ("Usage: [su -c /sudo] %s [OPTIONS]" % __mod__, "", "summary", True),
 
149
         ("e.g. su -c '%s'"%__mod__,"","summary",True),
 
150
         utils.USAGE_OPTIONS,
 
151
         utils.USAGE_HELP,
 
152
         utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
 
153
        ]
 
154
 
 
155
 
 
156
######## Main #######
 
157
try:
 
158
    mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
 
159
                    (INTERACTIVE_MODE, GUI_MODE),
 
160
                    (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4), True, True)
 
161
 
 
162
    opts, device_uri, printer_name, mode, ui_toolkit, loc = \
 
163
               mod.parseStdOpts('hl:g', ['help', 'help-rest', 'help-man', 'help-desc', 'logging=', 'debug'],handle_device_printer=False)
 
164
except getopt.GetoptError, e:
 
165
    log.error(e.msg)
 
166
    usage()
 
167
 
 
168
if os.getenv("HPLIP_DEBUG"):
 
169
    log.set_level('debug')
 
170
 
 
171
for o, a in opts:
 
172
    if o in ('-h', '--help'):
 
173
        usage()
 
174
 
 
175
    elif o == '--help-rest':
 
176
        usage('rest')
 
177
 
 
178
    elif o == '--help-man':
 
179
        usage('man')
 
180
 
 
181
    elif o == '--help-desc':
 
182
        print __doc__,
 
183
        clean_exit(0,False)
 
184
 
 
185
    elif o in ('-l', '--logging'):
 
186
        log_level = a.lower().strip()
 
187
        if not log.set_level(log_level):
 
188
            usage()
 
189
 
 
190
    elif o in ('-g', '--debug'):
 
191
        log.set_level('debug')
 
192
 
 
193
 
 
194
if os.getuid() != 0:
 
195
    log.error("logCapture needs root permissions since cups service restart requires....")
 
196
    sys.exit()
 
197
 
 
198
cmd = "mkdir -p %s"%LOG_FILES
 
199
log.debug("Creating temporary logs folder =%s"%cmd)
 
200
sts, out = utils.run(cmd)
 
201
if sts != 0:
 
202
   log.error("Failed to create directory =%s. Exiting"%LOG_FILES)
 
203
   sys.exit(1)
 
204
 
 
205
 
 
206
enable_log()
 
207
 
 
208
#### Clearing previous logs.. ###########
 
209
ok,user_input = tui.enter_choice("Archiving system logs (i.e. syslog, message, error_log). Press (y=yes*, n=no, q=quit):",['y', 'n','q'], 'y')
 
210
if not ok or user_input == "q":
 
211
    restore_loglevels()
 
212
    log.warn("User exit")
 
213
    sys.exit(1)
 
214
 
 
215
if ok and user_input == "y":
 
216
    backup_clearLog('/var/log/syslog')
 
217
    backup_clearLog('/var/log/messages')
 
218
    backup_clearLog('/var/log/cups/error_log')
 
219
 
 
220
File_list, File_list_str =utils.expand_list('%s/*.bmp'%TMP_DIR)
 
221
if File_list:
 
222
    cmd= 'rm -rf %s'%File_list_str
 
223
    log.debug("cmd= %s"%cmd)
 
224
    sts,out = utils.run(cmd)
 
225
    if sts != 0:
 
226
        log.warn("Failed to remove %s files"%File_list_st)
 
227
 
 
228
File_list, File_list_str =utils.expand_list('%s/*.out'%TMP_DIR)
 
229
if File_list:
 
230
    cmd= 'rm -rf %s'%File_list_str
 
231
    log.debug("cmd= %s"%cmd)
 
232
    sts,out = utils.run(cmd)
 
233
    if sts != 0:
 
234
        log.warn("Failed to remove %s files"%File_list_st)
 
235
 
 
236
 
 
237
######## Waiting for user to completed job #######
 
238
while 1:
 
239
    log.info(log.bold("\nPlease perform the tasks (Print, scan, fax) for which you need to collect the logs."))
 
240
    ok,user_input =tui.enter_choice("Are you done with taks?. Press (y=yes*, q=quit):",['y','q'], 'y')
 
241
    if ok and user_input == "y":
 
242
        break;
 
243
    elif not ok or user_input == "q":
 
244
        restore_loglevels()
 
245
        log.warn("User exit")
 
246
        sys.exit(1)
 
247
   
 
248
######## Copying logs to Temporary log folder #######
 
249
sts,out = utils.run('hp-check')
 
250
if sts != 0:
 
251
    log.error("Failed to run hp-check command")
 
252
 
 
253
log.debug("Copying logs to Temporary folder =%s"%LOG_FILES)
 
254
if os.path.exists('/var/log/syslog'):
 
255
    sts,out = utils.run ('cp -f /var/log/syslog %s/syslog.log'%LOG_FILES)
 
256
    if sts != 0:
 
257
      log.error("Failed to capture %s log file."%("/var/log/syslog"))
 
258
 
 
259
if os.path.exists('/var/log/messages'):
 
260
    sts,out = utils.run('cp -f /var/log/messages %s/messages.log'%LOG_FILES)
 
261
    if sts != 0:
 
262
      log.error("Failed to capture %s log file."%("/var/log/messages"))
 
263
 
 
264
 
 
265
if os.path.exists('/var/log/cups/error_log'):
 
266
    sts,out = utils.run('cp -f /var/log/cups/error_log %s/cups_error_log.log'%LOG_FILES)
 
267
    if sts != 0:
 
268
      log.error("Failed to capture %s log file."%("/var/log/cups/error_log"))
 
269
 
 
270
 
 
271
File_list, File_list_str = utils.expand_list('/var/log/hp/*.log')
 
272
if File_list:
 
273
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
 
274
    if sts != 0:
 
275
      log.error("Failed to capture %s log files."%(File_list_str))
 
276
 
 
277
File_list, File_list_str =utils.expand_list('%s/*.bmp'%TMP_DIR)
 
278
if File_list:
 
279
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
 
280
    if sts != 0:
 
281
      log.error("Failed to capture %s log files."%(File_list_str))
 
282
 
 
283
 
 
284
File_list, File_list_str =utils.expand_list('%s/*.out'%TMP_DIR)
 
285
if File_list:
 
286
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
 
287
    if sts != 0:
 
288
      log.error("Failed to capture %s log files."%(File_list_str))
 
289
 
 
290
 
 
291
sts,out = utils.run('mv -f ./hp-check.log %s'%LOG_FILES)
 
292
if sts != 0:
 
293
    log.error("Failed to capture %s log files."%("./hp-check.log"))
 
294
ists,out = utils.run('chmod 666 -R %s'%LOG_FILES)
 
295
if sts != 0:
 
296
    log.error("Failed to change permissions for %s. Only root can access."%(LOG_FILES))
 
297
 
 
298
######## Compressing log files #######
 
299
cmd = 'tar -zcf %s.tar.gz %s'%(LOG_FOLDER_NAME,LOG_FILES)
 
300
log.debug("Compressing logs. cmd =%s"%cmd)
 
301
 
 
302
sts_compress,out = utils.run(cmd)
 
303
if sts != 0:
 
304
    log.error("Failed to compress %s folder."%(LOG_FILES))
 
305
else:
 
306
    log.debug("Changing Permissions of ./%s.tar.gz "%LOG_FOLDER_NAME)
 
307
    sts,out = utils.run('chmod 666 -R ./%s.tar.gz'%(LOG_FOLDER_NAME))
 
308
    if sts != 0:
 
309
        log.error("Failed to change permissions for %s.tar.gz Only root can access."%(LOG_FILES))
 
310
    log.debug("Removing Temporary log files..")
 
311
    sts,out = utils.run('rm -rf %s'%LOG_FILES)
 
312
    if sts != 0:
 
313
        log.error("Failed to remove temporary files. Remove manually."%(LOG_FILES))
 
314
 
 
315
restore_loglevels()
 
316
 
 
317
log.info("")
 
318
log.info("")
 
319
if sts_compress == 0:
 
320
    log.info(log.bold("Logs are saved as %s/%s.tar.gz"%( os.getcwd(),LOG_FOLDER_NAME)))
 
321
else:
 
322
    log.info(log.bold("Logs are saved as %s/%s"%(os.getcwd(),LOG_FOLDER_NAME)))
 
323
log.info("")