def setup_method(self, method):
        imp.reload(configreader)
        imp.reload(test.config.app)

        context.setup(
            app='test',
            app_config=test.config.app.TestingConfig()
        )
        context.setup_thread_id()

        context.default_log.info(
            '%s %s::%s %s' % ('=' * 20, self.__class__.__name__, self._testMethodName, '=' * 20)
        )

        # modify http client to store http requests
        from amplify.agent.util.http import HTTPClient
        self.http_requests = []

        original_get = HTTPClient.get
        original_post = HTTPClient.post

        def fake_get(obj, url, *args, **kwargs):
            self.http_requests.append(url)
            return original_get(obj, url, *args, **kwargs)

        def fake_post(obj, url, *args, **kwargs):
            self.http_requests.append(url)
            return original_post(obj, url, *args, **kwargs)

        HTTPClient.get = fake_get
        HTTPClient.post = fake_post
    def setup_method(self, method):
        imp.reload(configreader)
        imp.reload(test.config.app)

        context.setup(
            app='test',
            app_config=test.config.app.TestingConfig()
        )
        context.setup_thread_id()

        context.default_log.info(
            '%s %s::%s %s' % ('=' * 20, self.__class__.__name__, self._testMethodName, '=' * 20)
        )
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
from optparse import OptionParser, Option

sys.path.append(os.getcwd())  # to make amplify libs available

from amplify.agent.context import context
context.setup(
    app='agent',
    config_file='etc/agent.conf.development',
)

from amplify.agent.nginx.config.config import NginxConfig


__author__ = "Mike Belov"
__copyright__ = "Copyright (C) Nginx, Inc. All rights reserved."
__credits__ = ["Mike Belov", "Andrei Belov", "Ivan Poluyanov", "Oleg Mamontov", "Andrew Alexeev", "Grant Hulegaard"]
__license__ = ""
__maintainer__ = "Mike Belov"
__email__ = "*****@*****.**"

usage = "usage: sudo -u nginx %prog -h"

option_list = (
    Option(
        '-c', '--config',
        action='store',
def test(config_file, pid_file):
    print('')

    try:
        # check that config file exists
        if not os.path.isfile(config_file) or not os.access(config_file, os.R_OK):
            print("\033[31mConfig file %s could not be found or opened.\033[0m\n" % config_file)
            print("If you installed the agent from the package you should do the following actions:")
            print("  1. sudo cp /etc/amplify-agent/agent.conf.default /etc/amplify-agent/agent.conf")
            print("  2. sudo chown nginx /etc/amplify-agent/agent.conf")
            print("  3. write your API key in [credentials][api_key]")
            return 1

        # check it can be loaded
        from amplify.agent.context import context
        context.setup(
            app='agent',
            config_file=config_file,
            pid_file=pid_file
        )

        # check that it contain needed stuff
        if not context.app_config['cloud']['api_url']:
            print("\033[31mAPI url is not specified in %s\033[0m\n" % config_file)
            print("Write API url https://receiver.amplify.nginx.com:443/1.0 in [cloud][api_url]")
            return 1

        if not context.app_config['credentials']['api_key']:
            print("\033[31mAPI key is not specified in %s\033[0m\n" % config_file)
            print("Write your API key in [credentials][api_key]")
            return 1

        # test logger
        try:
            context.log.info('configtest check')
        except:
            print("\033[31mCould not write to log\033[0m\n")
            print("Maybe the log folder doestn't exist or rights are broken")
            print("You should do the following actions:")
            print("  1. sudo mkdir /var/log/amplify-agent")
            print("  2. sudo touch /var/log/amplify-agent/agent.log")
            print("  3. sudo chown nginx /var/log/amplify-agent/agent.log")
            return 1

        # try to connect to the cloud
        try:
            context.http_client.post('agent/', {})
        except requests.HTTPError as e:
            api_url = context.app_config['cloud']['api_url']
            print("\033[31mCould not connect to cloud via url %s\033[0m" % api_url)

            if e.response.status_code == 404:
                api_key = context.app_config['credentials']['api_key']
                print("\033[31mIt seems like your API key '%s' is wrong. \033[0m\n" % api_key)
            else:
                print("\033[31mIt seems like we have little problems at our side. \nApologies and bear with us\033[0m\n")

            return 1
    except:
        print("\033[31mSomething failed:\033[0m\n")
        print(traceback.format_exc())
        return 1

    print("\033[32mConfig file %s is OK\033[0m" % config_file)
    return 0
        print("Invalid action or no action supplied\n")
        parser.print_help()
        sys.exit(1)

    # check config before start
    if action in ('configtest', 'start'):
        rc = test_config(options.config, options.pid)
        print("")
        if action == 'configtest' or rc:
            sys.exit(rc)

    try:
        from amplify.agent.context import context
        context.setup(
            app='agent',
            config_file=options.config,
            pid_file=options.pid
        )
    except:
        import traceback
        print(traceback.format_exc(sys.exc_traceback))

    try:
        from amplify.agent.supervisor import Supervisor
        supervisor = Supervisor(foreground=options.foreground)

        if not options.foreground:
            from amplify.agent.runner import Runner
            daemon_runner = Runner(supervisor)
            daemon_runner.do_action()
        else: