GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Failed
Push — develop-v1.6.0 ( 9d5181...7efb31 )
by
unknown
04:49
created

DebugInfoCollector   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 450
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 450
rs 5.1724
c 0
b 0
f 0
wmc 57

15 Methods

Rating   Name   Duplication   Size   Complexity  
F run() 0 46 9
A __init__() 0 50 1
A add_user_info() 0 12 2
B collect_pack_content() 0 26 5
A add_shell_command_output() 0 18 3
B get_system_information() 0 88 5
A format_output_filename() 0 13 1
B create_tarball() 0 27 3
B upload_archive() 0 21 6
A collect_config_files() 0 15 1
A add_system_information() 0 14 2
A collect_logs() 0 11 2
A create_temp_directories() 0 16 2
B encrypt_archive() 0 33 5
F create_archive() 0 44 10

How to fix   Complexity   

Complex Class

Complex classes like DebugInfoCollector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
"""
17
This script submits information which helps StackStorm employees debug different
18
user problems and issues to StackStorm.
19
20
By default the following information is included:
21
22
- Logs from /var/log/st2
23
- StackStorm and mistral config file (/etc/st2/st2.conf, /etc/mistral/mistral.conf)
24
- All the content (integration packs).
25
- Information about your system and StackStorm installation (Operating system,
26
  Python version, StackStorm version, Mistral version)
27
28
Note: This script currently assumes it's running on Linux.
29
"""
30
31
import os
32
import sys
33
import shutil
34
import socket
35
import logging
36
import tarfile
37
import argparse
38
import platform
39
import tempfile
40
import httplib
41
42
import six
43
import yaml
44
import gnupg
45
import requests
46
from distutils.spawn import find_executable
47
48
import st2common
49
from st2common.content.utils import get_packs_base_paths
50
from st2common import __version__ as st2_version
51
from st2common import config
52
from st2common.util import date as date_utils
53
from st2common.util.shell import run_command
54
from st2debug.constants import GPG_KEY
55
from st2debug.constants import GPG_KEY_FINGERPRINT
56
from st2debug.constants import S3_BUCKET_URL
57
from st2debug.constants import COMPANY_NAME
58
from st2debug.constants import ARG_NAMES
59
from st2debug.utils.fs import copy_files
60
from st2debug.utils.fs import get_full_file_list
61
from st2debug.utils.fs import get_dirs_in_path
62
from st2debug.utils.fs import remove_file
63
from st2debug.utils.fs import remove_dir
64
from st2debug.utils.system_info import get_cpu_info
65
from st2debug.utils.system_info import get_memory_info
66
from st2debug.utils.system_info import get_package_list
67
from st2debug.utils.git_utils import get_repo_latest_revision_hash
68
from st2debug.processors import process_st2_config
69
from st2debug.processors import process_mistral_config
70
from st2debug.processors import process_content_pack_dir
71
72
LOG = logging.getLogger(__name__)
73
74
# Constants
75
GPG_INSTALLED = find_executable('gpg') is not None
76
77
LOG_FILE_PATHS = [
78
    '/var/log/st2/*.log',
79
    '/var/log/mistral*.log'
80
]
81
82
ST2_CONFIG_FILE_PATH = '/etc/st2/st2.conf'
83
MISTRAL_CONFIG_FILE_PATH = '/etc/mistral/mistral.conf'
84
85
SHELL_COMMANDS = []
86
87
# Directory structure inside tarball
88
DIRECTORY_STRUCTURE = [
89
    'configs/',
90
    'logs/',
91
    'content/',
92
    'commands/'
93
]
94
95
OUTPUT_PATHS = {
96
    'logs': 'logs/',
97
    'configs': 'configs/',
98
    'content': 'content/',
99
    'commands': 'commands/',
100
    'system_info': 'system_info.yaml',
101
    'user_info': 'user_info.yaml'
102
}
103
104
# Options which should be removed from the st2 config
105
ST2_CONF_OPTIONS_TO_REMOVE = {
106
    'database': ['username', 'password'],
107
    'messaging': ['url']
108
}
109
110
REMOVE_VALUE_NAME = '**removed**'
111
112
OUTPUT_FILENAME_TEMPLATE = 'st2-debug-output-%(hostname)s-%(date)s.tar.gz'
113
114
DATE_FORMAT = '%Y-%m-%d-%H%M%S'
115
116
try:
117
    config.parse_args(args=[])
