Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ 53195377

History | View | Annotate | Download (11.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2011, 2012, 2013 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21
"""IP pool related commands"""
22

    
23
# pylint: disable=W0401,W0614
24
# W0401: Wildcard import ganeti.cli
25
# W0614: Unused import %s from wildcard import (since we need cli)
26

    
27
import textwrap
28
import itertools
29

    
30
from ganeti.cli import *
31
from ganeti import constants
32
from ganeti import opcodes
33
from ganeti import utils
34
from ganeti import errors
35

    
36

    
37
#: default list of fields for L{ListNetworks}
38
_LIST_DEF_FIELDS = ["name", "network", "gateway",
39
                    "mac_prefix", "group_list", "tags"]
40

    
41

    
42
def _HandleReservedIPs(ips):
43
  if ips is None:
44
    return None
45
  elif not ips:
46
    return []
47
  else:
48
    return utils.UnescapeAndSplit(ips, sep=",")
49

    
50

    
51
def AddNetwork(opts, args):
52
  """Add a network to the cluster.
53

54
  @param opts: the command line options selected by the user
55
  @type args: list
56
  @param args: a list of length 1 with the network name to create
57
  @rtype: int
58
  @return: the desired exit code
59

60
  """
61
  (network_name, ) = args
62

    
63
  if opts.tags is not None:
64
    tags = opts.tags.split(",")
65
  else:
66
    tags = []
67

    
68
  reserved_ips = _HandleReservedIPs(opts.add_reserved_ips)
69

    
70
  op = opcodes.OpNetworkAdd(network_name=network_name,
71
                            gateway=opts.gateway,
72
                            network=opts.network,
73
                            gateway6=opts.gateway6,
74
                            network6=opts.network6,
75
                            mac_prefix=opts.mac_prefix,
76
                            add_reserved_ips=reserved_ips,
77
                            conflicts_check=opts.conflicts_check,
78
                            tags=tags)
79
  SubmitOrSend(op, opts)
80

    
81

    
82
def _GetDefaultGroups(cl, groups):
83
  """Gets list of groups to operate on.
84

85
  If C{groups} doesn't contain groups, a list of all groups in the cluster is
86
  returned.
87

88
  @type cl: L{luxi.Client}
89
  @type groups: list
90
  @rtype: list
91

92
  """
93
  if groups:
94
    return groups
95

    
96
  return list(itertools.chain(*cl.QueryGroups([], ["uuid"], False)))
97

    
98

    
99
def ConnectNetwork(opts, args):
100
  """Map a network to a node group.
101

102
  @param opts: the command line options selected by the user
103
  @type args: list
104
  @param args: Network, mode, physlink and node groups
105
  @rtype: int
106
  @return: the desired exit code
107

108
  """
109
  cl = GetClient()
110

    
111
  (network, mode, link) = args[:3]
112
  groups = _GetDefaultGroups(cl, args[3:])
113

    
114
  # TODO: Change logic to support "--submit"
115
  for group in groups:
116
    op = opcodes.OpNetworkConnect(group_name=group,
117
                                  network_name=network,
118
                                  network_mode=mode,
119
                                  network_link=link,
120
                                  conflicts_check=opts.conflicts_check)
121
    SubmitOpCode(op, opts=opts, cl=cl)
122

    
123

    
124
def DisconnectNetwork(opts, args):
125
  """Unmap a network from a node group.
126

127
  @param opts: the command line options selected by the user
128
  @type args: list
129
  @param args: Network and node groups
130
  @rtype: int
131
  @return: the desired exit code
132

133
  """
134
  cl = GetClient()
135

    
136
  (network, ) = args[:1]
137
  groups = _GetDefaultGroups(cl, args[1:])
138

    
139
  # TODO: Change logic to support "--submit"
140
  for group in groups:
141
    op = opcodes.OpNetworkDisconnect(group_name=group,
142
                                     network_name=network)
143
    SubmitOpCode(op, opts=opts, cl=cl)
144

    
145

    
146
def ListNetworks(opts, args):
147
  """List Ip pools and their properties.
148

149
  @param opts: the command line options selected by the user
150
  @type args: list
151
  @param args: networks to list, or empty for all
152
  @rtype: int
153
  @return: the desired exit code
154

155
  """
156
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
157
  fmtoverride = {
158
    "group_list":
159
      (lambda data: utils.CommaJoin("%s (%s, %s)" % (name, mode, link)
160
                                    for (name, mode, link) in data),
161
       False),
162
    "inst_list": (",".join, False),
163
    "tags": (",".join, False),
164
    }
165

    
166
  cl = GetClient(query=True)
167
  return GenericList(constants.QR_NETWORK, desired_fields, args, None,
168
                     opts.separator, not opts.no_headers,
169
                     verbose=opts.verbose, format_override=fmtoverride,
170
                     cl=cl)
171

    
172

    
173
def ListNetworkFields(opts, args):
174
  """List network fields.
175

176
  @param opts: the command line options selected by the user
177
  @type args: list
178
  @param args: fields to list, or empty for all
179
  @rtype: int
180
  @return: the desired exit code
181

182
  """
183
  cl = GetClient(query=True)
184

    
185
  return GenericListFields(constants.QR_NETWORK, args, opts.separator,
186
                           not opts.no_headers, cl=cl)
187

    
188

    
189
def ShowNetworkConfig(_, args):
190
  """Show network information.
191

192
  @type args: list
193
  @param args: should either be an empty list, in which case
194
      we show information about all nodes, or should contain
195
      a list of networks (names or UUIDs) to be queried for information
196
  @rtype: int
197
  @return: the desired exit code
198

199
  """
200
  cl = GetClient()
201
  result = cl.QueryNetworks(fields=["name", "network", "gateway",
202
                                    "network6", "gateway6",
203
                                    "mac_prefix",
204
                                    "free_count", "reserved_count",
205
                                    "map", "group_list", "inst_list",
206
                                    "external_reservations",
207
                                    "serial_no", "uuid"],
208
                            names=args, use_locking=False)
209

    
210
  for (name, network, gateway, network6, gateway6,
211
       mac_prefix, free_count, reserved_count,
212
       mapping, group_list, instances, ext_res, serial, uuid) in result:
213
    pool = free_count or reserved_count or mapping or reserved_count
214
    ToStdout("Network name: %s", name)
215
    ToStdout("UUID: %s", uuid)
216
    ToStdout("Serial number: %d", serial)
217
    ToStdout("  Subnet: %s", network)
218
    ToStdout("  Gateway: %s", gateway)
219
    ToStdout("  IPv6 Subnet: %s", network6)
220
    ToStdout("  IPv6 Gateway: %s", gateway6)
221
    ToStdout("  Mac Prefix: %s", mac_prefix)
222
    if pool:
223
      size = free_count + reserved_count
224
      ToStdout("  Size: %d", size)
225
      ToStdout("  Free: %d (%.2f%%)", free_count,
226
               100 * float(free_count) / float(size))
227
      ToStdout("  Usage map:")
228
      idx = 0
229
      for line in textwrap.wrap(mapping, width=64):
230
        ToStdout("     %s %s %d", str(idx).rjust(3), line.ljust(64), idx + 63)
231
        idx += 64
232
      ToStdout("         (X) used    (.) free")
233

    
234
      if ext_res:
235
        ToStdout("  externally reserved IPs:")
236
        for line in textwrap.wrap(ext_res, width=64):
237
          ToStdout("    %s" % line)
238

    
239
    if group_list:
240
      ToStdout("  connected to node groups:")
241
      for group in group_list:
242
        ToStdout("    %s", group)
243
    else:
244
      ToStdout("  not connected to any node group")
245

    
246
    if instances:
247
      ToStdout("  used by %d instances:", len(instances))
248
      for inst in instances:
249
        ((ips, networks), ) = cl.QueryInstances([inst],
250
                                                ["nic.ips", "nic.networks"],
251
                                                use_locking=False)
252

    
253
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
254
                                    for idx, (ip, net) in enumerate(value)
255
                                      if net == uuid)
256

    
257
        ToStdout("    %s : %s", inst, l(zip(ips, networks)))
258
    else:
259
      ToStdout("  not used by any instances")
260

    
261

    
262
def SetNetworkParams(opts, args):
263
  """Modifies an IP address pool's parameters.
264

265
  @param opts: the command line options selected by the user
266
  @type args: list
267
  @param args: should contain only one element, the node group name
268

269
  @rtype: int
270
  @return: the desired exit code
271

272
  """
273
  # TODO: add "network": opts.network,
274
  all_changes = {
275
    "gateway": opts.gateway,
276
    "add_reserved_ips": _HandleReservedIPs(opts.add_reserved_ips),
277
    "remove_reserved_ips": _HandleReservedIPs(opts.remove_reserved_ips),
278
    "mac_prefix": opts.mac_prefix,
279
    "gateway6": opts.gateway6,
280
    "network6": opts.network6,
281
  }
282

    
283
  if all_changes.values().count(None) == len(all_changes):
284
    ToStderr("Please give at least one of the parameters.")
285
    return 1
286

    
287
  # pylint: disable=W0142
288
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
289

    
290
  # TODO: add feedback to user, e.g. list the modifications
291
  SubmitOrSend(op, opts)
292

    
293

    
294
def RemoveNetwork(opts, args):
295
  """Remove an IP address pool from the cluster.
296

297
  @param opts: the command line options selected by the user
298
  @type args: list
299
  @param args: a list of length 1 with the id of the IP address pool to remove
300
  @rtype: int
301
  @return: the desired exit code
302

303
  """
