1# -*- coding: utf-8 -*- #
2# Copyright 2015 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""'logging metrics update' command."""
17
18from __future__ import absolute_import
19from __future__ import division
20from __future__ import unicode_literals
21
22from googlecloudsdk.api_lib.logging import util
23from googlecloudsdk.calliope import arg_parsers
24from googlecloudsdk.calliope import base
25from googlecloudsdk.core import log
26
27
28@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
29                    base.ReleaseTrack.ALPHA)
30class Update(base.UpdateCommand):
31  """Updates the definition of a logs-based metric."""
32
33  detailed_help = {
34      'DESCRIPTION': """\
35          Updates the description or the filter expression of an existing
36          logs-based metric.
37      """,
38      'EXAMPLES': """\
39          To update the description of a metric called high_severity_count, run:
40
41            $ {command} high_severity_count --description="Count of high-severity log entries."
42
43          To update the filter expression of the metric, run:
44
45            $ {command} high_severity_count --log-filter="severity >= WARNING"
46
47          Detailed information about filters can be found at:
48          [](https://cloud.google.com/logging/docs/view/advanced_filters)
49
50          For advanced features such as user-defined labels and distribution
51          metrics, update using a config file:
52
53            $ {command} high_severity_count --config-from-file=$PATH_TO_FILE
54
55          The config file should be in YAML format. Detailed information about
56          how to configure metrics can be found at: [](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics#LogMetric).
57          Any top-level fields in the LogMetric definition that aren't specified
58          in the config file will not be updated in the metric.
59      """,
60  }
61
62  @staticmethod
63  def Args(parser):
64    """Register flags for this command."""
65    parser.add_argument(
66        'metric_name', help='The name of the log-based metric to update.')
67    config_group = parser.add_argument_group(
68        help='Data about the metric to update.',
69        mutex=True,
70        required=True)
71    legacy_mode_group = config_group.add_argument_group(
72        help=('Arguments to specify information about simple counter logs-'
73              'based metrics.'))
74    legacy_mode_group.add_argument(
75        '--description', required=False,
76        help=('A new description for the metric. '
77              'If omitted, the description is not changed.'))
78    legacy_mode_group.add_argument(
79        '--log-filter', required=False,
80        help=('A new filter string for the metric. '
81              'If omitted, the filter is not changed.'))
82    config_group.add_argument('--config-from-file',
83                              help=('A path to a YAML file specifying the '
84                                    'updates to be made to the logs-based '
85                                    'metric.'),
86                              type=arg_parsers.FileContents())
87
88  def Run(self, args):
89    """This is what gets called when the user runs this command.
90
91    Args:
92      args: an argparse namespace. All the arguments that were provided to
93        this command invocation.
94
95    Returns:
96      The updated metric.
97    """
98
99    # Calling the API's Update method on a non-existing metric creates it.
100    # Make sure the metric exists so we don't accidentally create it.
101    metric = util.GetClient().projects_metrics.Get(
102        util.GetMessages().LoggingProjectsMetricsGetRequest(
103            metricName=util.CreateResourceName(
104                util.GetCurrentProjectParent(), 'metrics', args.metric_name)))
105
106    updated_metric = util.UpdateLogMetric(metric,
107                                          args.description,
108                                          args.log_filter,
109                                          args.config_from_file)
110
111    result = util.GetClient().projects_metrics.Update(
112        util.GetMessages().LoggingProjectsMetricsUpdateRequest(
113            metricName=util.CreateResourceName(
114                util.GetCurrentProjectParent(), 'metrics', args.metric_name),
115            logMetric=updated_metric))
116    log.UpdatedResource(args.metric_name)
117    return result
118