~ubuntu-branches/ubuntu/saucy/hplip/saucy-proposed

1.6.1 by Mark Purcell
Import upstream version 3.12.10
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 *
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
34
from base import utils,tui,module, os_utils
1.6.1 by Mark Purcell
Import upstream version 3.12.10
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
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
66
        if utils.which('service'):
67
           cmd = os.path.join(utils.which('service'), 'service')+" cups restart"
68
        elif utils.which('systemctl'):
69
           cmd = os.path.join(utils.which('systemctl'), 'systemctl')+" restart %s.service"%service_name
1.6.1 by Mark Purcell
Import upstream version 3.12.10
70
        elif os.path.exists('/etc/init.d/cups'):
71
           cmd = "/etc/init.d/cups restart"
72
        else:
73
           log.error("service command not found.. Please restart cups manually..")
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
74
1.6.1 by Mark Purcell
Import upstream version 3.12.10
75
        if cmd:
76
           log.debug("CUPS restart cmd = %s"%cmd)
77
           sts,out = utils.run(cmd)
78
           if sts == 0:
79
               result = True
80
81
    return result
82
83
############ restore_loglevels() function ############
84
#This function restores CUPS conf file to previous value and restarts CUPS service.
85
86
def restore_loglevels():
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
87
    result = False
1.6.1 by Mark Purcell
Import upstream version 3.12.10
88
    cmd='cp -f %s %s'%(CUPS_BACKUP_FILE,CUPS_FILE)
89
    log.debug("Restoring CUPS conf file. cmd=%s"%cmd)
90
    sts, out = utils.run(cmd)
91
    if sts == 0:
92
       cmd='rm -f %s'%CUPS_BACKUP_FILE
93
       log.debug("Removing Temporary file.. cmd=%s"%cmd)
94
       sts,out = utils.run(cmd)
95
       if sts != 0:
96
            log.warn("Failed to remove the Temporary backup file=%s"%CUPS_BACKUP_FILE)
97
    else:
98
       log.error("Failed to restore cups config file = %s"%CUPS_FILE)
99
    log.debug("Restarting CUPS service")
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
100
1.6.1 by Mark Purcell
Import upstream version 3.12.10
101
    cmd=None
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
102
    if utils.which('service'):
103
       cmd = os.path.join(utils.which('service'), 'service')+" cups restart"
104
    elif utils.which('systemctl'):
105
       cmd = os.path.join(utils.which('systemctl'), 'systemctl')+" restart %s.service"%service_name
1.6.1 by Mark Purcell
Import upstream version 3.12.10
106
    elif os.path.exists('/etc/init.d/cups'):
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
107
       cmd = "/etc/init.d/cups restart"
1.6.1 by Mark Purcell
Import upstream version 3.12.10
108
    else:
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
109
       log.error("service command not found.. Please restart cups manually..")
1.6.1 by Mark Purcell
Import upstream version 3.12.10
110
111
    if cmd:
112
        log.debug("CUPS restart cmd = %s"%cmd)
113
        sts,out = utils.run(cmd)
114
        if sts == 0:
115
           result = True
116
117
    return result
118
119
def usage(typ='text'):
120
    if typ == 'text':
121
        utils.log_title(__title__, __version__)
122
123
    utils.format_text(USAGE, typ, __title__, __mod__, __version__)
124
    sys.exit(0)
125
126
127
def backup_clearLog(strLog):
128
    if os.path.exists(strLog):
129
        iArch =1
130
        while os.path.exists("%s.%d"%(strLog, iArch)) or os.path.exists("%s.%d.gz"%(strLog, iArch)):
131
            iArch +=1
132
        sts,out = utils.run('cp %s %s.%d'%(strLog, strLog, iArch))
133
        if sts != 0:
134
            log.error("Failed to archive %s log file"%strLog)
135
        else:
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
136
            cmd = 'cat /dev/null > %s' % strLog
137
            sts = os_utils.execute(cmd)
1.6.1 by Mark Purcell
Import upstream version 3.12.10
138
            if sts != 0:
139
                log.warn("Failed to clear the %s log file"%strLog)
140
            if utils.which('gzip'):
141
                sts,out = utils.run ('gzip %s.%d'%(strLog, iArch))
142
                if sts != 0:
143
                    log.info("Existing %s log file copied to %s.%d"%(strLog, strLog, iArch))
144
                else:
145
                    log.info("Existing %s log file copied to %s.%d.gz"%(strLog, strLog, iArch))
146
            else:
147
                log.info("Existing %s log file copied to %s.%d"%(strLog, strLog, iArch))
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
148
1.6.1 by Mark Purcell
Import upstream version 3.12.10
149
150
151
USAGE = [(__doc__, "", "name", True),
152
         ("Usage: [su -c /sudo] %s [OPTIONS]" % __mod__, "", "summary", True),
153
         ("e.g. su -c '%s'"%__mod__,"","summary",True),
154
         utils.USAGE_OPTIONS,
155
         utils.USAGE_HELP,
156
         utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
157
        ]
158
159
160
######## Main #######
161
try:
162
    mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
163
                    (INTERACTIVE_MODE, GUI_MODE),
164
                    (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4), True, True)
165
166
    opts, device_uri, printer_name, mode, ui_toolkit, loc = \
167
               mod.parseStdOpts('hl:g', ['help', 'help-rest', 'help-man', 'help-desc', 'logging=', 'debug'],handle_device_printer=False)
168
except getopt.GetoptError, e:
169
    log.error(e.msg)
170
    usage()
171
172
if os.getenv("HPLIP_DEBUG"):
173
    log.set_level('debug')
174
175
for o, a in opts:
176
    if o in ('-h', '--help'):
177
        usage()
178
179
    elif o == '--help-rest':
180
        usage('rest')
181
182
    elif o == '--help-man':
183
        usage('man')
184
185
    elif o == '--help-desc':
186
        print __doc__,
187
        clean_exit(0,False)
188
189
    elif o in ('-l', '--logging'):
190
        log_level = a.lower().strip()
191
        if not log.set_level(log_level):
192
            usage()
193
194
    elif o in ('-g', '--debug'):
195
        log.set_level('debug')
196
197
198
if os.getuid() != 0:
199
    log.error("logCapture needs root permissions since cups service restart requires....")
200
    sys.exit()
201
202
cmd = "mkdir -p %s"%LOG_FILES
203
log.debug("Creating temporary logs folder =%s"%cmd)
204
sts, out = utils.run(cmd)
205
if sts != 0:
206
   log.error("Failed to create directory =%s. Exiting"%LOG_FILES)
207
   sys.exit(1)
208
209
210
enable_log()
211
212
#### Clearing previous logs.. ###########
213
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')
214
if not ok or user_input == "q":
215
    restore_loglevels()
216
    log.warn("User exit")
217
    sys.exit(1)
218
219
if ok and user_input == "y":
220
    backup_clearLog('/var/log/syslog')
221
    backup_clearLog('/var/log/messages')
222
    backup_clearLog('/var/log/cups/error_log')
223
224
File_list, File_list_str =utils.expand_list('%s/*.bmp'%TMP_DIR)
225
if File_list:
226
    cmd= 'rm -rf %s'%File_list_str
227
    log.debug("cmd= %s"%cmd)
228
    sts,out = utils.run(cmd)
229
    if sts != 0:
230
        log.warn("Failed to remove %s files"%File_list_st)
231
232
File_list, File_list_str =utils.expand_list('%s/*.out'%TMP_DIR)
233
if File_list:
234
    cmd= 'rm -rf %s'%File_list_str
235
    log.debug("cmd= %s"%cmd)
236
    sts,out = utils.run(cmd)
237
    if sts != 0:
238
        log.warn("Failed to remove %s files"%File_list_st)
239
240
241
######## Waiting for user to completed job #######
242
while 1:
243
    log.info(log.bold("\nPlease perform the tasks (Print, scan, fax) for which you need to collect the logs."))
244
    ok,user_input =tui.enter_choice("Are you done with taks?. Press (y=yes*, q=quit):",['y','q'], 'y')
245
    if ok and user_input == "y":
246
        break;
247
    elif not ok or user_input == "q":
248
        restore_loglevels()
249
        log.warn("User exit")
250
        sys.exit(1)
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
251
1.6.1 by Mark Purcell
Import upstream version 3.12.10
252
######## Copying logs to Temporary log folder #######
253
sts,out = utils.run('hp-check')
254
if sts != 0:
255
    log.error("Failed to run hp-check command")
