<commit_before># Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed 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.
#
# Author: <NAME>

import base64
from collections import defaultdict
import logging
import numpy
import pprint
import time

from google.appengine.ext import webapp
from google.appengine.api import runtime

import big_query_backend
import big_query_client
import cloud_sql_backend
import cloud_sql_client
import server

_MIN_ENTRIES_THRESHOLD = 100
_MAX_RESULTS_PER_CYCLE = 300000

_STANDARD_QUERY_PARAMS = {
    'select': """
web100_log_entry.connection_spec.remote_ip as client_ip,
web100_log_entry.connection_spec.local_ip as server_ip,

connection_spec.client_geolocation.country_code3 as country,
connection_spec.client_geolocation.region as region,
connection_spec.client_geolocation.city as city
""",
    'from': """[%(table_name)s]""",
    'where': """
IS_EXPLICITLY_DEFINED(project)
AND project = 0

AND IS_EXPLICITLY_DEFINED(web100_log_entry.connection_spec.remote_ip)
AND IS_EXPLICITLY_DEFINED(web100_log_entry.connection_spec.local_ip)

AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.country_code3)
AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.region)
AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.city)

AND IS_EXPLICITLY_DEFINED(connection_spec.data_direction)
AND connection_spec.data_direction = 1

AND IS_EXPLICITLY_DEFINED(web100_log_entry.is_last_entry)
AND web100_log_entry.is_last_entry = True

AND IS_EXPLICITLY_DEFINED(web100_log_entry.snap.CongSignals)
AND web100_log_entry.snap.CongSignals > 0

AND IS_EXPLICITLY_DEFINED(web100_log_entry.log_time)
""",
    'group_by': """
client_ip,
server_ip,
country,
region,
city
""" }


def HANDLERS():
    return [
        ('/_ah/start', StartupHandler),
        ('/_ah/task', TaskRequestHandler),
        ('/_ah/stop', ShutdownHandler),
    ]


class StartupHandler(webapp.RequestHandler):
    def get(self):
        logging.info('Received START request.')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Started...')
        # Noop.  All work is done when the task is received.


class ShutdownHandler(webapp.RequestHandler):
    def get(self):
        logging.info('Received STOP request.')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Shutting down.')
        # Noop.  Workers watch & catch runtime.is_shutting_down().


class TaskRequestHandler(webapp.RequestHandler):
    def post(self):
        request = self.request.get('request', default_value=None)
        metric = self.request.get('metric', default_value=None)
        logging.info('Received work task. {request: %s, metric: %s}'
                     % (request, metric))

        # Connect to BigQuery & CloudSQL.
        bq_client = big_query_client.AppAssertionCredentialsBQClient(
            big_query_backend.PROJECT_ID, big_query_backend.DATASET)
        bigquery = big_query_backend.BigQueryBackend(bq_client)

        cs_client = cloud_sql_client.CloudSQLClient(
            cloud_sql_backend.INSTANCE, cloud_sql_backend.DATABASE)
        cloudsql = cloud_sql_backend.CloudSQLBackend(cs_client)

        # Dispatch the task request.
        if request == 'delete_metric':
            _DeleteMetric(metric, cloudsql)
        elif request == 'refresh_metric':
            _RefreshMetric(metric, bigquery, cloudsql)
        elif request == 'update_metric':
            _UpdateMetric(metric, bigquery, cloudsql)
        elif request == 'update_locales':
            _UpdateLocales(cloudsql)
        else:
            logging.error('Unrecognized request: %s' % request)