118
except Exception:
119
    pass
120
121
122
def setup_logging():
123
    root = LOG
124
    root.setLevel(logging.INFO)
125
126
    ch = logging.StreamHandler(sys.stdout)
127
    ch.setLevel(logging.DEBUG)
128
    formatter = logging.Formatter('%(asctime)s  %(levelname)s - %(message)s')
129
    ch.setFormatter(formatter)
130
    root.addHandler(ch)
131
132
133
class DebugInfoCollector(object):
134
    def __init__(self, include_logs, include_configs, include_content, include_system_info,
135
                 include_shell_commands=False, user_info=None, debug=False, config_file=None,
136
                 output_path=None):
137
        """
138
        Initialize a DebugInfoCollector object.
139
140
        :param include_logs: Include log files in generated archive.
141
        :type include_logs: ``bool``
142
        :param include_configs: Include config files in generated archive.
143
        :type include_configs: ``bool``
144
        :param include_content: Include pack contents in generated archive.
145
        :type include_content: ``bool``
146
        :param include_system_info: Include system information in generated archive.
147
        :type include_system_info: ``bool``
148
        :param include_shell_commands: Include shell command output in generated archive.
149
        :type include_shell_commands: ``bool``
150
        :param user_info: User info to be included in generated archive.
151
        :type user_info: ``dict``
152
        :param debug: Enable debug logging.
153
        :type debug: ``bool``
154
        :param config_file: Values from config file to override defaults.
155
        :type config_file: ``dict``
156
        :param output_path: Path to write output file to. (optional)
157
        :type output_path: ``str``
158
        """
159
        self.include_logs = include_logs
160
        self.include_configs = include_configs
161
        self.include_content = include_content
162
        self.include_system_info = include_system_info
163
        self.include_shell_commands = include_shell_commands
164
        self.user_info = user_info
165
        self.debug = debug
166
        self.output_path = output_path
167
168
        config_file = config_file or {}
169
        self.st2_config_file_path = config_file.get('st2_config_file_path', ST2_CONFIG_FILE_PATH)
170
        self.mistral_config_file_path = config_file.get('mistral_config_file_path',
171
                                                        MISTRAL_CONFIG_FILE_PATH)
172
        self.log_file_paths = config_file.get('log_file_paths', LOG_FILE_PATHS[:])
173
        self.gpg_key = config_file.get('gpg_key', GPG_KEY)
174
        self.gpg_key_fingerprint = config_file.get('gpg_key_fingerprint', GPG_KEY_FINGERPRINT)
175
        self.s3_bucket_url = config_file.get('s3_bucket_url', S3_BUCKET_URL)
176
        self.company_name = config_file.get('company_name', COMPANY_NAME)
177
        self.shell_commands = config_file.get('shell_commands', SHELL_COMMANDS)
178
179
        self.st2_config_file_name = os.path.basename(self.st2_config_file_path)
180
        self.mistral_config_file_name = os.path.basename(self.mistral_config_file_path)
181
        self.config_file_paths = [
182
            self.st2_config_file_path,
183
            self.mistral_config_file_path
184
        ]
185
186
    def run(self, encrypt=False, upload=False, existing_file=None):
187
        """
188
        Run the specified steps.
189
190
        :param encrypt: If true, encrypt the archive file.
191
        :param encrypt: ``bool``
192
        :param upload: If true, upload the resulting file.
193
        :param upload: ``bool``
194
        :param existing_file: Path to an existing archive file. If not specified a new
195
        archive will be created.
196
        :param existing_file: ``str``
197
        """
198
        temp_files = []
199
200
        try:
201
            if existing_file:
202
                working_file = existing_file
203
            else:
204
                # Create a new archive if an existing file hasn't been provided
205
                working_file = self.create_archive()
206
                if not encrypt and not upload:
207
                    LOG.info('Debug tarball successfully '
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
208
                             'generated and can be reviewed at: %s' % working_file)
209
                else:
210
                    temp_files.append(working_file)
211
212
            if encrypt:
213
                working_file = self.encrypt_archive(archive_file_path=working_file)
214
                if not upload:
215
                    LOG.info('Encrypted debug tarball successfully generated at: %s' %
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
216
                             working_file)
217
                else:
218
                    temp_files.append(working_file)
219
220
            if upload:
221
                self.upload_archive(archive_file_path=working_file)
222
                tarball_name = os.path.basename(working_file)
