Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ 6a2c20f2

History | View | Annotate | Download (11.5 kB)

1
#
2
#
3

    
4
# Copyright (C) 2011, 2012 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

    
35

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

    
40

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

    
49

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

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

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

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

    
67
  reserved_ips = _HandleReservedIPs(opts.add_reserved_ips)
68

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

    
80

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

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

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

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

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

    
97

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

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

107
  """
108
  cl = GetClient()
109

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

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

    
122

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

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

132
  """
133
  cl = GetClient()
134

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

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

    
144

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

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

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

    
165
  return GenericList(constants.QR_NETWORK, desired_fields, args, None,
166
                     opts.separator, not opts.no_headers,
167
                     verbose=opts.verbose, format_override=fmtoverride)
168

    
169

    
170
def ListNetworkFields(opts, args):
171
  """List network fields.
172

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

179
  """
180
  return GenericListFields(constants.QR_NETWORK, args, opts.separator,
181
                           not opts.no_headers)
182

    
183

    
184
def ShowNetworkConfig(_, args):
185
  """Show network information.
186

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

194
  """
195
  cl = GetClient()
196
  result = cl.QueryNetworks(fields=["name", "network", "gateway",
197
                                    "network6", "gateway6",
198
                                    "mac_prefix",
199
                                    "free_count", "reserved_count",
200
                                    "map", "group_list", "inst_list",
201
                                    "external_reservations",
202
                                    "serial_no", "uuid"],
203
                            names=args, use_locking=False)
204

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

    
229
      if ext_res:
230
        ToStdout("  externally reserved IPs:")
231
        for line in textwrap.wrap(ext_res, width=64):
232
          ToStdout("    %s" % line)
233

    
234
    if group_list:
235
      ToStdout("  connected to node groups:")
236
      for group in group_list:
237
        ToStdout("    %s", group)
238
    else:
239
      ToStdout("  not connected to any node group")
240

    
241
    if instances:
242
      ToStdout("  used by %d instances:", len(instances))
243
      for inst in instances:
244
        ((ips, networks), ) = cl.QueryInstances([inst],
245
                                                ["nic.ips", "nic.networks"],
246
                                                use_locking=False)
247

    
248
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
249
                                    for idx, (ip, net) in enumerate(value)
250
                                      if net == uuid)
251

    
252
        ToStdout("    %s : %s", inst, l(zip(ips, networks)))
253
    else:
254
      ToStdout("  not used by any instances")
255

    
256

    
257
def SetNetworkParams(opts, args):
258
  """Modifies an IP address pool's parameters.
259

260
  @param opts: the command line options selected by the user
261
  @type args: list
262
  @param args: should contain only one element, the node group name
263

264
  @rtype: int
265
  @return: the desired exit code
266

267
  """
268
  # TODO: add "network": opts.network,
269
  all_changes = {
270
    "gateway": opts.gateway,
271
    "add_reserved_ips": _HandleReservedIPs(opts.add_reserved_ips),
272
    "remove_reserved_ips": _HandleReservedIPs(opts.remove_reserved_ips),
273
    "mac_prefix": opts.mac_prefix,
274
    "gateway6": opts.gateway6,
275
    "network6": opts.network6,
276
  }
277

    
278
  if all_changes.values().count(None) == len(all_changes):
279
    ToStderr("Please give at least one of the parameters.")
280
    return 1
281

    
282
  # pylint: disable=W0142
283
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
284

    
285
  # TODO: add feedback to user, e.g. list the modifications
286
  SubmitOrSend(op, opts)
287

    
288

    
289
def RemoveNetwork(opts, args):
290
  """Remove an IP address pool from the cluster.
291

292
  @param opts: the command line options selected by the user
293
  @type args: list
294
  @param args: a list of length 1 with the id of the IP address pool to remove
295
  @rtype: int
296
  @return: the desired exit code
297

298
  """
299
  (network_name,) = args
300
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
301
  SubmitOrSend(op, opts)
302

    
303

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

    
364

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