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.
Passed
Push — develop-v1.3.1 ( 8fa207...a1cf9b )
by
unknown
06:11
created

DebugInfoCollector.create_archive()   F

Complexity

Conditions 9

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 9
dl 0
loc 43
rs 3
c 4
b 0
f 0
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
            remove_dir(self._temp_dir_path)
276
277
    def encrypt_archive(self, archive_file_path):
278
        """
279
        Encrypt archive with debugging information using our public key.
280
281
        :param archive_file_path: Path to the non-encrypted tarball file.
282
        :type archive_file_path: ``str``
283
284
        :return: Path to the encrypted archive.
285
        :rtype: ``str``
286
        """
287
        try:
288
            assert archive_file_path.endswith('.tar.gz')
289
290
            LOG.info('Encrypting tarball...')
291
            gpg = gnupg.GPG(verbose=self.debug)
292
293
            # Import our public key
294
            import_result = gpg.import_keys(self.gpg_key)
295
            # pylint: disable=no-member
296
            assert import_result.count == 1
297
298
            encrypted_archive_output_file_name = os.path.basename(archive_file_path) + '.asc'
299
            encrypted_archive_output_file_path = os.path.join('/tmp',
300
                                                              encrypted_archive_output_file_name)
301
            with open(archive_file_path, 'rb') as fp:
302
                gpg.encrypt_file(file=fp,
303
                                 recipients=self.gpg_key_fingerprint,
304
                                 always_trust=True,
305
                                 output=encrypted_archive_output_file_path)
306
            return encrypted_archive_output_file_path
307
        except Exception as e:
308
            LOG.exception('Failed to encrypt archive', exc_info=True)
309
            raise e
310
311
    def upload_archive(self, archive_file_path):
312
        """
313
        Upload the encrypted archive.
314
315
        :param archive_file_path: Path to the encrypted tarball file.
316
        :type archive_file_path: ``str``
317
        """
318
        try:
319
            assert archive_file_path.endswith('.asc')
320
321
            LOG.debug('Uploading tarball...')
322
            file_name = os.path.basename(archive_file_path)
323
            url = self.s3_bucket_url + file_name
324
            assert url.startswith('https://')
325
326
            with open(archive_file_path, 'rb') as fp:
327
                response = requests.put(url=url, files={'file': fp})
328
            assert response.status_code == httplib.OK
329
        except Exception as e:
330
            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...
331
            raise e
332
333
    def collect_logs(self, output_path):
334
        """
335
        Copy log files to the output path.
336
337
        :param output_path: Path where log files will be copied to.
338
        :type output_path: ``str``
339
        """
340
        LOG.debug('Including log files')
341
        for file_path_glob in self.log_file_paths:
342
            log_file_list = get_full_file_list(file_path_glob=file_path_glob)
343
            copy_files(file_paths=log_file_list, destination=output_path)
344
345
    def collect_config_files(self, output_path):
346
        """
347
        Copy config files to the output path.
348
349
        :param output_path: Path where config files will be copied to.
350
        :type output_path: ``str``
351
        """
352
        LOG.debug('Including config files')
353
        copy_files(file_paths=self.config_file_paths, destination=output_path)
354
355
        st2_config_path = os.path.join(output_path, self.st2_config_file_name)
356
        process_st2_config(config_path=st2_config_path)
357
358
        mistral_config_path = os.path.join(output_path, self.mistral_config_file_name)
359
        process_mistral_config(config_path=mistral_config_path)
360
361
    @staticmethod
362
    def collect_pack_content(output_path):
363
        """
364
        Copy pack contents to the output path.
365
366
        :param output_path: Path where pack contents will be copied to.
367
        :type output_path: ``str``
368
        """
369
        LOG.debug('Including content')
370
371
        packs_base_paths = get_packs_base_paths()
372
        for index, packs_base_path in enumerate(packs_base_paths, 1):
373
            dst = os.path.join(output_path, 'dir-%s' % index)