223
                LOG.info('Debug tarball successfully uploaded to %s (name=%s)' %
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
224
                         (self.company_name, tarball_name))
225
                LOG.info('When communicating with support, please let them know the '
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
226
                         'tarball name - %s' % tarball_name)
227
        finally:
228
            # Remove temp files
229
            for temp_file in temp_files:
230
                assert temp_file.startswith('/tmp')
231
                remove_file(file_path=temp_file)
232
233
    def create_archive(self):
234
        """
235
        Create an archive with debugging information.
236
237
        :return: Path to the generated archive.
238
        :rtype: ``str``
239
        """
240
241
        try:
242
            # 1. Create temporary directory with the final directory structure where we will move
243
            # files which will be processed and included in the tarball
244
            self._temp_dir_path = self.create_temp_directories()
245
246
            # Prepend temp_dir_path to OUTPUT_PATHS
247
            output_paths = {}
248
            for key, path in OUTPUT_PATHS.iteritems():
249
                output_paths[key] = os.path.join(self._temp_dir_path, path)
250
251
            # 2. Moves all the files to the temporary directory
252
            LOG.info('Collecting files...')
253
            if self.include_logs:
254
                self.collect_logs(output_paths['logs'])
255
            if self.include_configs:
256
                self.collect_config_files(output_paths['configs'])
257
            if self.include_content:
258
                self.collect_pack_content(output_paths['content'])
259
            if self.include_system_info:
260
                self.add_system_information(output_paths['system_info'])
261
            if self.user_info:
262
                self.add_user_info(output_paths['user_info'])
263
            if self.include_shell_commands:
264
                self.add_shell_command_output(output_paths['commands'])
265
266
            # 3. Create a tarball
267
            return self.create_tarball(self._temp_dir_path)
268
269
        except Exception as e:
270
            LOG.exception('Failed to generate tarball', exc_info=True)
271
            raise e
272
273
        finally:
274
            # Ensure temp files are removed regardless of success or failure
275
            assert self._temp_dir_path.startswith('/tmp')
276
            remove_dir(self._temp_dir_path)
277
278
    def encrypt_archive(self, archive_file_path):
279
        """
280
        Encrypt archive with debugging information using our public key.
281
282
        :param archive_file_path: Path to the non-encrypted tarball file.
283
        :type archive_file_path: ``str``
284
285
        :return: Path to the encrypted archive.
286
        :rtype: ``str``
287
        """
288
        try:
289
            assert archive_file_path.endswith('.tar.gz')
290
291
            LOG.info('Encrypting tarball...')
292
            gpg = gnupg.GPG(verbose=self.debug)
293
294
            # Import our public key
295
            import_result = gpg.import_keys(self.gpg_key)
296
            # pylint: disable=no-member
297
            assert import_result.count == 1
298
299
            encrypted_archive_output_file_name = os.path.basename(archive_file_path) + '.asc'
300
            encrypted_archive_output_file_path = os.path.join('/tmp',
301
                                                              encrypted_archive_output_file_name)
302
            with open(archive_file_path, 'rb') as fp:
303
                gpg.encrypt_file(file=fp,
304
                                 recipients=self.gpg_key_fingerprint,
305
                                 always_trust=True,
306
                                 output=encrypted_archive_output_file_path)
307
            return encrypted_archive_output_file_path
308
        except Exception as e:
309
            LOG.exception('Failed to encrypt archive', exc_info=True)
310
            raise e
311
312
    def upload_archive(self, archive_file_path):
313
        """
314
        Upload the encrypted archive.
315
316
        :param archive_file_path: Path to the encrypted tarball file.
317
        :type archive_file_path: ``str``
318
        """
319
        try:
320
            assert archive_file_path.endswith('.asc')
321
322
            LOG.debug('Uploading tarball...')
323
            file_name = os.path.basename(archive_file_path)
324
            url = self.s3_bucket_url + file_name
325
            assert url.startswith('https://')
326
327
            with open(archive_file_path, 'rb') as fp:
328
                response = requests.put(url=url, files={'file': fp})
329
            assert response.status_code == httplib.OK
330
        except Exception as e:
331
            LOG.exception('Failed to upload tarball to %s' % self.company_name, exc_info=True)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
332
            raise e
333
334
    def collect_logs(self, output_path):
335
        """
336
        Copy log files to the output path.
337
338
        :param output_path: Path where log files will be copied to.
339
        :type output_path: ``str``
340
        """
341
        LOG.debug('Including log files')
