"""The main module of the Analytics API Load Tests tool.

Copyright (c) 2019 Red Hat Inc.

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 3 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, see <http://www.gnu.org/licenses/>.
"""

import sys
import os
from time import time
from fastlog import log
from csv_reader import read_csv_as_dicts
from setup import setup
from cliargs import cli_parser

from component_analysis import ComponentAnalysis
from stack_analysis import StackAnalysis
from test_runner import start_tests


# current version of this tool
VERSION_MAJOR = 1
VERSION_MINOR = 0


def check_api_endpoint(api):
    """Check that some API endpoint is callable."""
    log.info("Checking: core API endpoint")
    with log.indent():
        if not api.is_api_running():
            log.error("Fatal: tested system is not available")
            sys.exit(1)
        else:
            log.success("ok")


def check_auth_token(api):
    """Check the authorization token for the core API."""
    log.info("Checking: authorization token for the core API")
    with log.indent():
        if api.check_auth_token_validity():
            log.success("ok")
        else:
            log.error("Fatal: wrong token(?)")
            sys.exit(1)


def check_system(api):
    """Check if all system endpoints are available and that tokens are valid."""
    # try to access system endpoints
    log.info("System check")
    with log.indent():
        check_api_endpoint(api)
        check_auth_token(api)


def show_version():
    """Show A2T version."""
    print("A2T version {major}.{minor}".format(major=VERSION_MAJOR, minor=VERSION_MINOR))


def main():
    """Entry point to the Analytics API Load Tests."""
    log.setLevel(log.INFO)
    cli_arguments = cli_parser.parse_args()
    if cli_arguments.version:
        show_version()
        sys.exit(0)
    else:
        cfg = setup(cli_arguments)

        coreapi_url = os.environ.get('F8A_SERVER_API_URL', None)
        component_analysis = ComponentAnalysis(coreapi_url,
                                               cfg["access_token"], cfg["user_key"], True)
        stack_analysis = StackAnalysis(coreapi_url,
                                       cfg["access_token"], cfg["user_key"], True)

        check_system(component_analysis)

        try:
            tests = read_csv_as_dicts(cfg["input_file"])
        except Exception as e:
            log.error("Test description can not be read")
            log.error(e)
            sys.exit(0)

        t1 = time()
        tags = cfg["tags"]
        start_tests(cfg, tests, tags, component_analysis, stack_analysis)
        t2 = time()
        log.info("Start time: {}".format(t1))
        log.info("End time:   {}".format(t2))
        log.info("Duration:   {}".format(t2 - t1))


if __name__ == "__main__":
    # execute only if run as a script
    main()

