Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ in development
* Allow user to pass a boolean value for the ``cacert`` st2client constructor argument. This way
it now mimics the behavior of the ``verify`` argument of the ``requests.request`` method.
(improvement)
* Add datastore access to Python actions. (new-feature) #2396 [Kale Blankenship]

1.3.0 - January 22, 2016
------------------------
Expand Down
38 changes: 36 additions & 2 deletions st2actions/st2actions/runners/python_action_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
import sys
import json
import argparse
import logging as stdlib_logging
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why you went with stdlib logging instead of st2common logging that's already used everywhere else.

You just need to import like so "from st2common import log as logging" in DatastoreService. Also, passing in a logger seems not needed at that point. Am I missing something?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more to do with usage in _set_up_logger as logging from st2common is still used in this module.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I forgot I had done that. It's from a quick attempt at getting this to log in the same file as the action, _set_up_logger is a copy and paste from the Action class. I didn't intend to submit with that code. (This is also the answer to @manasdk's question about _set_up_logger.)

Do you have a suggestion on how to accomplish the same goal? Assuming logging into the same files is desired.

As to why it's being passed in, in SensorService it was using the logger from the instance of SensorWrapper that gets passed in. I wanted to avoid changing SensorService's behavior.


from st2common import log as logging
from st2actions import config
from st2actions.runners.pythonrunner import Action
from st2common.util import loader as action_loader
from st2common.util.config_parser import ContentPackConfigParser
from st2common.constants.action import ACTION_OUTPUT_RESULT_DELIMITER
from st2common.service_setup import db_setup
from st2common.services.datastore import DatastoreService

__all__ = [
'PythonActionWrapper'
Expand All @@ -46,10 +49,14 @@ def __init__(self, pack, file_path, parameters=None, parent_args=None):
:param parent_args: Command line arguments passed to the parent process.
:type parse_args: ``list``
"""
db_setup()

self._pack = pack
self._file_path = file_path
self._parameters = parameters or {}
self._parent_args = parent_args or []
self._class_name = None
self._logger = logging.getLogger('PythonActionWrapper')

try:
config.parse_args(args=self._parent_args)
Expand Down Expand Up @@ -85,10 +92,37 @@ def _get_action_instance(self):
LOG.info('Using config "%s" for action "%s"' % (config.file_path,
self._file_path))

return action_cls(config=config.config)
action_instance = action_cls(config=config.config)
else:
LOG.info('No config found for action "%s"' % (self._file_path))
return action_cls(config={})
action_instance = action_cls(config={})

# Setup action_instance proeprties
action_instance.logger = self._set_up_logger(action_cls.__name__)
action_instance.datastore = DatastoreService(logger=action_instance.logger,
pack_name=self._pack,
class_name=action_cls.__name__,
api_username="action_service")

return action_instance

def _set_up_logger(self, action_name):
"""
Set up a logger which logs all the messages with level DEBUG
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain why this is needed and how this will be used?

and above to stderr.
"""
logger_name = 'actions.python.%s' % (action_name)
logger = logging.getLogger(logger_name)

console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)

formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)

return logger


if __name__ == '__main__':
Expand Down
26 changes: 3 additions & 23 deletions st2actions/st2actions/runners/pythonrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@
import abc
import json
import uuid
import logging as stdlib_logging

import six
from eventlet.green import subprocess

from st2actions.runners import ActionRunner
from st2common.util.green.shell import run_command
from st2common import log as logging
from st2common.constants.action import ACTION_OUTPUT_RESULT_DELIMITER
from st2common.constants.action import LIVEACTION_STATUS_SUCCEEDED
from st2common.constants.action import LIVEACTION_STATUS_FAILED
Expand All @@ -44,8 +42,6 @@
'Action'
]

LOG = logging.getLogger(__name__)

# constants to lookup in runner_parameters.
RUNNER_ENV = 'env'
RUNNER_TIMEOUT = 'timeout'
Expand Down Expand Up @@ -73,30 +69,14 @@ def __init__(self, config=None):
:type config: ``dict``
"""
self.config = config or {}
self.logger = self._set_up_logger()
# logger and datastore are assigned in PythonActionWrapper._get_action_instance
self.logger = None
self.datastore = None

@abc.abstractmethod
def run(self, **kwargs):
pass

def _set_up_logger(self):
"""
Set up a logger which logs all the messages with level DEBUG
and above to stderr.
"""
logger_name = 'actions.python.%s' % (self.__class__.__name__)
logger = logging.getLogger(logger_name)

console = stdlib_logging.StreamHandler()
console.setLevel(stdlib_logging.DEBUG)

formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(stdlib_logging.DEBUG)

return logger


class PythonRunner(ActionRunner):

Expand Down
219 changes: 219 additions & 0 deletions st2common/st2common/services/datastore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from st2client.client import Client
from st2client.models import KeyValuePair
from st2common.services.access import create_token
from st2common.util.api import get_full_public_api_url


class DatastoreService(object):
"""
Class provides public methods for accessing datastore items.
"""

DATASTORE_NAME_SEPARATOR = ':'

def __init__(self, logger, pack_name, class_name, api_username):
self._api_username = api_username
self._pack_name = pack_name
self._class_name = class_name
self._logger = logger

self._client = None

##################################
# Methods for datastore management
##################################

def list_values(self, local=True, prefix=None):
"""
Retrieve all the datastores items.

:param local: List values from a namespace local to this pack/class. Defaults to True.
:type: local: ``bool``

:param prefix: Optional key name prefix / startswith filter.
:type prefix: ``str``

:rtype: ``list`` of :class:`KeyValuePair`
"""
client = self._get_api_client()
self._logger.audit('Retrieving all the value from the datastore')

key_prefix = self._get_full_key_prefix(local=local, prefix=prefix)
kvps = client.keys.get_all(prefix=key_prefix)
return kvps

def get_value(self, name, local=True):
"""
Retrieve a value from the datastore for the provided key.

By default, value is retrieved from the namespace local to the pack/class. If you want to
retrieve a global value from a datastore, pass local=False to this method.

:param name: Key name.
:type name: ``str``

:param local: Retrieve value from a namespace local to the pack/class. Defaults to True.
:type: local: ``bool``

:rtype: ``str`` or ``None``
"""
name = self._get_full_key_name(name=name, local=local)

client = self._get_api_client()
self._logger.audit('Retrieving value from the datastore (name=%s)', name)

try:
kvp = client.keys.get_by_id(id=name)
except Exception:
return None

if kvp:
return kvp.value

return None

def set_value(self, name, value, ttl=None, local=True):
"""
Set a value for the provided key.

By default, value is set in a namespace local to the pack/class. If you want to
set a global value, pass local=False to this method.

:param name: Key name.
:type name: ``str``

:param value: Key value.
:type value: ``str``

:param ttl: Optional TTL (in seconds).
:type ttl: ``int``

:param local: Set value in a namespace local to the pack/class. Defaults to True.
:type: local: ``bool``

:return: ``True`` on success, ``False`` otherwise.
:rtype: ``bool``
"""
name = self._get_full_key_name(name=name, local=local)

value = str(value)
client = self._get_api_client()

self._logger.audit('Setting value in the datastore (name=%s)', name)

instance = KeyValuePair()
instance.id = name
instance.name = name
instance.value = value

if ttl:
instance.ttl = ttl

client.keys.update(instance=instance)
return True

def delete_value(self, name, local=True):
"""
Delete the provided key.

By default, value is deleted from a namespace local to the pack/class. If you want to
delete a global value, pass local=False to this method.

:param name: Name of the key to delete.
:type name: ``str``

:param local: Delete a value in a namespace local to the pack/class. Defaults to True.
:type: local: ``bool``

:return: ``True`` on success, ``False`` otherwise.
:rtype: ``bool``
"""
name = self._get_full_key_name(name=name, local=local)

client = self._get_api_client()

instance = KeyValuePair()
instance.id = name
instance.name = name

self._logger.audit('Deleting value from the datastore (name=%s)', name)

try:
client.keys.delete(instance=instance)
except Exception:
return False

return True

def _get_api_client(self):
"""
Retrieve API client instance.
"""
if not self._client:
ttl = (24 * 60 * 60)
temporary_token = create_token(username=self._api_username, ttl=ttl)
api_url = get_full_public_api_url()
self._client = Client(api_url=api_url, token=temporary_token.token)

return self._client

def _get_full_key_name(self, name, local):
"""
Retrieve a full key name.

:rtype: ``str``
"""
if local:
name = self._get_key_name_with_prefix(name=name)

return name

def _get_full_key_prefix(self, local, prefix=None):
if local:
key_prefix = self._get_local_key_name_prefix()

if prefix:
key_prefix += prefix
else:
key_prefix = prefix

return key_prefix

def _get_local_key_name_prefix(self):
"""
Retrieve key prefix which is local to this pack/class.
"""
key_prefix = self._get_datastore_key_prefix() + self.DATASTORE_NAME_SEPARATOR
return key_prefix

def _get_key_name_with_prefix(self, name):
"""
Retrieve a full key name which is local to the current pack/class.

:param name: Base datastore key name.
:type name: ``str``

:rtype: ``str``
"""
prefix = self._get_datastore_key_prefix()
full_name = prefix + self.DATASTORE_NAME_SEPARATOR + name
return full_name

def _get_datastore_key_prefix(self):
prefix = '%s.%s' % (self._pack_name, self._class_name)
return prefix
Loading