342
        for file_path_glob in self.log_file_paths:
343
            log_file_list = get_full_file_list(file_path_glob=file_path_glob)
344
            copy_files(file_paths=log_file_list, destination=output_path)
345
346
    def collect_config_files(self, output_path):
347
        """
348
        Copy config files to the output path.
349
350
        :param output_path: Path where config files will be copied to.
351
        :type output_path: ``str``
352
        """
353
        LOG.debug('Including config files')
354
        copy_files(file_paths=self.config_file_paths, destination=output_path)
355
356
        st2_config_path = os.path.join(output_path, self.st2_config_file_name)
357
        process_st2_config(config_path=st2_config_path)
358
359
        mistral_config_path = os.path.join(output_path, self.mistral_config_file_name)
360
        process_mistral_config(config_path=mistral_config_path)
361
362
    @staticmethod
363
    def collect_pack_content(output_path):
364
        """
365
        Copy pack contents to the output path.
366
367
        :param output_path: Path where pack contents will be copied to.
368
        :type output_path: ``str``
369
        """
370
        LOG.debug('Including content')
371
372
        packs_base_paths = get_packs_base_paths()
373
        for index, packs_base_path in enumerate(packs_base_paths, 1):
374
            dst = os.path.join(output_path, 'dir-%s' % index)
375
376
            try:
377
                shutil.copytree(src=packs_base_path, dst=dst)
378
            except IOError:
379
                continue
380
381
        base_pack_dirs = get_dirs_in_path(file_path=output_path)
382
383
        for base_pack_dir in base_pack_dirs:
384
            pack_dirs = get_dirs_in_path(file_path=base_pack_dir)
385
386
            for pack_dir in pack_dirs:
387
                process_content_pack_dir(pack_dir=pack_dir)
388
389
    def add_system_information(self, output_path):
390
        """
391
        Collect and write system information to output path.
392
393
        :param output_path: Path where system information will be written to.
394
        :type output_path: ``str``
395
        """
396
        LOG.debug('Including system info')
397
398
        system_information = yaml.dump(self.get_system_information(),
399
                                       default_flow_style=False)
400
401
        with open(output_path, 'w') as fp:
402
            fp.write(system_information)
403
404
    def add_user_info(self, output_path):
405
        """
406
        Write user info to output path as YAML.
407
408
        :param output_path: Path where user info will be written.
409
        :type output_path: ``str``
410
        """
411
        LOG.debug('Including user info')
412
        user_info = yaml.dump(self.user_info, default_flow_style=False)
413
414
        with open(output_path, 'w') as fp:
415
            fp.write(user_info)
416
417
    def add_shell_command_output(self, output_path):
418
        """"
419
        Get output of the required shell command and redirect the output to output path.
420
421
        :param output_path: Directory where output files will be written
422
        :param output_path: ``str``
423
        """
424
        LOG.debug('Including the required shell commands output files')
425
        for cmd in self.shell_commands:
426
            output_file = os.path.join(output_path, '%s.txt' % self.format_output_filename(cmd))
427
            exit_code, stdout, stderr = run_command(cmd=cmd, shell=True, cwd=output_path)
428
            with open(output_file, 'w') as fp:
429
                fp.write('[BEGIN STDOUT]\n')
430
                fp.write(stdout)
431
                fp.write('[END STDOUT]\n')
432
                fp.write('[BEGIN STDERR]\n')
433
                fp.write(stderr)
434
                fp.write('[END STDERR]')
435
436
    def create_tarball(self, temp_dir_path):
437
        """
438
        Create tarball with the contents of temp_dir_path.
439
440
        Tarball will be written to self.output_path, if set. Otherwise it will
441
        be written to /tmp a name generated according to OUTPUT_FILENAME_TEMPLATE.
442
443
        :param temp_dir_path: Base directory to include in tarbal.
444
        :type temp_dir_path: ``str``
445
446
        :return: Path to the created tarball.
447
        :rtype: ``str``
448
        """
449
        LOG.info('Creating tarball...')
450
        if self.output_path:
451
            output_file_path = self.output_path
452
        else:
453
            date = date_utils.get_datetime_utc_now().strftime(DATE_FORMAT)
454
            values = {'hostname': socket.gethostname(), 'date': date}
455
456
            output_file_name = OUTPUT_FILENAME_TEMPLATE % values
457
            output_file_path = os.path.join('/tmp', output_file_name)
458
459
        with tarfile.open(output_file_path, 'w:gz') as tar:
460
            tar.add(temp_dir_path, arcname='')
461
462
        return output_file_path
463
464
    @staticmethod
465
    def create_temp_directories():
466
        """
467
        Creates a new temp directory and creates the directory structure as defined
468
        by DIRECTORY_STRUCTURE.
469
470
        :return: Path to temp directory.
471
        :rtype: ``str``
472
        """
473
        temp_dir_path = tempfile.mkdtemp()
474
475
        for directory_name in DIRECTORY_STRUCTURE:
476
            full_path = os.path.join(temp_dir_path, directory_name)
477
            os.mkdir(full_path)
478
479
        return temp_dir_path
480
481
    @staticmethod
482
    def format_output_filename(cmd):
483
        """"
484
        Remove whitespace and special characters from a shell command.
485
486
        Used to create filename-safe representations of a shell command.
487
488
        :param cmd: Shell command.
489
        :type cmd: ``str``
490
        :return: Formatted filename.
491
        :rtype: ``str``
492
        """
493
        return cmd.translate(None, """ !@#$%^&*()[]{};:,./<>?\|`~=+"'""")
0 ignored issues
show
Bug introduced by
A suspicious escape sequence \| was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
494
495
    @staticmethod
496
    def get_system_information():
497
        """
498
        Retrieve system information which is included in the report.
499
500
        :rtype: ``dict``
501
        """
502
        system_information = {
503
            'hostname': socket.gethostname(),
504
            'operating_system': {},
505
            'hardware': {
506
                'cpu': {},
507
                'memory': {}
508
            },
509
            'python': {},
510
            'stackstorm': {},
511
            'mistral': {}
512
        }
513
514
        # Operating system information
515
        system_information['operating_system']['system'] = platform.system()
516
        system_information['operating_system']['release'] = platform.release()
517
        system_information['operating_system']['operating_system'] = platform.platform()
518
        system_information['operating_system']['platform'] = platform.system()
519
        system_information['operating_system']['architecture'] = ' '.join(platform.architecture())
520
521
        if platform.system().lower() == 'linux':
522
            distribution = ' '.join(platform.linux_distribution())
523
            system_information['operating_system']['distribution'] = distribution
524
525
        system_information['python']['version'] = sys.version.split('\n')[0]
526
527
        # Hardware information
528
        cpu_info = get_cpu_info()
529
530
        if cpu_info:
531
            core_count = len(cpu_info)
532
            model = cpu_info[0]['model_name']
533
            system_information['hardware']['cpu'] = {
534
                'core_count': core_count,
535
                'model_name': model
536
            }
537
        else:
538
            # Unsupported platform
539
            system_information['hardware']['cpu'] = 'unsupported platform'
540
541
        memory_info = get_memory_info()
542
543
        if memory_info:
544
            total = memory_info['MemTotal'] / 1024
545
            free = memory_info['MemFree'] / 1024
546
            used = (total - free)
547
            system_information['hardware']['memory'] = {
548
                'total': total,
549
                'used': used,
550
                'free': free
551
            }
552
        else:
553
            # Unsupported platform
554
            system_information['hardware']['memory'] = 'unsupported platform'
555
556
        # StackStorm information
557
        system_information['stackstorm']['version'] = st2_version
558
559
        st2common_path = st2common.__file__
560
        st2common_path = os.path.dirname(st2common_path)
561
562
        if 'st2common/st2common' in st2common_path:
563
            # Assume we are running source install
564
            base_install_path = st2common_path.replace('/st2common/st2common', '')
565
566
            revision_hash = get_repo_latest_revision_hash(repo_path=base_install_path)
567
568
            system_information['stackstorm']['installation_method'] = 'source'
569
            system_information['stackstorm']['revision_hash'] = revision_hash
570
        else:
571
            package_list = get_package_list(name_startswith='st2')
572
573
            system_information['stackstorm']['installation_method'] = 'package'
574
            system_information['stackstorm']['packages'] = package_list
575
576
        # Mistral information
577
        repo_path = '/opt/openstack/mistral'
578
        revision_hash = get_repo_latest_revision_hash(repo_path=repo_path)
579
        system_information['mistral']['installation_method'] = 'source'
580
        system_information['mistral']['revision_hash'] = revision_hash
581
582
        return system_information
583
584
585
def main():
586
    parser = argparse.ArgumentParser(description='')