def _DeleteMetric(metric, cloudsql):
    logging.info('Deleting metric: %s' % metric)

    if not runtime.is_shutting_down():
        _DeleteMetricInfo(cloudsql, metric)
        _DeleteMetricData(cloudsql, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')

def _RefreshMetric(metric, bigquery, cloudsql):
    query = cloudsql.GetMetricInfo(metric)['query']
    bq_dates = bigquery.ExistingDates()
    cs_dates = cloudsql.ExistingDates()
    missing_cs_dates = set(bq_dates) - set(cs_dates)

    logging.info('Refreshing metric %s for dates: %s'
                 % (metric, sorted(missing_cs_dates)))

    for date in sorted(missing_cs_dates):
        if not runtime.is_shutting_down():
            _ComputeMetricData(bigquery, cloudsql, query, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')

def _UpdateMetric(metric, bigquery, cloudsql):
    query = cloudsql.GetMetricInfo(metric)['query']

    logging.info('Updating (regenerating) metric: %s' % metric)

    for date in sorted(bigquery.ExistingDates()):
        if not runtime.is_shutting_down():
            _DeleteMetricData(cloudsql, metric, date)
            _ComputeMetricData(bigquery, cloudsql, query, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')


def _DeleteMetricInfo(cloudsql, metric):
    logging.info('Deleting metric info for "%s".' % metric)
    cloudsql.DeleteMetricInfo(metric)<commit_msg>Create metric tables before a refresh/update in case this is a completely new metric.<commit_after># Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed 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.
#
# Author: <NAME>

import base64
from collections import defaultdict
import logging
import numpy
import pprint
import time

from google.appengine.ext import webapp
from google.appengine.api import runtime

import big_query_backend
import big_query_client
import cloud_sql_backend
import cloud_sql_client
import server

_MIN_ENTRIES_THRESHOLD = 100
_MAX_RESULTS_PER_CYCLE = 300000

_STANDARD_QUERY_PARAMS = {
    'select': """
web100_log_entry.connection_spec.remote_ip as client_ip,
web100_log_entry.connection_spec.local_ip as server_ip,

connection_spec.client_geolocation.country_code3 as country,
connection_spec.client_geolocation.region as region,
connection_spec.client_geolocation.city as city
""",
    'from': """[%(table_name)s]""",
    'where': """
IS_EXPLICITLY_DEFINED(project)
AND project = 0

AND IS_EXPLICITLY_DEFINED(web100_log_entry.connection_spec.remote_ip)
AND IS_EXPLICITLY_DEFINED(web100_log_entry.connection_spec.local_ip)

AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.country_code3)
AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.region)
AND IS_EXPLICITLY_DEFINED(connection_spec.client_geolocation.city)

AND IS_EXPLICITLY_DEFINED(connection_spec.data_direction)
AND connection_spec.data_direction = 1

AND IS_EXPLICITLY_DEFINED(web100_log_entry.is_last_entry)
AND web100_log_entry.is_last_entry = True

AND IS_EXPLICITLY_DEFINED(web100_log_entry.snap.CongSignals)
AND web100_log_entry.snap.CongSignals > 0

AND IS_EXPLICITLY_DEFINED(web100_log_entry.log_time)
""",
    'group_by': """
client_ip,
server_ip,
country,
region,
city
""" }


def HANDLERS():
    return [
        ('/_ah/start', StartupHandler),
        ('/_ah/task', TaskRequestHandler),
        ('/_ah/stop', ShutdownHandler),
    ]


class StartupHandler(webapp.RequestHandler):
    def get(self):
        logging.info('Received START request.')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Started...')
        # Noop.  All work is done when the task is received.


class ShutdownHandler(webapp.RequestHandler):
    def get(self):
        logging.info('Received STOP request.')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Shutting down.')
        # Noop.  Workers watch & catch runtime.is_shutting_down().


class TaskRequestHandler(webapp.RequestHandler):
    def post(self):
        request = self.request.get('request', default_value=None)
        metric = self.request.get('metric', default_value=None)
        logging.info('Received work task. {request: %s, metric: %s}'
                     % (request, metric))

        # Connect to BigQuery & CloudSQL.
        bq_client = big_query_client.AppAssertionCredentialsBQClient(
            big_query_backend.PROJECT_ID, big_query_backend.DATASET)
        bigquery = big_query_backend.BigQueryBackend(bq_client)

        cs_client = cloud_sql_client.CloudSQLClient(
            cloud_sql_backend.INSTANCE, cloud_sql_backend.DATABASE)
        cloudsql = cloud_sql_backend.CloudSQLBackend(cs_client)

        # Dispatch the task request.
        if request == 'delete_metric':
            _DeleteMetric(metric, cloudsql)
        elif request == 'refresh_metric':
            _RefreshMetric(metric, bigquery, cloudsql)
        elif request == 'update_metric':
            _UpdateMetric(metric, bigquery, cloudsql)
        elif request == 'update_locales':
            _UpdateLocales(cloudsql)
        else:
            logging.error('Unrecognized request: %s' % request)


def _DeleteMetric(metric, cloudsql):
    logging.info('Deleting metric: %s' % metric)

    if not runtime.is_shutting_down():
        _DeleteMetricInfo(cloudsql, metric)
        _DeleteMetricData(cloudsql, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')

def _RefreshMetric(metric, bigquery, cloudsql):
    query = cloudsql.GetMetricInfo(metric)['query']
    bq_dates = bigquery.ExistingDates()
    cs_dates = cloudsql.ExistingDates()
    missing_cs_dates = set(bq_dates) - set(cs_dates)

    logging.info('Refreshing metric %s for dates: %s'
                 % (metric, sorted(missing_cs_dates)))

    cloudsql.CreateMetricDataTable(metric)
    for date in sorted(missing_cs_dates):
        if not runtime.is_shutting_down():
            _ComputeMetricData(bigquery, cloudsql, query, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')

def _UpdateMetric(metric, bigquery, cloudsql):
    query = cloudsql.GetMetricInfo(metric)['query']

    logging.info('Updating (regenerating) metric: %s' % metric)

    cloudsql.CreateMetricDataTable(metric)
    for date in sorted(bigquery.ExistingDates()):
        if not runtime.is_shutting_down():
            _DeleteMetricData(cloudsql, metric, date)
            _ComputeMetricData(bigquery, cloudsql, query, metric, date)

    if runtime.is_shutting_down():
        logging.info('Interrupted!  Shutting down.')
    else:
        logging.info('Work completed.')


def _DeleteMetricInfo(cloudsql, metric):
    logging.info('Deleting metric info for "%s".' % metric)
    cloudsql.DeleteMetricInfo(metric)
{'fraction_non_alphanumeric': 0.09680148925368083, 'fraction_numerical': 0.008630902013877137, 'mean_word_length': 3.9286905754795662, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3294605', 'n_tokens_mistral': 3770, 'n_tokens_neox': 3640, 'n_words': 812}