256
257
log.debug("Copying logs to Temporary folder =%s"%LOG_FILES)
258
if os.path.exists('/var/log/syslog'):
259
    sts,out = utils.run ('cp -f /var/log/syslog %s/syslog.log'%LOG_FILES)
260
    if sts != 0:
261
      log.error("Failed to capture %s log file."%("/var/log/syslog"))
262
263
if os.path.exists('/var/log/messages'):
264
    sts,out = utils.run('cp -f /var/log/messages %s/messages.log'%LOG_FILES)
265
    if sts != 0:
266
      log.error("Failed to capture %s log file."%("/var/log/messages"))
267
268
if os.path.exists('/var/log/cups/error_log'):
269
    sts,out = utils.run('cp -f /var/log/cups/error_log %s/cups_error_log.log'%LOG_FILES)
270
    if sts != 0:
271
      log.error("Failed to capture %s log file."%("/var/log/cups/error_log"))
272
273
File_list, File_list_str = utils.expand_list('/var/log/hp/*.log')
274
if File_list:
275
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
276
    if sts != 0:
277
      log.error("Failed to capture %s log files."%(File_list_str))
278
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
279
File_list, File_list_str =utils.expand_list('%s/hpcupsfilter*'%TMP_DIR)
280
if File_list:
281
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
282
    if sts != 0:
283
      log.error("Failed to capture %s log files."%(File_list_str))
284
285
File_list, File_list_str =utils.expand_list('%s/hpcups_*'%TMP_DIR)
286
if File_list:
287
    sts,out = utils.run('cp -f %s %s'%(File_list_str, LOG_FILES))
288
    if sts != 0:
289
      log.error("Failed to capture %s log files."%(File_list_str))
1.6.1 by Mark Purcell
Import upstream version 3.12.10
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"))
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
294
sts,out = utils.run('chmod 755  %s'%LOG_FILES)
1.6.1 by Mark Purcell
Import upstream version 3.12.10
295
if sts != 0:
296
    log.error("Failed to change permissions for %s. Only root can access."%(LOG_FILES))
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
297
cmd = 'chmod 666 -R %s/*' % LOG_FILES
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
298
sts = os_utils.execute(cmd)
299
if sts != 0:
300
    log.error("Failed to change permissions for %s. Only root can access."%(LOG_FILES))
1.6.1 by Mark Purcell
Import upstream version 3.12.10
301
302
######## Compressing log files #######
303
cmd = 'tar -zcf %s.tar.gz %s'%(LOG_FOLDER_NAME,LOG_FILES)
304
log.debug("Compressing logs. cmd =%s"%cmd)
305
306
sts_compress,out = utils.run(cmd)
1.7.2 by Till Kamppeter
Import upstream version 3.13.8
307
if sts_compress != 0:
1.6.1 by Mark Purcell
Import upstream version 3.12.10
308
    log.error("Failed to compress %s folder."%(LOG_FILES))
309
else:
310
    log.debug("Changing Permissions of ./%s.tar.gz "%LOG_FOLDER_NAME)
311
    sts,out = utils.run('chmod 666 -R ./%s.tar.gz'%(LOG_FOLDER_NAME))
312
    if sts != 0:
313
        log.error("Failed to change permissions for %s.tar.gz Only root can access."%(LOG_FILES))
314
    log.debug("Removing Temporary log files..")
315
    sts,out = utils.run('rm -rf %s'%LOG_FILES)
316
    if sts != 0:
317
        log.error("Failed to remove temporary files. Remove manually."%(LOG_FILES))
318
319
restore_loglevels()
320
321
log.info("")
322
log.info("")
323
if sts_compress == 0:
324
    log.info(log.bold("Logs are saved as %s/%s.tar.gz"%( os.getcwd(),LOG_FOLDER_NAME)))
1.5.9 by Till Kamppeter
Import upstream version 3.13.2
325
    log.info(log.bold("Please create a bug @https://bugs.launchpad.net/hplip/+filebug and upload this log file."))
1.6.1 by Mark Purcell
Import upstream version 3.12.10
326
else:
327
    log.info(log.bold("Logs are saved as %s/%s"%(os.getcwd(),LOG_FOLDER_NAME)))
328
log.info("")