374
375
            try:
376
                shutil.copytree(src=packs_base_path, dst=dst)
377
            except IOError:
378
                continue
379
380
        base_pack_dirs = get_dirs_in_path(file_path=output_path)
381
382
        for base_pack_dir in base_pack_dirs:
383
            pack_dirs = get_dirs_in_path(file_path=base_pack_dir)
384
385
            for pack_dir in pack_dirs:
386
                process_content_pack_dir(pack_dir=pack_dir)
387
388
    def add_system_information(self, output_path):
389
        """
390
        Collect and write system information to output path.
391
392
        :param output_path: Path where system information will be written to.
393
        :type output_path: ``str``
394
        """
395
        LOG.debug('Including system info')
396
397
        system_information = yaml.dump(self.get_system_information(),
398
                                       default_flow_style=False)
399
400
        with open(output_path, 'w') as fp:
401
            fp.write(system_information)
402
403
    def add_user_info(self, output_path):
404
        """
405
        Write user info to output path as YAML.
406
407
        :param output_path: Path where user info will be written.
408
        :type output_path: ``str``
409
        """
410
        LOG.debug('Including user info')
411
        user_info = yaml.dump(self.user_info, default_flow_style=False)
412
413
        with open(output_path, 'w') as fp:
414
            fp.write(user_info)
415
416
    def add_shell_command_output(self, output_path):
417
        """"
418
        Get output of the required shell command and redirect the output to output path.
419
420
        :param output_path: Directory where output files will be written
421
        :param output_path: ``str``
422
        """
423
        LOG.debug('Including the required shell commands output files')
424
        for cmd in self.shell_commands:
425
            output_file = os.path.join(output_path, '%s.txt' % self.format_output_filename(cmd))
426
            exit_code, stdout, stderr = run_command(cmd=cmd, shell=True)
427
            with open(output_file, 'w') as fp:
428
                fp.write('[BEGIN STDOUT]\n')
429
                fp.write(stdout)
430
                fp.write('[END STDOUT]\n')
431
                fp.write('[BEGIN STDERR]\n')
432
                fp.write(stderr)
433
                fp.write('[END STDERR]')
434
435
    def create_tarball(self, temp_dir_path):
436
        """
437
        Create tarball with the contents of temp_dir_path.
438
439
        Tarball will be written to self.output_path, if set. Otherwise it will
440
        be written to /tmp a name generated according to OUTPUT_FILENAME_TEMPLATE.
441
442
        :param temp_dir_path: Base directory to include in tarbal.
443
        :type temp_dir_path: ``str``
444
445
        :return: Path to the created tarball.
446
        :rtype: ``str``
447
        """
448
        LOG.info('Creating tarball...')
449
        if self.output_path:
450
            output_file_path = self.output_path
451
        else:
452
            date = date_utils.get_datetime_utc_now().strftime(DATE_FORMAT)
453
            values = {'hostname': socket.gethostname(), 'date': date}
454
455
            output_file_name = OUTPUT_FILENAME_TEMPLATE % values
456
            output_file_path = os.path.join('/tmp', output_file_name)
457
458
        with tarfile.open(output_file_path, 'w:gz') as tar:
459
            tar.add(temp_dir_path, arcname='')
460
461
        return output_file_path
462
463
    @staticmethod
464
    def create_temp_directories():
465
        """
466
        Creates a new temp directory and creates the directory structure as defined
467
        by DIRECTORY_STRUCTURE.
468
469
        :return: Path to temp directory.
470
        :rtype: ``str``
471
        """
472
        temp_dir_path = tempfile.mkdtemp()
473
474
        for directory_name in DIRECTORY_STRUCTURE:
475
            full_path = os.path.join(temp_dir_path, directory_name)
476
            os.mkdir(full_path)
477
478
        return temp_dir_path
479
480
    @staticmethod
481
    def format_output_filename(cmd):
