예제 #1
0
  def list_behaviors(self):
    AppLogging.info("behaviors")

    behaviors = self.behavior_repository.get_available_behaviors()
    body = json.dumps(behaviors)
    tron_response = TronResponse(body)
    return tron_response
 def create_database(cursor):
     try:
         cursor.execute(
             "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
     except mysql.connector.Error as err:
         AppLogging.error("Failed creating database: {}".format(err))
         exit(1)
예제 #3
0
 def validate_config(self):
     errors = self.validate_json()
     if errors is not None and len(errors) > 0:
         config_file_path = self.config_file
         AppLogging.error('****Configuration file ' + config_file_path +
                          ' is not valid*****')
         for error in errors:
             AppLogging.error('  ' + error)
         raise SystemExit
 def setUp(self):
     AppLogging.init('info')
     self.http_utils = mock.Mock()
     self.http_utils.get_demo_http_headers.return_value = {}
     self.app_config = mock.Mock()
     self.app_config.get_delay_start_ms.return_value = 0
     self.app_config.get_process_start_time.return_value = time.time()
     self.result = mock.Mock()
     self.createResponseFunc = (lambda x, y, z: self.result)
     self.message = MessageHandler(self.app_config, self.http_utils,
                                   repository.Repository(["SOMETHING"]),
                                   self.createResponseFunc)
예제 #5
0
def help_message():
    AppLogging.info("help")

    body = '''
        API Usage:
        - GET    /api/validateMessage\n
        - GET    /api/inventory\n
        - GET    /api/inventory/<id>\n
    '''
    tron_response = TronResponse(body)

    return tron_response
예제 #6
0
 def setUp(self):
     AppLogging.init('info')
     self.http_utils = mock.Mock()
     self.http_utils.query_service.return_value = "{}"
     self.http_utils.get_demo_http_headers.return_value = {}
     self.app_config = mock.Mock()
     self.app_config.get_delay_start_ms.return_value = 0
     self.app_config.get_process_start_time.return_value = time.time()
     self.result = mock.Mock()
     self.createResponseFunc = (lambda x,y,z: self.result)
     self.datastore = mock.Mock()
     self.all_inventory = [0,1,2,3,4,5,6,7,8,9]
     self.datastore.get_records.return_value = self.all_inventory
     self.inventory = InventoryHandler(self.app_config, self.datastore, self.http_utils, repository.Repository(["SOMETHING"]), self.createResponseFunc)
예제 #7
0
 def validate_json(self):
     config_file_path = self.config_file
     s = schema.get_schema()
     errors = None
     if config_file_path is not None:
         with open(config_file_path) as json_file:
             try:
                 instance = json.load(json_file)
             except:
                 return ['file is not a JSON file']
             v = Draft6Validator(s)
             validation_errors = sorted(v.iter_errors(instance), key=str)
             errors = self._parse_errors(validation_errors)
             return errors
     else:
         AppLogging.error('No configuration file defined')
         raise Exception('No configuration file defined')
예제 #8
0
    def get_inventory(self):
        BaseHandler(self.app_config).ensure_app_is_started()
        AppLogging.info("get_inventory")
        handle_behaviors_pre(self.behavior_repository, self.http_utils.get_demo_http_headers())

        data = self.datastore.get_records()
        tron_response = self.createResponseFunc(data, self.app_config, self.http_utils)

        urls = self.app_config.get_dependency_endpoint('/api/inventory')
        if urls is not None:
            for url in urls:
                if url is not None:
                    downstream_response = self.http_utils.query_service(url)
                    tron_response.append_trace(self.http_utils, downstream_response)

        handle_behaviors_post(self.behavior_repository, self.http_utils.get_demo_http_headers())

        return tron_response
예제 #9
0
def inventory_repository_selector(app_config=None):
    if app_config == None:
        from dependency_injection_container import Container
        app_config = Container().app_config()

    database_options = app_config.get_app_config_value('database')
    option_values = [
        database_options.get(i, '')
        for i in ['user', 'password', 'host', 'port', 'name']
    ]

    # false if there exists an option with no value, true if all options have values
    use_database = not ('' in option_values)

    selection = "database" if use_database else "file"

    AppLogging.info(f"Using inventory repository type: {selection}")

    return selection
예제 #10
0
    def validate(self):
        BaseHandler(self.app_config).ensure_app_is_started()
        AppLogging.info("validate_message")
        handle_behaviors_pre(self.behavior_repository,
                             self.http_utils.get_demo_http_headers())

        data = {"result": True}
        tron_response = self.createResponseFunc(data, self.app_config,
                                                self.http_utils)

        urls = self.app_config.get_dependency_endpoint('/api/validateMessage')
        if urls is not None:
            for url in urls:
                if url is not None:
                    downstream_response = self.http_utils.query_service(url)
                    tron_response.append_trace(self.http_utils,
                                               downstream_response)

        handle_behaviors_post(self.behavior_repository,
                              self.http_utils.get_demo_http_headers())

        return tron_response
예제 #11
0
    def connect(self, **kwargs):
        try:
            if self.__connection == None:
                # if options are provided, dont use default options
                connect_options = kwargs if len(
                    kwargs) > 0 else self.__connectin_info.asdict()

                self.__connection = mysql.connector.connect(**connect_options)

            return self.__connection
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                AppLogging.error(
                    "Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                AppLogging.error("Database does not exist")
            else:
                AppLogging.error(err)
예제 #12
0
def lambda_handler(event, context):
    AppLogging.init('info')

    app_config = AppConfig(
        config_file=os.environ['config_file']
    )

    config = app_config.asdict()

    database_connection_info_func = lambda: DatabaseConnectionInfo(
        user=config['database']['user'],
        password=config['database']['password'],
        host=config['database']['host'],
        port=config['database']['port'],
        database=config['database']['name']
    )

    database_connector = MySqlConnector(
        connection_info=database_connection_info_func()
    )

    database_inventory_repository = DatabaseInventoryRepository(
        database_connector=database_connector
    )

    file_inventory_repository = FileInventoryRepository()

    inventory_repositories = {
        'file': file_inventory_repository,
        'database': database_inventory_repository
    }
    inventory_repository = inventory_repositories[inventory_repository_selector(app_config)]

    http_utils = HttpUtils(
        func_get_headers=lambda: (event['headers'] or dict()).items()
    )

    def behavior_factory(name, value):
        if name == "throw":
            return ThrowException()
        elif name == "compute":
            return Compute(value)
        elif name == "malloc":
            return Malloc(value)
        elif name == "invalid_query":
            return InvalidQuery(database_inventory_repository)
        else:
            return None

    behavior_repository = Repository(
        app_id=app_config.get_app_id(),
        behavior_factory_func=behavior_factory
    )
    
    AppLogging.init('info')
    
    if(inventory_repository_selector(app_config) == 'database'):
        setup_database = SetupDatabaseAction(database_connector, database_connection_info_func(), get_inventory_data())
        setup_database.execute()

    endpoint = (event['resource'] or "").lower()
    if endpoint == "/":
        index = IndexHandler(app_config, behavior_repository)
        resp =  index.index_message()
    elif endpoint == "/validatemessage":
        message = MessageHandler(app_config, http_utils, behavior_repository)
        resp =  message.validate()
    elif endpoint == "/help":
        resp = help_message()
    elif endpoint == "/inventory":
        inventory = InventoryHandler(app_config, inventory_repository, http_utils, behavior_repository)
        resp = inventory.get_inventory()
    elif endpoint == "/inventory/{id+}":
        inventory = InventoryHandler(app_config, inventory_repository, http_utils, behavior_repository)
        item_id = event['pathParameters']['id']
        resp = inventory.get_inventory_item(item_id)
    else:
        body = "Unsupported endpoint: " + endpoint
        resp = TronResponse(body, dict(), 404)

    return get_lambda_reponse(resp)
예제 #13
0
def handle_exception(e):
    message = "{}".format(e)
    AppLogging.error(message)
    return message, 500
예제 #14
0
    )
    for k, v in tron_response.get_headers().items():
        response.headers[k] = v
    return response


if __name__ == "__main__":
    container = Container()
    app_config = container.app_config()

    container.config.from_dict(app_config.asdict())
    container.wire(modules=[sys.modules[__name__]])

    arguments = container.arguments()

    AppLogging.init(arguments.logging_level)

    if inventory_repository_selector(app_config) == 'database':
        container.setup_database_action().execute()

    database_connector = container.database_connector()
    http_utils = container.http_utils()
    inventory = container.inventory_handler()
    message = container.message_handler()
    behaviors = container.behaviors_handler()
    index = container.index_handler()

    debug_mode = arguments.debug_mode

    if debug_mode is not None and debug_mode == 'On':
        os.environ["FLASK_ENV"] = "development"
예제 #15
0
    def index_message(self):
        AppLogging.info("index")

        body = self.get_message()
        tron_response = TronResponse(body)
        return tron_response
예제 #16
0
 def setUp(self):
     AppLogging.init('info')
     self.app_config = mock.Mock()
     self.result = mock.Mock()
     self.behaviors = BehaviorsHandler(self.app_config,
                                       repository.Repository(["SOMETHING"]))
    def execute(self):
        DB_NAME = self.__database_connection_info.database
        # remove this since we dont know if database exists yet.
        self.__database_connection_info.database = None

        cnx = self.__database_connector.connect(**self.__database_connection_info.asdict())
        cursor = cnx.cursor()

        def create_database(cursor):
            try:
                cursor.execute(
                    "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
            except mysql.connector.Error as err:
                AppLogging.error("Failed creating database: {}".format(err))
                exit(1)

        try:
            cursor.execute("USE {}".format(DB_NAME))
            AppLogging.info("Database already exists")
        except mysql.connector.Error as err:
            AppLogging.info("Database {} does not exists.".format(DB_NAME))
            if err.errno == errorcode.ER_BAD_DB_ERROR:
                create_database(cursor)
                AppLogging.info("Database {} created successfully.".format(DB_NAME))
                cnx.database = DB_NAME

                TABLES = {}
                TABLES['inventory'] = (
                    "CREATE TABLE `inventory` ("
                    "  `id` int(11) NOT NULL AUTO_INCREMENT,"
                    "  `item` varchar(14) NOT NULL,"
                    "  `sku` varchar(80) NOT NULL,"
                    "  `price` varchar(14) NOT NULL,"
                    "  PRIMARY KEY (`id`)"
                    ") ENGINE=InnoDB")

                AppLogging.info("Creating inventory table . . .")

                for table_name in TABLES:
                    table_description = TABLES[table_name]
                    try:
                        AppLogging.info("Creating table {}: ".format(table_name))
                        cursor.execute(table_description)
                    except mysql.connector.Error as err:
                        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
                            AppLogging.error("table already exists.")
                        else:
                            AppLogging.error(err.msg)
                    else:
                        AppLogging.info("OK")

                AppLogging.info("Inserting inventory data . . .")

                add_inventory_item = ("INSERT INTO inventory "
                                    "(item, price, sku) "
                                    "VALUES (%(item)s, %(price)s, %(sku)s)")

                for item in self.__inventory_data:
                    cursor.execute(add_inventory_item, item)
                    cnx.commit()

                cursor.close()
                cnx.close()
            else:
                AppLogging.error(err)
                exit(1)