PKfn{N?e2redash_stmo/__init__.py# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. """Extensions to Redash by Mozilla""" __version__ = "2019.3.0" PKfn{N3svHredash_stmo/dockerflow.py# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import import logging from dockerflow.flask import Dockerflow from redash import migrate, redis_connection from redash.models import db logger = logging.getLogger(__name__) def extension(app): logger.info('Loading Redash Extension for Dockerflow') dockerflow = Dockerflow(app, db=db, migrate=migrate, redis=redis_connection) logger.info('Loaded Redash Extension for Dockerflow') return dockerflow PKfn{N|??redash_stmo/resources.pyfrom redash.handlers import api def add_resource(app, *args, **kwargs): """ After api.init_app() is called, api.app should be set by Flask (but it's not) so that further calls to add_resource() are handled immediately for the given app. """ api.app = app api.add_org_resource(*args, **kwargs) PKfn{N/redash_stmo/settings.pyimport os from redash.settings.helpers import parse_boolean, set_from_string # Frequency of health query runs in minutes (12 hours by default) HEALTH_QUERIES_REFRESH_SCHEDULE = int( os.environ.get("REDASH_HEALTH_QUERIES_REFRESH_SCHEDULE", 720) ) # When enabled this will match the given remote groups request header with a # configured list of allowed user groups. REMOTE_GROUPS_ENABLED = parse_boolean( os.environ.get("REDASH_REMOTE_GROUPS_ENABLED", "false") ) REMOTE_GROUPS_HEADER = os.environ.get( "REDASH_REMOTE_GROUPS_HEADER", "X-Forwarded-Remote-Groups" ) REMOTE_GROUPS_ALLOWED = set_from_string( os.environ.get("REDASH_REMOTE_GROUPS_ALLOWED", "") ) PKfn{N$redash_stmo/data_sources/__init__.pyPKfn{Nb($dd"redash_stmo/data_sources/health.pyimport os import json import time from redash_stmo import settings from redash_stmo.resources import add_resource from flask import jsonify from flask_login import login_required from celery.utils.log import get_task_logger from redash import models, redis_connection, statsd_client from redash.worker import celery from redash.utils import parse_human_time from redash.monitor import get_status as original_get_status from redash.handlers.base import routes, BaseResource from redash.permissions import require_super_admin logger = get_task_logger(__name__) class DataSourceHealthResource(BaseResource): def get(self): health_data = json.loads(redis_connection.get('data_sources:health') or '{}') return jsonify(health_data) def store_health_status(data_source_id, data_source_name, query_text, data): key = "data_sources:health" cache = json.loads(redis_connection.get(key) or '{}') if data_source_id not in cache: cache[data_source_id] = { "metadata": {"name": data_source_name}, "queries": {} } cache[data_source_id]["queries"][query_text] = data cache[data_source_id]["status"] = "SUCCESS" for query_status in cache[data_source_id]["queries"].values(): if query_status["status"] == "FAIL": cache[data_source_id]["status"] = "FAIL" break redis_connection.set(key, json.dumps(cache)) @celery.task(name="redash_stmo.health.update_health_status", time_limit=90, soft_time_limit=60) def update_health_status(): for data_source in models.DataSource.query: logger.info(u"task=update_health_status state=start ds_id=%s", data_source.id) runtime = None query_text = data_source.query_runner.noop_query ds_id = str(data_source.id) custom_query_env_var = "REDASH_CUSTOM_HEALTH_QUERIES_{data_source_id}".format(data_source_id=ds_id) custom_query = os.environ.get(custom_query_env_var, "") query_text = custom_query or query_text try: start_time = time.time() test_connection(data_source.query_runner, query_text) runtime = time.time() - start_time except NotImplementedError: logger.info(u"Unable to compute health status without test query for %s", data_source.name) continue except Exception: logger.warning(u"Failed health check for the data source: %s", data_source.name, exc_info=1) statsd_client.incr('update_health_status.error') logger.info(u"task=update_health_status state=error ds_id=%s runtime=%.2f", data_source.id, time.time() - start_time) status = { "status": "FAIL" if runtime is None else "SUCCESS", "last_run": start_time, "last_run_human": str(parse_human_time(str(start_time))), "runtime": runtime } store_health_status(ds_id, data_source.name, query_text, status) def test_connection(self, custom_query_text=None): if self.noop_query is None: raise NotImplementedError() query_text = custom_query_text or self.noop_query data, error = self.run_query(query_text, None) if error is not None: raise Exception(error) @login_required @require_super_admin def stmo_status_api(): status = original_get_status() health_data = json.loads(redis_connection.get('data_sources:health') or '{}') # Get the top level status for each data source for health_data_point in health_data.values(): data_source_name = health_data_point["metadata"]["name"] dashboard_label = "[Data Source Health] {name}".format(name=data_source_name) status[dashboard_label] = health_data_point["status"] return jsonify(status) def extension(app=None): """A Redash extension to add datasource health status reporting.""" # Override the default status API view with our extended view app.view_functions['%s.status_api' % routes.name] = stmo_status_api # Add a new endpoint with full health data add_resource(app, DataSourceHealthResource, '/status/data_sources/health.json') # Add the update_health_status task to a list of periodic tasks if not hasattr(app, 'periodic_tasks'): app.periodic_tasks = {} app.periodic_tasks['update_health_status'] = { 'sig': update_health_status.s(), 'schedule': settings.HEALTH_QUERIES_REFRESH_SCHEDULE, } PKfn{N.MV V )redash_stmo/data_sources/link/__init__.pyfrom redash.models import DataSource from redash.handlers.base import BaseResource, get_object_or_404 from redash.permissions import require_access, view_only from redash.query_runner import query_runners from redash_stmo.resources import add_resource DATASOURCE_URLS = { "bigquery": "https://cloud.google.com/bigquery/docs/reference/legacy-sql", "Cassandra": "http://cassandra.apache.org/doc/latest/cql/index.html", "dynamodb_sql": "https://dql.readthedocs.io/en/latest/", "baseelasticsearch": "https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html", "google_spreadsheets": "http://redash.readthedocs.io/en/latest/datasources.html#google-spreadsheets", "hive": "https://cwiki.apache.org/confluence/display/Hive/LanguageManual", "impala": "http://www.cloudera.com/documentation/enterprise/latest/topics/impala_langref.html", "influxdb": "https://docs.influxdata.com/influxdb/v1.0/query_language/spec/", "jirajql": "https://confluence.atlassian.com/jirasoftwarecloud/advanced-searching-764478330.html", "mongodb": "https://docs.mongodb.com/manual/reference/operator/query/", "mssql": "https://msdn.microsoft.com/en-us/library/bb510741.aspx", "mysql": "https://dev.mysql.com/doc/refman/5.7/en/", "oracle": "http://docs.oracle.com/database/121/SQLRF/toc.htm", "pg": "https://www.postgresql.org/docs/current/", "redshift": "http://docs.aws.amazon.com/redshift/latest/dg/cm_chap_SQLCommandRef.html", "presto": "https://prestodb.io/docs/current/", "python": "http://redash.readthedocs.io/en/latest/datasources.html#python", "insecure_script": "http://redash.readthedocs.io/en/latest/datasources.html#python", "sqlite": "http://sqlite.org/lang.html", "treasuredata": "https://docs.treasuredata.com/categories/hive", "url": "http://redash.readthedocs.io/en/latest/datasources.html#url", "vertica": ( "https://my.vertica.com/docs/8.0.x/HTML/index.htm#Authoring/" "ConceptsGuide/Other/SQLOverview.htm%3FTocPath%3DSQL" "%2520Reference%2520Manual%7C_____1" ) } class DataSourceLinkResource(BaseResource): def get(self, data_source_id): data_source = get_object_or_404( DataSource.get_by_id_and_org, data_source_id, self.current_org, ) require_access(data_source.groups, self.current_user, view_only) try: result = { "type_name": data_source.query_runner.name(), "doc_url": data_source.options.get("doc_url", None) } except Exception as e: return {"message": unicode(e), "ok": False} else: return {"message": result, "ok": True} def extension(app=None): for runner_type, runner_class in query_runners.items(): if runner_type not in DATASOURCE_URLS: continue runner_class.add_configuration_property("doc_url", { "type": "string", "title": "Documentation URL", "default": DATASOURCE_URLS[runner_type]}) add_resource(app, DataSourceLinkResource, '/api/data_sources//link') PKfn{N$Y7redash_stmo/data_sources/link/bundle/datasource_link.js/* eslint-disable no-console, camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { react2angular } from 'react2angular'; class DatasourceLink extends React.Component { static propTypes = { clientConfig: PropTypes.object.isRequired, datasourceId: PropTypes.number.isRequired, } constructor(props) { super(props); this.state = { type_name: '', doc_url: '', }; } componentDidMount() { this.loadURLData(); } componentDidUpdate(prevProps) { if (this.props.datasourceId !== prevProps.datasourceId) { this.loadURLData(); } } loadURLData() { fetch(`${this.props.clientConfig.basePath}api/data_sources/${this.props.datasourceId}/link`) .then((response) => { if (response.status === 200) { return response.json(); } return {}; }) .catch((error) => { console.error(`Error loading data source URL: ${error}`); return {}; }) .then((json) => { const { type_name, doc_url } = json.message; this.setState({ type_name, doc_url }); }); } render() { if (!this.state.doc_url) { return null; } return ( {this.state.type_name} documentation ); } } export default function init(ngModule) { ngModule.component('datasourceLink', react2angular(DatasourceLink, ['datasourceId'], ['clientConfig'])); } init.init = true; PKfn{N="]].redash_stmo/data_sources/validator/__init__.pyimport subprocess import apiclient.errors from flask import request from redash import models from redash.handlers.base import BaseResource, get_object_or_404 from redash.permissions import not_view_only, has_access from redash.utils import collect_parameters_from_request, json_loads, mustache_render from redash_stmo.resources import add_resource class DataSourceValidatorResource(BaseResource): def validate_pg(self, query_runner, query): p = subprocess.Popen("pgsanity", stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, _ = p.communicate(query + ";") return p.returncode == 0, stdout def validate_bigquery(self, query_runner, query): jobs = query_runner._get_bigquery_service().jobs() project_id = query_runner._get_project_id() job_data = { "configuration": { "query": { "query": query, }, "dryRun": True, } } if query_runner.configuration.get('useStandardSql', False): job_data['configuration']['query']['useLegacySql'] = False if query_runner.configuration.get('userDefinedFunctionResourceUri'): resource_uris = query_runner.configuration["userDefinedFunctionResourceUri"].split(',') job_data["configuration"]["query"]["userDefinedFunctionResources"] = map( lambda resource_uri: {"resourceUri": resource_uri}, resource_uris) if "maximumBillingTier" in query_runner.configuration: job_data["configuration"]["query"]["maximumBillingTier"] = query_runner.configuration["maximumBillingTier"] insert_response = jobs.insert(projectId=project_id, body=job_data).execute() if 'errorResult' in insert_response['status']: return False, insert_response['status']['errorResult'] return True, "This query will process %s bytes." % (insert_response['statistics']['totalBytesProcessed'],) def get_validator(self, query_runner): """Return the query validator for the given query runner""" try: validator = getattr(self, 'validate_%s' % query_runner.type()) if callable(validator): return validator except AttributeError: pass def post(self, data_source_id): params = request.get_json(force=True) parameter_values = collect_parameters_from_request(request.args) query = mustache_render(params['query'], parameter_values) data_source = get_object_or_404( models.DataSource.get_by_id_and_org, data_source_id, self.current_org, ) # get the validator method validator = self.get_validator(data_source.query_runner) if (validator is None or not has_access(data_source.groups, self.current_user, not_view_only)): return { 'valid': False, 'report': 'You do not have permission to run queries with this data source.' }, 403 try: valid, report = validator(data_source.query_runner, query) return {'valid': valid, 'report': report}, 200 except apiclient.errors.HttpError as e: if e.resp.status == 400: error = json_loads(e.content)['error']['message'] else: error = e.content return {'valid': False, 'report': error}, 200 except Exception as e: return {'valid': False, 'report': str(e)}, 500 def extension(app): add_resource(app, DataSourceValidatorResource, '/api/data_sources//validate') PKfn{NX˂Aredash_stmo/data_sources/validator/bundle/datasource_validator.js/* eslint-disable camelcase */ import React from 'react'; import { render } from 'react-dom'; import { debounce } from 'lodash'; function getValidateQuery($http, dataSourceId, query) { return $http.post(`api/data_sources/${dataSourceId}/validate`, { query }); } class DataSourceValidator extends React.Component { constructor(props) { super(props); this.getValidateQuery = debounce(getValidateQuery, 500); this.state = { valid: false, report: '', }; } componentDidMount() { this.componentDidUpdate(); } componentDidUpdate(prevProps, prevState) { const queryTextChanged = !prevProps || prevProps.queryText !== this.props.queryText; const reportChanged = prevState && prevState.report !== this.state.report; if (queryTextChanged || reportChanged) { const p = this.getValidateQuery(this.props.$http, this.props.dataSourceId, this.props.queryText); if (p) { p.then((response) => { this.setState(response.data); }); } } } render() { return ( {this.state.report} ); } } export default function init(ngModule) { ngModule.decorator('queryEditorDirective', ['$delegate', '$http', ($delegate, $http) => { const controller = $delegate[0].controller; const controllerFunc = controller[controller.length - 1]; controllerFunc.prototype.origRender = controllerFunc.prototype.render; controllerFunc.prototype.render = function newRender() { this.origRender(); const container = document.querySelector('.editor__control div'); let status = document.querySelector('#stmo_datasource_validator'); if (!status) { status = document.createElement('div'); status.id = 'stmo_datasource_validator'; } else { container.removeChild(status); } container.appendChild(status); render( , status, ); }; return $delegate; }]); } init.init = true; PKfn{N,redash_stmo/data_sources/version/__init__.pyimport json import logging from redash_stmo.resources import add_resource from redash.models import DataSource from redash.handlers.base import BaseResource, get_object_or_404 from redash.permissions import require_access, view_only logger = logging.getLogger(__name__) DATASOURCE_VERSION_PARSE_INFO = { "pg": { "version_query": "SELECT version();", "delimiter": " ", "index": 1 }, "redshift": { "version_query": "SELECT version();", "delimiter": " ", "index": -1 }, "mysql": { "version_query": "SELECT VERSION() AS version;", "delimiter": "-", "index": 0 }, } class DataSourceVersionResource(BaseResource): def get(self, data_source_id): data_source = get_object_or_404( DataSource.get_by_id_and_org, data_source_id, self.current_org ) require_access(data_source.groups, self.current_user, view_only) version_info = get_data_source_version(data_source.query_runner) return {"version": version_info} def get_data_source_version(query_runner): parse_info = DATASOURCE_VERSION_PARSE_INFO.get(query_runner.type()) if parse_info is None: return None data, error = query_runner.run_query(parse_info["version_query"], None) if error is not None: logger.error( "Unable to run version query for %s: %s", query_runner.type(), error) return None try: version = json.loads(data)['rows'][0]['version'] except (KeyError, IndexError) as err: logger.exception( "Unable to parse data source version for %s: %s", query_runner.type(), err) return None version = version.split(parse_info["delimiter"])[parse_info["index"]] return version def extension(app=None): add_resource(app, DataSourceVersionResource, '/api/data_sources//version') PKfn{Nehh=redash_stmo/data_sources/version/bundle/datasource_version.js/* eslint-disable no-console, camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { react2angular } from 'react2angular'; class DatasourceVersion extends React.Component { static propTypes = { clientConfig: PropTypes.object.isRequired, datasourceId: PropTypes.number.isRequired, } constructor(props) { super(props); this.state = { version: '', }; } componentDidMount() { this.loadURLData(); } componentDidUpdate(prevProps) { if (this.props.datasourceId !== prevProps.datasourceId) { this.loadURLData(); } } loadURLData() { fetch(`${this.props.clientConfig.basePath}api/data_sources/${this.props.datasourceId}/version`) .then((response) => { if (response.status === 200) { return response.json(); } return {}; }) .catch((error) => { console.error(`Error loading data source version: ${error}`); return {}; }) .then((json) => { this.setState({ version: json.version }); }); } render() { if (!this.state.version) { return null; } return ( {this.state.version} ); } } export default function init(ngModule) { ngModule.component('datasourceVersion', react2angular(DatasourceVersion, ['datasourceId'], ['clientConfig'])); } init.init = true; PKfn{N redash_stmo/handlers/__init__.pyPKfn{N/redash_stmo/handlers/authentication/__init__.pyPKfn{NO;7redash_stmo/handlers/authentication/remote_user_auth.pyfrom flask import redirect, request, url_for from redash import settings from redash.authentication import get_next_path from redash.authentication.org_resolving import current_org from redash.authentication.remote_user_auth import logger from redash_stmo import settings as extension_settings def check_remote_groups(): """Check if there is a header of user groups and if yes check it against a list of allowed user groups from the settings""" # Quick shortcut out if remote user auth or remote groups aren't enabled if ( not settings.REMOTE_USER_LOGIN_ENABLED or not extension_settings.REMOTE_GROUPS_ENABLED ): return # Generate the URL to the remote auth login endpoint if settings.MULTI_ORG: org = current_org._get_current_object() remote_auth_path = url_for("remote_user_auth.login", org_slug=org.slug) else: remote_auth_path = url_for("remote_user_auth.login") # Then only act if the request is for the remote user auth view if request.path.startswith(remote_auth_path): remote_groups = settings.set_from_string( request.headers.get(extension_settings.REMOTE_GROUPS_HEADER) or "" ) # Finally check if the remote groups found in the request header # intersect with the allowed remote groups if not extension_settings.REMOTE_GROUPS_ALLOWED.intersection(remote_groups): logger.error( "User groups provided in the %s header are not " "matching the allowed groups.", extension_settings.REMOTE_GROUPS_HEADER, ) # Otherwise redirect back to the frontpage unsafe_next_path = request.args.get("next") next_path = get_next_path(unsafe_next_path) if settings.MULTI_ORG: org = current_org._get_current_object() index_url = url_for("redash.index", org_slug=org.slug, next=next_path) else: index_url = url_for("redash.index", next=next_path) return redirect(index_url) def extension(app): """An extension that checks the REMOTE_GROUPS_HEADER.""" app.before_request(check_remote_groups) PKfn{Nj j .redash_stmo/handlers/query_results/__init__.pyfrom redash.handlers.query_results import QueryResultResource from redash.permissions import require_access, require_permission, view_only from redash.handlers.base import get_object_or_404 from redash import models from ...resources import add_resource from .parser import extract_table_names class StmoQueryResultResource(QueryResultResource): @require_permission('view_query') def get(self, query_id=None, query_result_id=None, filetype='json'): if query_result_id: query_result = get_object_or_404( models.QueryResult.get_by_id_and_org, query_result_id, self.current_org, ) # Look for queries matching this result whose data source is 'Query Results'. if models.Query.query.join( models.DataSource, ).filter( models.Query.query_hash == query_result.query_hash, models.DataSource.type == 'results', ).first(): table_names = extract_table_names(query_result.query_text) for table_name in table_names: # Look for query IDs being accessed. if table_name.startswith("query_"): try: qid = int(table_name.split('_', 1)[1]) except ValueError: # If it's not "query_NNN" it can't affect our permissions check here. continue upstream_q = models.Query.query.filter( models.Query.id == qid ).first() if upstream_q is None: continue # If the user making this request doesn't have permission to # view the query results being accessed in this query, deny # access. require_access(upstream_q.data_source.groups, self.current_user, view_only) require_access(query_result.data_source.groups, self.current_user, view_only) return super(StmoQueryResultResource, self).get(query_id, query_result_id, filetype) def extension(app): # remove the original resource del app.view_functions['query_result'] add_resource( app, StmoQueryResultResource, '/api/query_results/.', '/api/query_results/', '/api/queries//results.', '/api/queries//results/.', endpoint='query_result', ) PKfn{Nt9??,redash_stmo/handlers/query_results/parser.py#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2018 the sqlparse authors and contributors # # # This example is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause # # This example illustrates how to extract table names from nested # SELECT statements. # # See: # https://groups.google.com/forum/#!forum/sqlparse/browse_thread/thread/b0bd9a022e9d4895 import sqlparse from sqlparse.sql import IdentifierList, Identifier from sqlparse.tokens import Keyword, DML def is_subselect(parsed): if not parsed.is_group: return False for item in parsed.tokens: if item.ttype is DML and item.value.upper() == 'SELECT': return True return False def extract_from_part(parsed): from_seen = False for item in parsed.tokens: if from_seen: if is_subselect(item): for x in extract_from_part(item): yield x elif item.ttype is Keyword: raise StopIteration else: yield item elif item.ttype is Keyword and item.value.upper() == 'FROM': from_seen = True def extract_table_identifiers(token_stream): for item in token_stream: if isinstance(item, IdentifierList): for identifier in item.get_identifiers(): yield identifier.get_real_name() elif isinstance(item, Identifier): yield item.get_real_name() # It's a bug to check for Keyword here, but in the example # above some tables names are identified as keywords... elif item.ttype is Keyword: yield item.value def extract_table_names(sql): stream = extract_from_part(sqlparse.parse(sql)[0]) return list(extract_table_identifiers(stream)) PKfn{N$redash_stmo/query_runner/__init__.pyPKfn{Ns8ss&redash_stmo/query_runner/activedata.py""" A custom Redash query runner for Mozilla's ActiveData service: More information: - https://wiki.mozilla.org/EngineeringProductivity/Projects/ActiveData - https://github.com/mozilla/ActiveData/blob/dev/docs/redash.md Originally written by Github user @klahnakoski Original link: https://github.com/klahnakoski/ActiveData-redash-query-runner/blob/c0e7286c09c6f1eb6746a6c7cca581bea79f4757/active_data.py """ import json import logging import requests from redash.query_runner import (TYPE_INTEGER, TYPE_STRING, TYPE_FLOAT, BaseSQLQueryRunner, register) from redash.utils import JSONEncoder logger = logging.getLogger(__name__) TYPES_MAP = { bool: TYPE_INTEGER, str: TYPE_STRING, unicode: TYPE_STRING, dict: TYPE_STRING, list: TYPE_STRING, int: TYPE_INTEGER, long: TYPE_INTEGER, float: TYPE_FLOAT, "string": TYPE_STRING, "object": TYPE_STRING, "long": TYPE_STRING, "double": TYPE_FLOAT, "integer": TYPE_FLOAT } class ActiveData(BaseSQLQueryRunner): noop_query = "SELECT 1" @classmethod def configuration_schema(cls): return { "type": "object", "properties": { "host_url": { "type": "string", "title": "Host URL", "default": "https://activedata.allizom.org:80", "info": "Please include a port. Do not end with a trailing slash." }, "doc_url": { "type": "string", "title": "Documentation URL", "default": "https://github.com/klahnakoski/ActiveData/tree/dev/docs" }, "toggle_table_string": { "type": "string", "title": "Toggle Table String", "default": "_v", "info": "This string will be used to toggle visibility of tables in the schema browser when editing a query in order to remove non-useful tables from sight." } }, "required": ["host_url"] } @classmethod def name(cls): return "ActiveData" @classmethod def type(cls): return "activedata" @classmethod def enabled(cls): return True def _get_tables(self, schema): query = { "from": "meta.columns", "select": [ "name", "type", "table" ], "where": {"not": {"prefix": {"es_index": "meta."}}}, "limit": 1000, "format": "list" } results = self.run_jx_query(query, None) for row in results['data']: table_name = row['table'] if table_name not in schema: schema[table_name] = {'name': table_name, 'columns': []} schema[table_name]['columns'].append( row['name'] + ' (' + TYPES_MAP.get(row['type'], TYPE_STRING) + ')' ) return [ { 'name': table['name'], 'columns': sorted(table['columns']) } for table in schema.values() ] def run_jx_query(self, query, user): data = json.dumps(query, ensure_ascii=False) result = requests.post( self.configuration['host_url'] + "/query", data=data, ) response = json.loads(result.content) if response.get('type') == "ERROR": cause = self.find_error_cause(response) raise Exception(cause) return response def run_query(self, annotated_query, user): request = {} comment, request["sql"] = annotated_query.split("*/", 2) meta = request['meta'] = {} for kv in comment.strip()[2:].split(","): k, v = [s.strip() for s in kv.split(':')] meta[k] = v logger.debug("Send ActiveData a SQL query: %s", request['sql']) data = json.dumps(request, ensure_ascii=False) result = requests.post( self.configuration['host_url'] + "/sql", data=data, ) response = json.loads(result.content) if response.get('type') == "ERROR": cause = self.find_error_cause(response) return None, cause output = self.normalize_response(response) json_data = json.dumps(output, cls=JSONEncoder) return json_data, None def normalize_response(self, table): columns = {} # MAP FROM name TO (MAP FROM type TO (full_name)) output = [] def get_unique_name(name, type): all_types = columns.get(name) if all_types is None: all_types = columns[name] = {} specific_type = all_types.get(type) if specific_type is None: if all_types: specific_type = all_types[type] = name + "." + type else: specific_type = all_types[type] = name return specific_type for r in table['data']: new_row = {} for i, cname in enumerate(table['header']): val = r[i] if val is None: continue if isinstance(val, (dict, list)): val = json.dumps(val, cls=JSONEncoder) col = get_unique_name(cname, TYPES_MAP.get(type(val), TYPE_STRING)) new_row[col] = val output.append(new_row) output_columns = [ { "name": full_name, "type": ctype, "friendly_name": full_name } for cname, types in columns.items() for ctype, full_name in types.items() ] return { 'columns': output_columns, 'rows': output } def find_error_cause(self, response): while response.get('cause') is not None: cause = response['cause'] if isinstance(cause, list): response = cause[0] else: response = cause return response.get('template') register(ActiveData) PKfn{NMsRz z "redash_stmo/query_runner/presto.pyimport collections import logging import six from pyhive import presto from redash.query_runner.presto import Presto from redash.query_runner import register logger = logging.getLogger(__name__) class STMOPresto(Presto): """ A custom Presto query runner. Currently empty. """ class STMOConnection(presto.Connection): """ A custom Presto connection that uses the custom Presto cursor as the default cursor. """ def cursor(self): return STMOPrestoCursor(*self._args, **self._kwargs) class STMOPrestoCursor(presto.Cursor): """ A custom Presto cursor that processes the data after it has been handled by the parent cursor to apply various transformations. """ def _process_response(self, response): super(STMOPrestoCursor, self)._process_response(response) self._data = self._process_data() def _process_data(self): processed_data = collections.deque() for row in self._data: # the top-level is an iterable of records (i.e. rows) item = [] for column, row in zip(self._columns, row): item.append(self._format_data(column["typeSignature"], row)) processed_data.append(item) return processed_data def _format_data(self, column, data): """Given a Presto column and its data, return a more human-readable format of its data for some data types.""" type = column["rawType"] try: iter(data) # check if the data is iterable except TypeError: return data # non-iterables can simply be directly shown # records should have their fields associated with types # but keep the tuple format for backward-compatibility if type == "row": keys = column["literalArguments"] values = [ self._format_data(c, d) for c, d in zip(column["typeArguments"], data) ] return tuple(zip(keys, values)) # arrays should have their element types associated with each element elif type == "array": rep = [ column["typeArguments"][0] ] * len(data) return ( self._format_data(c, d) for c, d in zip(rep, data) ) # maps should have their value types associated with each value # (note that keys are always strings), but keep the tuple format # for backward-compatibility elif type == "map": value_type = column["typeArguments"][1] return ( (k, self._format_data(value_type, v)) for k, v in six.iteritems(data) ) else: # unknown type, don't process it return data def stmo_connect(*args, **kwargs): """ A custom connect function to be used to override the default pyhive.presto.connect function. """ return STMOConnection(*args, **kwargs) def extension(app): logger.info('Loading Redash Extension for the custom Presto query runner') # Monkeypatch the pyhive.presto.connect function presto.connect = stmo_connect # and register our own STMOPresto query runner class # which automatically overwrites the default presto query runner register(STMOPresto) logger.info('Loaded Redash Extension for the custom Presto query runner') return stmo_connect PK!H" /redash_stmo-2019.3.0.dist-info/entry_points.txt} F0>`O262k$-4; ~ Gs YщL`1ݺ~ c3}~LWcF_M齶:GψeUV3'i`HFIg-`бMJMo(#=j\֙)PKfn{Ni0UAUA&redash_stmo-2019.3.0.dist-info/LICENSEMozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. PK!HMuSa$redash_stmo-2019.3.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!HjD 'redash_stmo-2019.3.0.dist-info/METADATAV[s6~ׯ8C LlC. m&&3,;eDdF$o}7gC%Y\t.ј̥џl2⽬xDsʈ_g1mJzБ7StIcZ SqK7JBMTIգ]gT'q$5ms%J(Et).^-9̪&EgF>-|:/δtN9/X^hD/(5yK ޛz;=(|:7Zo-~cu- !s:msu`W K:mkPݺIjmH3=\Z JCT-J M|}4w|(>@gk8X㧁4HoOl">VYv9Z=mksmn^`^1w0?~}эݣfY)_=,O}ɵ|}4>ޏFM0YV =P>w.*ރUHwA(3 ky/(B@ URlAl?!V~ݢ'K[?MΨ $ `2Ie^p`gPTUĮTs4; `/ǓEt|svSJɥLjTlX/ijFZբqY;.h`m#Ḫ.Ҵra[ .Wj6F }b~7ݔ֧ e5ƬτRzek8%<R&4ꌟwGq*#H228,q.4iRdH|0,5RnBTMu6Fuz?V[àrkkc;=uu MQH \`GὥM6`(/^-^_7]j4 Cu!Lfmc{+Yk10?3a Υ@b86[tCA=dpDhfawԭ@ʃY[κROX]bEn_Iy +BjƶEn Yo=PK!HѠd]7 %redash_stmo-2019.3.0.dist-info/RECORDIH[ 28l2I_߾m;nmaupYU֌DE /7{XtF +#e8[~g널)FL0}%u6-0;ù$v]m \ә%Pq6 -꾍aUʼn&~s:`=?t(',TEG ƨ:>ŨǦr\6gn(6G%R6J+Stt!Qx|U8VI2/"o[*Wp4Vl A}N`T;jO7vl*\Ik %8]*+K:96fbq0u}c:\KKP8UR ۩;#2g seL!ﴀ:)Z"6|M<7D+[ƤoIѸ#snjg2,NɡVDwd`p$.RCK=;{ YԨ0#If^e!;؂҃ˆC ,O~BEnфMhqWq=70ksƾ/yYF2pəd`!fõ?pA&jDZ) C'V yuJP[)'茙e%wv_UE }zѩq$4-9^Tvf c6A8?P~/ ^z(O9WM#WZ;kr/]+O EoJ55p#sfKj3.5o^B=Sp c6L$E +T5~ЍqۏXd6P iFf* ZJ6-cfgz`dZs0r'k A@k9H< YtO]\ZcAޮup y,z*9{ټV/._kb=%/PKfn{N?e2redash_stmo/__init__.pyPKfn{N3svH<redash_stmo/dockerflow.pyPKfn{N|??redash_stmo/resources.pyPKfn{N/predash_stmo/settings.pyPKfn{N$Iredash_stmo/data_sources/__init__.pyPKfn{Nb($dd"redash_stmo/data_sources/health.pyPKfn{N.MV V )/redash_stmo/data_sources/link/__init__.pyPKfn{N$Y7&redash_stmo/data_sources/link/bundle/datasource_link.jsPKfn{N="]].-redash_stmo/data_sources/validator/__init__.pyPKfn{NX˂A;redash_stmo/data_sources/validator/bundle/datasource_validator.jsPKfn{N,Dredash_stmo/data_sources/version/__init__.pyPKfn{Nehh=bLredash_stmo/data_sources/version/bundle/datasource_version.jsPKfn{N %Rredash_stmo/handlers/__init__.pyPKfn{N/cRredash_stmo/handlers/authentication/__init__.pyPKfn{NO;7Rredash_stmo/handlers/authentication/remote_user_auth.pyPKfn{Nj j .[redash_stmo/handlers/query_results/__init__.pyPKfn{Nt9??,lfredash_stmo/handlers/query_results/parser.pyPKfn{N$mredash_stmo/query_runner/__init__.pyPKfn{Ns8ss&7nredash_stmo/query_runner/activedata.pyPKfn{NMsRz z "redash_stmo/query_runner/presto.pyPK!H" /redash_stmo-2019.3.0.dist-info/entry_points.txtPKfn{Ni0UAUA&redash_stmo-2019.3.0.dist-info/LICENSEPK!HMuSa$=redash_stmo-2019.3.0.dist-info/WHEELPK!HjD 'redash_stmo-2019.3.0.dist-info/METADATAPK!HѠd]7 %redash_stmo-2019.3.0.dist-info/RECORDPKlY