482
        """"
483
        Remove whitespace and special characters from a shell command.
484
485
        Used to create filename-safe representations of a shell command.
486
487
        :param cmd: Shell command.
488
        :type cmd: ``str``
489
        :return: Formatted filename.
490
        :rtype: ``str``
491
        """
492
        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...
493
494
    @staticmethod
495
    def get_system_information():
496
        """
497
        Retrieve system information which is included in the report.
498
499
        :rtype: ``dict``
500
        """
501
        system_information = {
502
            'hostname': socket.gethostname(),
503
            'operating_system': {},
504
            'hardware': {
505
                'cpu': {},
506
                'memory': {}
507
            },
508
            'python': {},
509
            'stackstorm': {},
510
            'mistral': {}
511
        }
512
513
        # Operating system information
514
        system_information['operating_system']['system'] = platform.system()
515
        system_information['operating_system']['release'] = platform.release()
516
        system_information['operating_system']['operating_system'] = platform.platform()
517
        system_information['operating_system']['platform'] = platform.system()
518
        system_information['operating_system']['architecture'] = ' '.join(platform.architecture())
519
520
        if platform.system().lower() == 'linux':
521
            distribution = ' '.join(platform.linux_distribution())
522
            system_information['operating_system']['distribution'] = distribution
523
524
        system_information['python']['version'] = sys.version.split('\n')[0]
525
526
        # Hardware information
527
        cpu_info = get_cpu_info()
528
529
        if cpu_info:
530
            core_count = len(cpu_info)
531
            model = cpu_info[0]['model_name']
532
            system_information['hardware']['cpu'] = {
533
                'core_count': core_count,
534
                'model_name': model
535
            }
536
        else:
537
            # Unsupported platform
538
            system_information['hardware']['cpu'] = 'unsupported platform'
539
540
        memory_info = get_memory_info()
541
542
        if memory_info:
543
            total = memory_info['MemTotal'] / 1024
544
            free = memory_info['MemFree'] / 1024
545
            used = (total - free)
546
            system_information['hardware']['memory'] = {
547
                'total': total,
548
                'used': used,
549
                'free': free
550
            }
551
        else:
552
            # Unsupported platform
553
            system_information['hardware']['memory'] = 'unsupported platform'
554
555
        # StackStorm information
556
        system_information['stackstorm']['version'] = st2_version
557
558
        st2common_path = st2common.__file__
559
        st2common_path = os.path.dirname(st2common_path)
560
561
        if 'st2common/st2common' in st2common_path:
562
            # Assume we are running source install
563
            base_install_path = st2common_path.replace('/st2common/st2common', '')
564
565
            revision_hash = get_repo_latest_revision_hash(repo_path=base_install_path)
566
567
            system_information['stackstorm']['installation_method'] = 'source'
568
            system_information['stackstorm']['revision_hash'] = revision_hash
569
        else:
570
            package_list = get_package_list(name_startswith='st2')
571
572
            system_information['stackstorm']['installation_method'] = 'package'
573
            system_information['stackstorm']['packages'] = package_list
574
575
        # Mistral information
576
        repo_path = '/opt/openstack/mistral'
577
        revision_hash = get_repo_latest_revision_hash(repo_path=repo_path)
578
        system_information['mistral']['installation_method'] = 'source'
579
        system_information['mistral']['revision_hash'] = revision_hash
580
581
        return system_information
582
583
584
def main():
585
    parser = argparse.ArgumentParser(description='')
586
    parser.add_argument('--exclude-logs', action='store_true', default=False,
587
                        help='Don\'t include logs in the generated tarball')
588
    parser.add_argument('--exclude-configs', action='store_true', default=False,
589
                        help='Don\'t include configs in the generated tarball')
590
    parser.add_argument('--exclude-content', action='store_true', default=False,
591
                        help='Don\'t include content packs in the generated tarball')
592
    parser.add_argument('--exclude-system-info', action='store_true', default=False,
593
                        help='Don\'t include system information in the generated tarball')