304
  (network_name,) = args
305
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
306
  SubmitOrSend(op, opts)
307

    
308

    
309
commands = {
310
  "add": (
311
    AddNetwork, ARGS_ONE_NETWORK,
312
    [DRY_RUN_OPT, NETWORK_OPT, GATEWAY_OPT, ADD_RESERVED_IPS_OPT,
313
     MAC_PREFIX_OPT, NETWORK6_OPT, GATEWAY6_OPT,
314
     NOCONFLICTSCHECK_OPT, TAG_ADD_OPT, PRIORITY_OPT, SUBMIT_OPT],
315
    "<network_name>", "Add a new IP network to the cluster"),
316
  "list": (
317
    ListNetworks, ARGS_MANY_NETWORKS,
318
    [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT],
319
    "[<network_id>...]",
320
    "Lists the IP networks in the cluster. The available fields can be shown"
321
    " using the \"list-fields\" command (see the man page for details)."
322
    " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
323
  "list-fields": (
324
    ListNetworkFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
325
    "Lists all available fields for networks"),
326
  "info": (
327
    ShowNetworkConfig, ARGS_MANY_NETWORKS, [],
328
    "[<network_name>...]", "Show information about the network(s)"),
329
  "modify": (
330
    SetNetworkParams, ARGS_ONE_NETWORK,
331
    [DRY_RUN_OPT, SUBMIT_OPT, ADD_RESERVED_IPS_OPT, REMOVE_RESERVED_IPS_OPT,
332
     GATEWAY_OPT, MAC_PREFIX_OPT, NETWORK6_OPT, GATEWAY6_OPT,
333
     PRIORITY_OPT],
334
    "<network_name>", "Alters the parameters of a network"),
335
  "connect": (
336
    ConnectNetwork,
337
    [ArgNetwork(min=1, max=1),
338
     ArgChoice(min=1, max=1, choices=constants.NIC_VALID_MODES),
339
     ArgUnknown(min=1, max=1),
340
     ArgGroup()],
341
    [NOCONFLICTSCHECK_OPT, PRIORITY_OPT],
342
    "<network_name> <mode> <link> [<node_group>...]",
343
    "Map a given network to the specified node group"
344
    " with given mode and link (netparams)"),
345
  "disconnect": (
346
    DisconnectNetwork,
347
    [ArgNetwork(min=1, max=1), ArgGroup()],
348
    [PRIORITY_OPT],
349
    "<network_name> [<node_group>...]",
350
    "Unmap a given network from a specified node group"),
351
  "remove": (
352
    RemoveNetwork, ARGS_ONE_NETWORK,
353
    [FORCE_OPT, DRY_RUN_OPT, SUBMIT_OPT, PRIORITY_OPT],
354
    "[--dry-run] <network_id>",
355
    "Remove an (empty) network from the cluster"),
356
  "list-tags": (
357
    ListTags, ARGS_ONE_NETWORK, [],
358
    "<network_name>", "List the tags of the given network"),
359
  "add-tags": (
360
    AddTags, [ArgNetwork(min=1, max=1), ArgUnknown()],
361
    [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
362
    "<network_name> tag...", "Add tags to the given network"),
363
  "remove-tags": (
364
    RemoveTags, [ArgNetwork(min=1, max=1), ArgUnknown()],
365
    [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
366
    "<network_name> tag...", "Remove tags from given network"),
367
}
368

    
369

    
370
def Main():
371
  return GenericMain(commands, override={"tag_type": constants.TAG_NETWORK})