[((39, 4, 39, 43), 'fastlog.log.info', 'log.info', ({(39, 13, 39, 42): '"""Checking: core API endpoint"""'}, {}), "('Checking: core API endpoint')", False, 'from fastlog import log\n'), ((50, 4, 50, 62), 'fastlog.log.info', 'log.info', ({(50, 13, 50, 61): '"""Checking: authorization token for the core API"""'}, {}), "('Checking: authorization token for the core API')", False, 'from fastlog import log\n'), ((62, 4, 62, 28), 'fastlog.log.info', 'log.info', ({(62, 13, 62, 27): '"""System check"""'}, {}), "('System check')", False, 'from fastlog import log\n'), ((75, 4, 75, 26), 'fastlog.log.setLevel', 'log.setLevel', ({(75, 17, 75, 25): 'log.INFO'}, {}), '(log.INFO)', False, 'from fastlog import log\n'), ((76, 20, 76, 43), 'cliargs.cli_parser.parse_args', 'cli_parser.parse_args', ({}, {}), '()', False, 'from cliargs import cli_parser\n'), ((40, 9, 40, 21), 'fastlog.log.indent', 'log.indent', ({}, {}), '()', False, 'from fastlog import log\n'), ((51, 9, 51, 21), 'fastlog.log.indent', 'log.indent', ({}, {}), '()', False, 'from fastlog import log\n'), ((63, 9, 63, 21), 'fastlog.log.indent', 'log.indent', ({}, {}), '()', False, 'from fastlog import log\n'), ((79, 8, 79, 19), 'sys.exit', 'sys.exit', ({(79, 17, 79, 18): '(0)'}, {}), '(0)', False, 'import sys\n'), ((81, 14, 81, 34), 'setup.setup', 'setup', ({(81, 20, 81, 33): 'cli_arguments'}, {}), '(cli_arguments)', False, 'from setup import setup\n'), ((83, 22, 83, 64), 'os.environ.get', 'os.environ.get', ({(83, 37, 83, 57): '"""F8A_SERVER_API_URL"""', (83, 59, 83, 63): 'None'}, {}), "('F8A_SERVER_API_URL', None)", False, 'import os\n'), ((84, 29, 85, 90), 'component_analysis.ComponentAnalysis', 'ComponentAnalysis', ({(84, 47, 84, 58): 'coreapi_url', (85, 47, 85, 66): "cfg['access_token']", (85, 68, 85, 83): "cfg['user_key']", (85, 85, 85, 89): 'True'}, {}), "(coreapi_url, cfg['access_token'], cfg['user_key'], True)", False, 'from component_analysis import ComponentAnalysis\n'), ((86, 25, 87, 82), 'stack_analysis.StackAnalysis', 'StackAnalysis', ({(86, 39, 86, 50): 'coreapi_url', (87, 39, 87, 58): "cfg['access_token']", (87, 60, 87, 75): "cfg['user_key']", (87, 77, 87, 81): 'True'}, {}), "(coreapi_url, cfg['access_token'], cfg['user_key'], True)", False, 'from stack_analysis import StackAnalysis\n'), ((98, 13, 98, 19), 'time.time', 'time', ({}, {}), '()', False, 'from time import time\n'), ((100, 8, 100, 73), 'test_runner.start_tests', 'start_tests', ({(100, 20, 100, 23): 'cfg', (100, 25, 100, 30): 'tests', (100, 32, 100, 36): 'tags', (100, 38, 100, 56): 'component_analysis', (100, 58, 100, 72): 'stack_analysis'}, {}), '(cfg, tests, tags, component_analysis, stack_analysis)', False, 'from test_runner import start_tests\n'), ((101, 13, 101, 19), 'time.time', 'time', ({}, {}), '()', False, 'from time import time\n'), ((42, 12, 42, 62), 'fastlog.log.error', 'log.error', ({(42, 22, 42, 61): '"""Fatal: tested system is not available"""'}, {}), "('Fatal: tested system is not available')", False, 'from fastlog import log\n'), ((43, 12, 43, 23), 'sys.exit', 'sys.exit', ({(43, 21, 43, 22): '(1)'}, {}), '(1)', False, 'import sys\n'), ((45, 12, 45, 29), 'fastlog.log.success', 'log.success', ({(45, 24, 45, 28): '"""ok"""'}, {}), "('ok')", False, 'from fastlog import log\n'), ((53, 12, 53, 29), 'fastlog.log.success', 'log.success', ({(53, 24, 53, 28): '"""ok"""'}, {}), "('ok')", False, 'from fastlog import log\n'), ((55, 12, 55, 46), 'fastlog.log.error', 'log.error', ({(55, 22, 55, 45): '"""Fatal: wrong token(?)"""'}, {}), "('Fatal: wrong token(?)')", False, 'from fastlog import log\n'), ((56, 12, 56, 23), 'sys.exit', 'sys.exit', ({(56, 21, 56, 22): '(1)'}, {}), '(1)', False, 'import sys\n'), ((92, 20, 92, 56), 'csv_reader.read_csv_as_dicts', 'read_csv_as_dicts', ({(92, 38, 92, 55): "cfg['input_file']"}, {}), "(cfg['input_file'])", False, 'from csv_reader import read_csv_as_dicts\n'), ((94, 12, 94, 57), 'fastlog.log.error', 'log.error', ({(94, 22, 94, 56): '"""Test description can not be read"""'}, {}), "('Test description can not be read')", False, 'from fastlog import log\n'), ((95, 12, 95, 24), 'fastlog.log.error', 'log.error', ({(95, 22, 95, 23): 'e'}, {}), '(e)', False, 'from fastlog import log\n'), ((96, 12, 96, 23), 'sys.exit', 'sys.exit', ({(96, 21, 96, 22): '(0)'}, {}), '(0)', False, 'import sys\n')]