594
    parser.add_argument('--exclude-shell-commands', action='store_true', default=False,
595
                        help='Don\'t include shell commands output in the generated tarball')
596
    parser.add_argument('--yes', action='store_true', default=False,
597
                        help='Run in non-interactive mode and answer "yes" to all the questions')
598
    parser.add_argument('--review', action='store_true', default=False,
599
                        help='Generate the tarball, but don\'t encrypt and upload it')
600
    parser.add_argument('--debug', action='store_true', default=False,
601
                        help='Enable debug mode')
602
    parser.add_argument('--config', action='store', default=None,
603
                        help='Get required configurations from config file')
604
    parser.add_argument('--output', action='store', default=None,
605
                        help='Specify output file path')
606
    parser.add_argument('--existing-file', action='store', default=None,
607
                        help='Specify an existing file to operate on')
608
    args = parser.parse_args()
609
610
    setup_logging()
611
612
    # Ensure that not all options have been excluded
613
    abort = True
614
    for arg_name in ARG_NAMES:
615
        abort &= getattr(args, arg_name, False)
616
617
    if abort:
618
        print('Generated tarball would be empty. Aborting.')
619
        sys.exit(2)
620
621
    # Get setting overrides from yaml file if specified
622
    if args.config:
623
        try:
624
            with open(args.config, 'r') as yaml_file:
625
                config_file = yaml.safe_load(yaml_file)
626
        except Exception as e:
627
            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...
628
            sys.exit(1)
629
630
        if not isinstance(config_file, dict):
631
            LOG.error('Unrecognized config file format')
632
            sys.exit(1)
633
    else:
634
        config_file = {}
635
636
    company_name = config_file.get('company_name', COMPANY_NAME)
637
638
    # Defaults
639
    encrypt = True
640
    upload = True
641
642
    if args.review:
643
        encrypt = False
644
        upload = False
645
646
    if encrypt:
647
        # When not running in review mode, GPG needs to be installed and
648
        # available
649
        if not GPG_INSTALLED:
650
            msg = ('"gpg" binary not found, can\'t proceed. Make sure "gpg" is installed '
651
                   'and available in PATH.')
652
            raise ValueError(msg)
653
654
    if not args.yes and not args.existing_file and upload:
655
        submitted_content = [name.replace('exclude_', '') for name in ARG_NAMES if
656
                             not getattr(args, name, False)]
657
        submitted_content = ', '.join(submitted_content)
658
        print('This will submit the following information to %s: %s' % (company_name,
659
                                                                        submitted_content))
660
        value = six.moves.input('Are you sure you want to proceed? [y/n] ')
661
        if value.strip().lower() not in ['y', 'yes']:
662
            print('Aborting')
663
            sys.exit(1)
664
665
    # Prompt user for optional additional context info
666
    user_info = {}
667
    if not args.yes and not args.existing_file:
668
        print('If you want us to get back to you via email, you can provide additional context '
669
              'such as your name, email and an optional comment')
670
        value = six.moves.input('Would you like to provide additional context? [y/n] ')
671
        if value.strip().lower() in ['y', 'yes']:
672
            user_info['name'] = six.moves.input('Name: ')
673
            user_info['email'] = six.moves.input('Email: ')
674
            user_info['comment'] = six.moves.input('Comment: ')
675
676
    debug_collector = DebugInfoCollector(include_logs=not args.exclude_logs,
677
                                         include_configs=not args.exclude_configs,
678
                                         include_content=not args.exclude_content,
679
                                         include_system_info=not args.exclude_system_info,
680
                                         include_shell_commands=not args.exclude_shell_commands,
681
                                         user_info=user_info,
682
                                         debug=args.debug,
683
                                         config_file=config_file,
684
                                         output_path=args.output)
685
686
    debug_collector.run(encrypt=encrypt, upload=upload, existing_file=args.existing_file)
687