How to use the grok.app.webservices.AuthenticatedBaseHandler function in grok

To help you get started, we’ve selected a few grok examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github numenta / numenta-apps / grok / grok / app / webservices / custom_api.py View on Github external
from grok import grok_logging

LOGGER = grok_logging.getExtendedLogger(__name__)

urls = (
  # /_metrics/custom
  '', "CustomDefaultHandler",
  # /_metrics/custom/
  '/', "CustomDefaultHandler",
  # /_metrics/custom/
  '/([\w\.\-]+)', "CustomDefaultHandler",
)



class CustomDefaultHandler(AuthenticatedBaseHandler):


  def GET(self):
    with web.ctx.connFactory() as conn:
      metrics = repository.getCustomMetrics(conn, getMetricDisplayFields(conn))
    convertedMetrics = [convertMetricRowToMetricDict(metric)
                        for metric in metrics]
    self.addStandardHeaders()
    return json.dumps(convertedMetrics)


  def DELETE(self, metricName):
    adapter = createDatasourceAdapter("custom")
    try:
      adapter.deleteMetricByName(metricName)
    except app_exceptions.ObjectNotFoundError:
github numenta / numenta-apps / grok / grok / app / webservices / autostacks_api.py View on Github external
"region '%s'. Please enter a unique Autostack name." % (
                nativeMetric.get("name", "None"),
                nativeMetric.get("region", "None")))
      raise web.created(utils.jsonEncode(result))
    except (web.HTTPError, QuotaError) as ex:
      if bool(re.match(r"([45][0-9][0-9])\s?", web.ctx.status)):
        # Log 400-599 status codes as errors, ignoring 200-399
        log.error(str(ex) or repr(ex))
      raise
    except Exception as ex:
      log.exception("POST Failed")
      raise web.internalerror(str(ex) or repr(ex))



class AutostackInstancesHandler(AuthenticatedBaseHandler):

  @staticmethod
  def formatInstance(instance, keys=("instanceID", "state", "instanceType",
                                     "launchTime", "tags", "regionName")):
    """ Format InstanceInfo namedtuple to dict for API consumption

        :param instance: InstanceInfo object
        :type instance: grok.app.runtime.aggregator_instances.InstanceInfo
        :param keys: Keys to be included in resulting dict
        :type keys: tuple
        :return: Formatted InstanceInfo dict containing keys defined by keys
                 kwarg, and corresponding values from original InstanceInfo
                 object.  `lanchTime` is converted explicitly to ISO format.
        :rtype: dict
    """
    # convert to dict (for mutability)
github numenta / numenta-apps / grok / grok / app / webservices / anomalies_api.py View on Github external
def getModelRankByServer(model):
        return (-serverValues[model["server"]], model["server"], model["name"])
      modelsList = sorted(modelsList, key=getModelRankByServer)

      return utils.jsonEncode(modelsList)

    except (web.HTTPError) as ex:
      log.info(str(ex) or repr(ex))
      raise ex

    except Exception as ex:
      log.exception("GET Failed")
      raise web.internalerror(str(ex) or repr(ex))


