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"""Implementation of gcloud dataflow jobs drain command.
17"""
18
19from __future__ import absolute_import
20from __future__ import division
21from __future__ import unicode_literals
22
23from googlecloudsdk.api_lib.dataflow import apis
24from googlecloudsdk.api_lib.util import exceptions
25from googlecloudsdk.calliope import base
26from googlecloudsdk.command_lib.dataflow import job_utils
27from googlecloudsdk.core import log
28
29
30@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
31class Drain(base.Command):
32  """Drains all jobs that match the command line arguments.
33
34     Once Drain is triggered, the pipeline will stop accepting new inputs.
35     The input watermark will be advanced to infinity. Elements already in the
36     pipeline will continue to be processed. Drained jobs can safely be
37     cancelled.
38  """
39
40  @staticmethod
41  def Args(parser):
42    """Register flags for this command."""
43    job_utils.ArgsForJobRefs(parser, nargs='+')
44
45  def Run(self, args):
46    """This is what gets called when the user runs this command.
47
48    Args:
49      args: all the arguments that were provided to this command invocation.
50    """
51    for job_ref in job_utils.ExtractJobRefs(args):
52      try:
53        apis.Jobs.Drain(
54            job_ref.jobId,
55            project_id=job_ref.projectId,
56            region_id=job_ref.location)
57        log.status.Print('Started draining job [{0}]'.format(job_ref.jobId))
58      except exceptions.HttpException as error:
59        log.status.Print((
60            "Failed to drain job [{0}]: {1} Please ensure you have permission "
61            "to access the job and the `--region` flag, {2}, matches the job\'s"
62            " region.").format(
63                job_ref.jobId, error.payload.status_message, job_ref.location))
64