1#!/usr/bin/env python
2"""CLI for dns, version v1."""
3# NOTE: This file is autogenerated and should not be edited by hand.
4
5import code
6import os
7import platform
8import sys
9
10from apitools.base.protorpclite import message_types
11from apitools.base.protorpclite import messages
12
13from google.apputils import appcommands
14import gflags as flags
15
16import apitools.base.py as apitools_base
17from apitools.base.py import cli as apitools_base_cli
18import dns_v1_client as client_lib
19import dns_v1_messages as messages
20
21
22def _DeclareDnsFlags():
23  """Declare global flags in an idempotent way."""
24  if 'api_endpoint' in flags.FLAGS:
25    return
26  flags.DEFINE_string(
27      'api_endpoint',
28      u'https://www.googleapis.com/dns/v1/',
29      'URL of the API endpoint to use.',
30      short_name='dns_url')
31  flags.DEFINE_string(
32      'history_file',
33      u'~/.dns.v1.history',
34      'File with interactive shell history.')
35  flags.DEFINE_multistring(
36      'add_header', [],
37      'Additional http headers (as key=value strings). '
38      'Can be specified multiple times.')
39  flags.DEFINE_string(
40      'service_account_json_keyfile', '',
41      'Filename for a JSON service account key downloaded'
42      ' from the Developer Console.')
43  flags.DEFINE_enum(
44      'alt',
45      u'json',
46      [u'json'],
47      u'Data format for the response.')
48  flags.DEFINE_string(
49      'fields',
50      None,
51      u'Selector specifying which fields to include in a partial response.')
52  flags.DEFINE_string(
53      'key',
54      None,
55      u'API key. Your API key identifies your project and provides you with '
56      u'API access, quota, and reports. Required unless you provide an OAuth '
57      u'2.0 token.')
58  flags.DEFINE_string(
59      'oauth_token',
60      None,
61      u'OAuth 2.0 token for the current user.')
62  flags.DEFINE_boolean(
63      'prettyPrint',
64      'True',
65      u'Returns response with indentations and line breaks.')
66  flags.DEFINE_string(
67      'quotaUser',
68      None,
69      u'Available to use for quota purposes for server-side applications. Can'
70      u' be any arbitrary string assigned to a user, but should not exceed 40'
71      u' characters. Overrides userIp if both are provided.')
72  flags.DEFINE_string(
73      'trace',
74      None,
75      'A tracing token of the form "token:<tokenid>" to include in api '
76      'requests.')
77  flags.DEFINE_string(
78      'userIp',
79      None,
80      u'IP address of the site where the request originates. Use this if you '
81      u'want to enforce per-user limits.')
82
83
84FLAGS = flags.FLAGS
85apitools_base_cli.DeclareBaseFlags()
86_DeclareDnsFlags()
87
88
89def GetGlobalParamsFromFlags():
90  """Return a StandardQueryParameters based on flags."""
91  result = messages.StandardQueryParameters()
92  if FLAGS['alt'].present:
93    result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt)
94  if FLAGS['fields'].present:
95    result.fields = FLAGS.fields.decode('utf8')
96  if FLAGS['key'].present:
97    result.key = FLAGS.key.decode('utf8')
98  if FLAGS['oauth_token'].present:
99    result.oauth_token = FLAGS.oauth_token.decode('utf8')
100  if FLAGS['prettyPrint'].present:
101    result.prettyPrint = FLAGS.prettyPrint
102  if FLAGS['quotaUser'].present:
103    result.quotaUser = FLAGS.quotaUser.decode('utf8')
104  if FLAGS['trace'].present:
105    result.trace = FLAGS.trace.decode('utf8')
106  if FLAGS['userIp'].present:
107    result.userIp = FLAGS.userIp.decode('utf8')
108  return result
109
110
111def GetClientFromFlags():
112  """Return a client object, configured from flags."""
113  log_request = FLAGS.log_request or FLAGS.log_request_response
114  log_response = FLAGS.log_response or FLAGS.log_request_response
115  api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint)
116  additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header)
117  credentials_args = {
118      'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile)
119  }
120  try:
121    client = client_lib.DnsV1(
122        api_endpoint, log_request=log_request,
123        log_response=log_response,
124        credentials_args=credentials_args,
125        additional_http_headers=additional_http_headers)
126  except apitools_base.CredentialsError as e:
127    print 'Error creating credentials: %s' % e
128    sys.exit(1)
129  return client
130
131
132class PyShell(appcommands.Cmd):
133
134  def Run(self, _):
135    """Run an interactive python shell with the client."""
136    client = GetClientFromFlags()
137    params = GetGlobalParamsFromFlags()
138    for field in params.all_fields():
139      value = params.get_assigned_value(field.name)
140      if value != field.default:
141        client.AddGlobalParam(field.name, value)
142    banner = """
143           == dns interactive console ==
144                 client: a dns client
145          apitools_base: base apitools module
146         messages: the generated messages module
147    """
148    local_vars = {
149        'apitools_base': apitools_base,
150        'client': client,
151        'client_lib': client_lib,
152        'messages': messages,
153    }
154    if platform.system() == 'Linux':
155      console = apitools_base_cli.ConsoleWithReadline(
156          local_vars, histfile=FLAGS.history_file)
157    else:
158      console = code.InteractiveConsole(local_vars)
159    try:
160      console.interact(banner)
161    except SystemExit as e:
162      return e.code
163
164
165class ChangesCreate(apitools_base_cli.NewCmd):
166  """Command wrapping changes.Create."""
167
168  usage = """changes_create <project> <managedZone>"""
169
170  def __init__(self, name, fv):
171    super(ChangesCreate, self).__init__(name, fv)
172    flags.DEFINE_string(
173        'change',
174        None,
175        u'A Change resource to be passed as the request body.',
176        flag_values=fv)
177
178  def RunWithArgs(self, project, managedZone):
179    """Atomically update the ResourceRecordSet collection.
180
181    Args:
182      project: Identifies the project addressed by this request.
183      managedZone: Identifies the managed zone addressed by this request. Can
184        be the managed zone name or id.
185
186    Flags:
187      change: A Change resource to be passed as the request body.
188    """
189    client = GetClientFromFlags()
190    global_params = GetGlobalParamsFromFlags()
191    request = messages.DnsChangesCreateRequest(
192        project=project.decode('utf8'),
193        managedZone=managedZone.decode('utf8'),
194        )
195    if FLAGS['change'].present:
196      request.change = apitools_base.JsonToMessage(messages.Change, FLAGS.change)
197    result = client.changes.Create(
198        request, global_params=global_params)
199    print apitools_base_cli.FormatOutput(result)
200
201
202class ChangesGet(apitools_base_cli.NewCmd):
203  """Command wrapping changes.Get."""
204
205  usage = """changes_get <project> <managedZone> <changeId>"""
206
207  def __init__(self, name, fv):
208    super(ChangesGet, self).__init__(name, fv)
209
210  def RunWithArgs(self, project, managedZone, changeId):
211    """Fetch the representation of an existing Change.
212
213    Args:
214      project: Identifies the project addressed by this request.
215      managedZone: Identifies the managed zone addressed by this request. Can
216        be the managed zone name or id.
217      changeId: The identifier of the requested change, from a previous
218        ResourceRecordSetsChangeResponse.
219    """
220    client = GetClientFromFlags()
221    global_params = GetGlobalParamsFromFlags()
222    request = messages.DnsChangesGetRequest(
223        project=project.decode('utf8'),
224        managedZone=managedZone.decode('utf8'),
225        changeId=changeId.decode('utf8'),
226        )
227    result = client.changes.Get(
228        request, global_params=global_params)
229    print apitools_base_cli.FormatOutput(result)
230
231
232class ChangesList(apitools_base_cli.NewCmd):
233  """Command wrapping changes.List."""
234
235  usage = """changes_list <project> <managedZone>"""
236
237  def __init__(self, name, fv):
238    super(ChangesList, self).__init__(name, fv)
239    flags.DEFINE_integer(
240        'maxResults',
241        None,
242        u'Optional. Maximum number of results to be returned. If unspecified,'
243        u' the server will decide how many results to return.',
244        flag_values=fv)
245    flags.DEFINE_string(
246        'pageToken',
247        None,
248        u'Optional. A tag returned by a previous list request that was '
249        u'truncated. Use this parameter to continue a previous list request.',
250        flag_values=fv)
251    flags.DEFINE_enum(
252        'sortBy',
253        u'changeSequence',
254        [u'changeSequence'],
255        u'Sorting criterion. The only supported value is change sequence.',
256        flag_values=fv)
257    flags.DEFINE_string(
258        'sortOrder',
259        None,
260        u"Sorting order direction: 'ascending' or 'descending'.",
261        flag_values=fv)
262
263  def RunWithArgs(self, project, managedZone):
264    """Enumerate Changes to a ResourceRecordSet collection.
265
266    Args:
267      project: Identifies the project addressed by this request.
268      managedZone: Identifies the managed zone addressed by this request. Can
269        be the managed zone name or id.
270
271    Flags:
272      maxResults: Optional. Maximum number of results to be returned. If
273        unspecified, the server will decide how many results to return.
274      pageToken: Optional. A tag returned by a previous list request that was
275        truncated. Use this parameter to continue a previous list request.
276      sortBy: Sorting criterion. The only supported value is change sequence.
277      sortOrder: Sorting order direction: 'ascending' or 'descending'.
278    """
279    client = GetClientFromFlags()
280    global_params = GetGlobalParamsFromFlags()
281    request = messages.DnsChangesListRequest(
282        project=project.decode('utf8'),
283        managedZone=managedZone.decode('utf8'),
284        )
285    if FLAGS['maxResults'].present:
286      request.maxResults = FLAGS.maxResults
287    if FLAGS['pageToken'].present:
288      request.pageToken = FLAGS.pageToken.decode('utf8')
289    if FLAGS['sortBy'].present:
290      request.sortBy = messages.DnsChangesListRequest.SortByValueValuesEnum(FLAGS.sortBy)
291    if FLAGS['sortOrder'].present:
292      request.sortOrder = FLAGS.sortOrder.decode('utf8')
293    result = client.changes.List(
294        request, global_params=global_params)
295    print apitools_base_cli.FormatOutput(result)
296
297
298class ManagedZonesCreate(apitools_base_cli.NewCmd):
299  """Command wrapping managedZones.Create."""
300
301  usage = """managedZones_create <project>"""
302
303  def __init__(self, name, fv):
304    super(ManagedZonesCreate, self).__init__(name, fv)
305    flags.DEFINE_string(
306        'managedZone',
307        None,
308        u'A ManagedZone resource to be passed as the request body.',
309        flag_values=fv)
310
311  def RunWithArgs(self, project):
312    """Create a new ManagedZone.
313
314    Args:
315      project: Identifies the project addressed by this request.
316
317    Flags:
318      managedZone: A ManagedZone resource to be passed as the request body.
319    """
320    client = GetClientFromFlags()
321    global_params = GetGlobalParamsFromFlags()
322    request = messages.DnsManagedZonesCreateRequest(
323        project=project.decode('utf8'),
324        )
325    if FLAGS['managedZone'].present:
326      request.managedZone = apitools_base.JsonToMessage(messages.ManagedZone, FLAGS.managedZone)
327    result = client.managedZones.Create(
328        request, global_params=global_params)
329    print apitools_base_cli.FormatOutput(result)
330
331
332class ManagedZonesDelete(apitools_base_cli.NewCmd):
333  """Command wrapping managedZones.Delete."""
334
335  usage = """managedZones_delete <project> <managedZone>"""
336
337  def __init__(self, name, fv):
338    super(ManagedZonesDelete, self).__init__(name, fv)
339
340  def RunWithArgs(self, project, managedZone):
341    """Delete a previously created ManagedZone.
342
343    Args:
344      project: Identifies the project addressed by this request.
345      managedZone: Identifies the managed zone addressed by this request. Can
346        be the managed zone name or id.
347    """
348    client = GetClientFromFlags()
349    global_params = GetGlobalParamsFromFlags()
350    request = messages.DnsManagedZonesDeleteRequest(
351        project=project.decode('utf8'),
352        managedZone=managedZone.decode('utf8'),
353        )
354    result = client.managedZones.Delete(
355        request, global_params=global_params)
356    print apitools_base_cli.FormatOutput(result)
357
358
359class ManagedZonesGet(apitools_base_cli.NewCmd):
360  """Command wrapping managedZones.Get."""
361
362  usage = """managedZones_get <project> <managedZone>"""
363
364  def __init__(self, name, fv):
365    super(ManagedZonesGet, self).__init__(name, fv)
366
367  def RunWithArgs(self, project, managedZone):
368    """Fetch the representation of an existing ManagedZone.
369
370    Args:
371      project: Identifies the project addressed by this request.
372      managedZone: Identifies the managed zone addressed by this request. Can
373        be the managed zone name or id.
374    """
375    client = GetClientFromFlags()
376    global_params = GetGlobalParamsFromFlags()
377    request = messages.DnsManagedZonesGetRequest(
378        project=project.decode('utf8'),
379        managedZone=managedZone.decode('utf8'),
380        )
381    result = client.managedZones.Get(
382        request, global_params=global_params)
383    print apitools_base_cli.FormatOutput(result)
384
385
386class ManagedZonesList(apitools_base_cli.NewCmd):
387  """Command wrapping managedZones.List."""
388
389  usage = """managedZones_list <project>"""
390
391  def __init__(self, name, fv):
392    super(ManagedZonesList, self).__init__(name, fv)
393    flags.DEFINE_string(
394        'dnsName',
395        None,
396        u'Restricts the list to return only zones with this domain name.',
397        flag_values=fv)
398    flags.DEFINE_integer(
399        'maxResults',
400        None,
401        u'Optional. Maximum number of results to be returned. If unspecified,'
402        u' the server will decide how many results to return.',
403        flag_values=fv)
404    flags.DEFINE_string(
405        'pageToken',
406        None,
407        u'Optional. A tag returned by a previous list request that was '
408        u'truncated. Use this parameter to continue a previous list request.',
409        flag_values=fv)
410
411  def RunWithArgs(self, project):
412    """Enumerate ManagedZones that have been created but not yet deleted.
413
414    Args:
415      project: Identifies the project addressed by this request.
416
417    Flags:
418      dnsName: Restricts the list to return only zones with this domain name.
419      maxResults: Optional. Maximum number of results to be returned. If
420        unspecified, the server will decide how many results to return.
421      pageToken: Optional. A tag returned by a previous list request that was
422        truncated. Use this parameter to continue a previous list request.
423    """
424    client = GetClientFromFlags()
425    global_params = GetGlobalParamsFromFlags()
426    request = messages.DnsManagedZonesListRequest(
427        project=project.decode('utf8'),
428        )
429    if FLAGS['dnsName'].present:
430      request.dnsName = FLAGS.dnsName.decode('utf8')
431    if FLAGS['maxResults'].present:
432      request.maxResults = FLAGS.maxResults
433    if FLAGS['pageToken'].present:
434      request.pageToken = FLAGS.pageToken.decode('utf8')
435    result = client.managedZones.List(
436        request, global_params=global_params)
437    print apitools_base_cli.FormatOutput(result)
438
439
440class ProjectsGet(apitools_base_cli.NewCmd):
441  """Command wrapping projects.Get."""
442
443  usage = """projects_get <project>"""
444
445  def __init__(self, name, fv):
446    super(ProjectsGet, self).__init__(name, fv)
447
448  def RunWithArgs(self, project):
449    """Fetch the representation of an existing Project.
450
451    Args:
452      project: Identifies the project addressed by this request.
453    """
454    client = GetClientFromFlags()
455    global_params = GetGlobalParamsFromFlags()
456    request = messages.DnsProjectsGetRequest(
457        project=project.decode('utf8'),
458        )
459    result = client.projects.Get(
460        request, global_params=global_params)
461    print apitools_base_cli.FormatOutput(result)
462
463
464class ResourceRecordSetsList(apitools_base_cli.NewCmd):
465  """Command wrapping resourceRecordSets.List."""
466
467  usage = """resourceRecordSets_list <project> <managedZone>"""
468
469  def __init__(self, name, fv):
470    super(ResourceRecordSetsList, self).__init__(name, fv)
471    flags.DEFINE_integer(
472        'maxResults',
473        None,
474        u'Optional. Maximum number of results to be returned. If unspecified,'
475        u' the server will decide how many results to return.',
476        flag_values=fv)
477    flags.DEFINE_string(
478        'name',
479        None,
480        u'Restricts the list to return only records with this fully qualified'
481        u' domain name.',
482        flag_values=fv)
483    flags.DEFINE_string(
484        'pageToken',
485        None,
486        u'Optional. A tag returned by a previous list request that was '
487        u'truncated. Use this parameter to continue a previous list request.',
488        flag_values=fv)
489    flags.DEFINE_string(
490        'type',
491        None,
492        u'Restricts the list to return only records of this type. If present,'
493        u' the "name" parameter must also be present.',
494        flag_values=fv)
495
496  def RunWithArgs(self, project, managedZone):
497    """Enumerate ResourceRecordSets that have been created but not yet
498    deleted.
499
500    Args:
501      project: Identifies the project addressed by this request.
502      managedZone: Identifies the managed zone addressed by this request. Can
503        be the managed zone name or id.
504
505    Flags:
506      maxResults: Optional. Maximum number of results to be returned. If
507        unspecified, the server will decide how many results to return.
508      name: Restricts the list to return only records with this fully
509        qualified domain name.
510      pageToken: Optional. A tag returned by a previous list request that was
511        truncated. Use this parameter to continue a previous list request.
512      type: Restricts the list to return only records of this type. If
513        present, the "name" parameter must also be present.
514    """
515    client = GetClientFromFlags()
516    global_params = GetGlobalParamsFromFlags()
517    request = messages.DnsResourceRecordSetsListRequest(
518        project=project.decode('utf8'),
519        managedZone=managedZone.decode('utf8'),
520        )
521    if FLAGS['maxResults'].present:
522      request.maxResults = FLAGS.maxResults
523    if FLAGS['name'].present:
524      request.name = FLAGS.name.decode('utf8')
525    if FLAGS['pageToken'].present:
526      request.pageToken = FLAGS.pageToken.decode('utf8')
527    if FLAGS['type'].present:
528      request.type = FLAGS.type.decode('utf8')
529    result = client.resourceRecordSets.List(
530        request, global_params=global_params)
531    print apitools_base_cli.FormatOutput(result)
532
533
534def main(_):
535  appcommands.AddCmd('pyshell', PyShell)
536  appcommands.AddCmd('changes_create', ChangesCreate)
537  appcommands.AddCmd('changes_get', ChangesGet)
538  appcommands.AddCmd('changes_list', ChangesList)
539  appcommands.AddCmd('managedZones_create', ManagedZonesCreate)
540  appcommands.AddCmd('managedZones_delete', ManagedZonesDelete)
541  appcommands.AddCmd('managedZones_get', ManagedZonesGet)
542  appcommands.AddCmd('managedZones_list', ManagedZonesList)
543  appcommands.AddCmd('projects_get', ProjectsGet)
544  appcommands.AddCmd('resourceRecordSets_list', ResourceRecordSetsList)
545
546  apitools_base_cli.SetupLogger()
547  if hasattr(appcommands, 'SetDefaultCommand'):
548    appcommands.SetDefaultCommand('pyshell')
549
550
551run_main = apitools_base_cli.run_main
552
553if __name__ == '__main__':
554  appcommands.Run()
555