class AnomaliesNameHandler(AuthenticatedBaseHandler):
  def GET(self):
    """
    Get metrics, sorted by AWS name tag / instance ID

    :returns: List of metrics
    :rtype: list

    Example request::

      GET /_anomalies/name

    Example response::

      [
        {
          "status": 1,
github numenta / numenta-apps / grok / grok / app / webservices / anomalies_api.py View on Github external
from grok import grok_logging

from collections import defaultdict


log = grok_logging.getExtendedLogger("webservices")


urls = (
  r"/period/(\d+)/*", "AnomaliesPeriodHandler",
  r"/name",           "AnomaliesNameHandler",
  "/*",               "DefaultHandler",
)


class DefaultHandler(AuthenticatedBaseHandler):
  def GET(self):
    """
    Get number of available periods

    Example request::

      GET /_anomalies

    Example response::

      [
        2,
        24,
        192
      ]
    """
github numenta / numenta-apps / grok / grok / app / webservices / settings_api.py View on Github external
def getAllSettings(self):
    # Make sure we have the latest version of configuration
    grok.app.config.loadConfig()

    apikey = AuthenticatedBaseHandler.extractAuthHeader()
    authResult = AuthenticatedBaseHandler.compareAuthorization(apikey)

    if authResult is False:
      AuthenticatedBaseHandler.raiseAuthFailure()

    res = {}
    for section in self.validSections():
      res[section] = {}
      for key, value in grok.app.config.items(section):
        if key not in HIDDEN_SETTINGS.get(section, set()):
          res[section][key] = value
    return res
github numenta / numenta-apps / grok / grok / app / webservices / update_api.py View on Github external
import grok.app

from htmengine import utils
from grok.app.webservices import AuthenticatedBaseHandler


urls = (
  '', "UpdateHandler"
)

FLAG_DIR = '/tmp/'
FLAG_FILE_AVAILABLE = FLAG_DIR + 'grok-update-available'
FLAG_FILE_START =     FLAG_DIR + 'grok-update-start'


class UpdateHandler(AuthenticatedBaseHandler):

  def isFlagFileAvailable(self):
    return os.path.isfile(FLAG_FILE_AVAILABLE)

  # is there an update available?
  def GET(self):
    web.header('Content-Type', 'application/json; charset=UTF-8', True)
    res = self.isFlagFileAvailable()
    return utils.jsonEncode({ 'result': res })

  # trigger the update to start
  def POST(self):
    web.header('Content-Type', 'application/json; charset=UTF-8', True)
    res = self.isFlagFileAvailable()
    if res:
      try:
github numenta / numenta-apps / grok / grok / app / webservices / cloudwatch_api.py View on Github external
specificResource["resID"]},
                   "identifier": specificResource["resID"],
                   "metric": metric,
                   "name": specificResource["name"],
                   "namespace": cloudwatchParams["namespace"],
                   "region": region}

    if region not in dict(adapter.describeRegions()):
      raise web.NotFound("Region '%s' was not found" % region)

    self.addStandardHeaders()
    return utils.jsonEncode(list(translateResourcesIntoMetrics()))



class CWNamespaceHandler(AuthenticatedBaseHandler):
  def GET(self, namespace=None):
    """
      List supported Cloudwatch namespaces

      ::

          GET /_metrics/cloudwatch/namespaces

      Returns:

      ::

          {'namespace-name1': {...},
           'namespace-name2': {...}
           ,...
        }
github numenta / numenta-apps / grok / grok / app / webservices / cloudwatch_api.py View on Github external
# than namespace.  The web ui must be updated to follow this convention.
  # Until then, the API is remaining the same, requiring massaging data to
  # fit the expected response format
  namespaces = {}
  for _, metrics in resources.items():
    for (metricName, metric) in metrics.items():
      namespace = namespaces.setdefault(metric["namespace"], {})
      (namespace.setdefault("metrics", set())
                .add(metricName))
      (namespace.setdefault("dimensions", set())
                .update(metric["dimensionGroups"][0]))

  return namespaces


class CWDefaultHandler(AuthenticatedBaseHandler):
  def GET(self): # pylint: disable=R0201
    """
    Describe Cloudwatch datasource, listing all supported regions, namespaces
    and metrics

      ::

          GET /_metrics/cloudwatch

      Returns:

      ::

        {
            'regions': { 'region-name": 'region-description',...},
            'namespaces': {
github numenta / numenta-apps / grok / grok / app / webservices / metrics_api.py View on Github external
from grok.app.adapters.datasource import listDatasourceNames
from grok.app.webservices import (AuthenticatedBaseHandler,
                                  cloudwatch_api,
                                  custom_api)



urls = (
  "/datasources", "MetricsHandler",
  "/cloudwatch", cloudwatch_api.app,
  "/custom", custom_api.app,
  "/?", "MetricsHandler"
)


class MetricsHandler(AuthenticatedBaseHandler):
  """
    List supported datasources

    ::

        GET /_metrics/datasources

    Returns:

    ::

        ["autostack", "cloudwatch", "custom"]
  """
  def GET(self):
    self.addStandardHeaders()
    return utils.jsonEncode(self.getDatasources())
github numenta / numenta-apps / grok / grok / app / webservices / instances_api.py View on Github external
resourceType = cloudwatch.NAMESPACE_TO_RESOURCE_TYPE[namespace]
          except KeyError:
            raise InvalidRequestResponse({"result": "Not supported."})

          modelSpecs = cwAdapter.getDefaultModelSpecs(
              resourceType, region, instanceId, dimension)

          for modelSpec in modelSpecs:
            ModelHandler.createModel(modelSpec)

    self.addStandardHeaders()
    return encodeJson({"result": "success"})



class InstancesHandler(AuthenticatedBaseHandler):


  def DELETE(self):
    """
    Delete models for multiple instances

    ::

        DELETE /_instances

    DELETE data:

    ::

        [
            "{region}/{namespace}/{instanceId}",