587
    parser.add_argument('--exclude-logs', action='store_true', default=False,
588
                        help='Don\'t include logs in the generated tarball')
589
    parser.add_argument('--exclude-configs', action='store_true', default=False,
590
                        help='Don\'t include configs in the generated tarball')
591
    parser.add_argument('--exclude-content', action='store_true', default=False,
592
                        help='Don\'t include content packs in the generated tarball')
593
    parser.add_argument('--exclude-system-info', action='store_true', default=False,
594
                        help='Don\'t include system information in the generated tarball')
595
    parser.add_argument('--exclude-shell-commands', action='store_true', default=False,
596
                        help='Don\'t include shell commands output in the generated tarball')
597
    parser.add_argument('--yes', action='store_true', default=False,
598
                        help='Run in non-interactive mode and answer "yes" to all the questions')
599
    parser.add_argument('--review', action='store_true', default=False,
600
                        help='Generate the tarball, but don\'t encrypt and upload it')
601
    parser.add_argument('--debug', action='store_true', default=False,
602
                        help='Enable debug mode')
603
    parser.add_argument('--config', action='store', default=None,
604
                        help='Get required configurations from config file')
605
    parser.add_argument('--output', action='store', default=None,
606
                        help='Specify output file path')
607
    parser.add_argument('--existing-file', action='store', default=None,
608
                        help='Specify an existing file to operate on')
609
    args = parser.parse_args()
610
611
    setup_logging()
612
613
    # Ensure that not all options have been excluded
614
    abort = True
615
    for arg_name in ARG_NAMES:
616
        abort &= getattr(args, arg_name, False)
617
618
    if abort:
619
        print('Generated tarball would be empty. Aborting.')
620
        sys.exit(2)
621
622
    # Get setting overrides from yaml file if specified
623
    if args.config:
624
        try:
625
            with open(args.config, 'r') as yaml_file:
626
                config_file = yaml.safe_load(yaml_file)
627
        except Exception as e:
628
            LOG.error('Failed to parse config file: %s' % e)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
629
            sys.exit(1)
630
631
        if not isinstance(config_file, dict):
632
            LOG.error('Unrecognized config file format')
633
            sys.exit(1)
634
    else:
635
        config_file = {}
636
637
    company_name = config_file.get('company_name', COMPANY_NAME)
638
639
    # Defaults
640
    encrypt = True
641
    upload = True
642
643
    if args.review:
644
        encrypt = False
645
        upload = False
646
647
    if encrypt:
648
        # When not running in review mode, GPG needs to be installed and
649
        # available
650
        if not GPG_INSTALLED:
651
            msg = ('"gpg" binary not found, can\'t proceed. Make sure "gpg" is installed '
652
                   'and available in PATH.')
653
            raise ValueError(msg)
654
655
    if not args.yes and not args.existing_file and upload:
656
        submitted_content = [name.replace('exclude_', '') for name in ARG_NAMES if
657
                             not getattr(args, name, False)]
658
        submitted_content = ', '.join(submitted_content)
659
        print('This will submit the following information to %s: %s' % (company_name,
660
                                                                        submitted_content))
661
        value = six.moves.input('Are you sure you want to proceed? [y/n] ')
662
        if value.strip().lower() not in ['y', 'yes']:
663
            print('Aborting')
664
            sys.exit(1)
665
666
    # Prompt user for optional additional context info
667
    user_info = {}
668
    if not args.yes and not args.existing_file:
669
        print('If you want us to get back to you via email, you can provide additional context '
670
              'such as your name, email and an optional comment')
671
        value = six.moves.input('Would you like to provide additional context? [y/n] ')
672
        if value.strip().lower() in ['y', 'yes']:
673
            user_info['name'] = six.moves.input('Name: ')
674
            user_info['email'] = six.moves.input('Email: ')
675
            user_info['comment'] = six.moves.input('Comment: ')
676
677
    debug_collector = DebugInfoCollector(include_logs=not args.exclude_logs,
678
                                         include_configs=not args.exclude_configs,
679
                                         include_content=not args.exclude_content,
680
                                         include_system_info=not args.exclude_system_info,
681
                                         include_shell_commands=not args.exclude_shell_commands,
682
                                         user_info=user_info,
683
                                         debug=args.debug,
684
                                         config_file=config_file,
685
                                         output_path=args.output)
686
687
    debug_collector.run(encrypt=encrypt, upload=upload, existing_file=args.existing_file)
688