# Copyright 2021 Google LLC
#
# 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.

# Lint as: python3
"""Cloud Functions have no scale up issues.

Log entries with Cloud Functions having scale up issues have been found.
"""

from gcpdiag import lint, models
from gcpdiag.queries import gcf, logs

#pylint: disable=line-too-long

MATCH_STR = 'The request was aborted because there was no available instance.'

logs_by_project = {}


def prepare_rule(context: models.Context):
  logs_by_project[context.project_id] = logs.query(
      project_id=context.project_id,
      resource_type='cloud_function',
      log_name='log_id("cloudfunctions.googleapis.com/cloud-functions")',
      filter_str=f'textPayload:"{MATCH_STR}"')


def run_rule(context: models.Context, report: lint.LintReportRuleInterface):
  cloudfunctions = gcf.get_cloudfunctions(context)
  if not cloudfunctions:
    report.add_skipped(None, f'no functions found {context}')
    return

  failed_functions = set()

  for query in logs_by_project.values():
    for log_entry in query.entries:
      if 'resource' in log_entry and 'httpRequest' in log_entry:
        if 'labels' in log_entry['resource'] and 'status' in log_entry[
            'httpRequest']:
          if 'function_name' in log_entry['resource']['labels']:
            function_name = log_entry['resource']['labels']['function_name']
            status = log_entry['httpRequest']['status']
            if status in [429, 500]:
              failed_functions.add(function_name)

  for _, cloudfunction in sorted(cloudfunctions.items()):
    if cloudfunction.name in failed_functions:
      report.add_failed(cloudfunction,
                        f'{cloudfunction.name} failed to scale up.')
    else:
      report.add_ok(cloudfunction)

@@ -709,16 +709,55 @@
 und.%0A%22%22%22
+%0Afrom boltons.iterutils import get_path
 %0A%0Afrom g
@@ -1595,267 +1595,166 @@
  if 
-'resource' in log_entry and 'httpRequest' in log_entry:%0A        if 'labels' in log_entry%5B'resource'%5D and 'status' in log_entry%5B%0A            'httpRequest'%5D:%0A          if 'function_name' in log_entry%5B'resource'%5D%5B'labels'%5D:%0A            function_name = log_entry%5B
+MATCH_STR not in get_path(log_entry, ('textPayload'), default=''):%0A        continue%0A      function_name = get_path(log_entry,%0A                               (
 'res
@@ -1763,18 +1763,18 @@
 rce'
-%5D%5B
+, 
 'labels'
 %5D%5B'f
@@ -1769,18 +1769,18 @@
 'labels'
-%5D%5B
+, 
 'functio
@@ -1786,17 +1786,18 @@
 on_name'
-%5D
+),
 %0A       
@@ -1805,17 +1805,63 @@
     
-status = 
+                   default='')%0A      status = get_path(
 log_
@@ -1865,17 +1865,19 @@
 og_entry
-%5B
+, (
 'httpReq
@@ -1885,18 +1885,18 @@
 est'
-%5D%5B
+, 
 'status'
 %5D%0A  
@@ -1895,16 +1895,22 @@
 tus'
-%5D%0A      
+), default=0)%0A
     
@@ -1934,24 +1934,36 @@
 29, 500%5D
-:%0A      
+ and function_name:%0A
         

Add check for MATCH_STR