Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ 3924c9e0

History | View | Annotate | Download (11.8 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

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

    
35

    
36
#: default list of fields for L{ListNetworks}
37
_LIST_DEF_FIELDS = ["name", "network", "gateway",
38
                    "network_type", "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.network is None:
63
    raise errors.OpPrereqError("The --network option must be given",
64
                               errors.ECODE_INVAL)
65

    
66
  if opts.tags is not None:
67
    tags = opts.tags.split(",")
68
  else:
69
    tags = []
70

    
71
  reserved_ips = _HandleReservedIPs(opts.add_reserved_ips)
72

    
73
  op = opcodes.OpNetworkAdd(network_name=network_name,
74
                            gateway=opts.gateway,
75
                            network=opts.network,
76
                            gateway6=opts.gateway6,
77
                            network6=opts.network6,
78
                            mac_prefix=opts.mac_prefix,
79
                            network_type=opts.network_type,
80
                            add_reserved_ips=reserved_ips,
81
                            conflicts_check=opts.conflicts_check,
82
                            tags=tags)
83
  SubmitOrSend(op, opts)
84

    
85

    
86
def MapNetwork(opts, args):
87
  """Map a network to a node group.
88

89
  @param opts: the command line options selected by the user
90
  @type args: list
91
  @param args: a list of length 3 with network, nodegroup, mode, physlink
92
  @rtype: int
93
  @return: the desired exit code
94

95
  """
96
  (network, groups, mode, link) = args
97

    
98
  cl = GetClient()
99

    
100
  # FIXME: This doesn't work with a group named "all"
101
  if groups == "all":
102
    (groups, ) = cl.QueryGroups([], ["name"], False)
103
  else:
104
    groups = [groups]
105

    
106
  # TODO: Change logic to support "--submit"
107
  for group in groups:
108
    op = opcodes.OpNetworkConnect(group_name=group,
109
                                  network_name=network,
110
                                  network_mode=mode,
111
                                  network_link=link,
112
                                  conflicts_check=opts.conflicts_check)
113
    SubmitOpCode(op, opts=opts, cl=cl)
114

    
115

    
116
def UnmapNetwork(opts, args):
117
  """Unmap a network from a node group.
118

119
  @param opts: the command line options selected by the user
120
  @type args: list
121
  @param args: a list of length 3 with network, nodegroup
122
  @rtype: int
123
  @return: the desired exit code
124

125
  """
126
  (network, groups) = args
127

    
128
  cl = GetClient()
129

    
130
  # FIXME: This doesn't work with a group named "all"
131
  if groups == "all":
132
    (groups, ) = cl.QueryGroups([], ["name"], False)
133
  else:
134
    groups = [groups]
135

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

    
143

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

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

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

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

    
168

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

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

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

    
182

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

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

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

    
204
  for (name, network, gateway, network6, gateway6,
205
       mac_prefix, network_type, free_count, reserved_count,
206
       mapping, group_list, instances, ext_res, serial, uuid) in result:
207
    size = free_count + reserved_count
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
    ToStdout("  Type: %s", network_type)
217
    ToStdout("  Size: %d", size)
218
    ToStdout("  Free: %d (%.2f%%)", free_count,
219
             100 * float(free_count) / float(size))
220
    ToStdout("  Usage map:")
221
    idx = 0
222
    for line in textwrap.wrap(mapping, width=64):
223
      ToStdout("     %s %s %d", str(idx).rjust(3), line.ljust(64), idx + 63)
224
      idx += 64
225
    ToStdout("         (X) used    (.) free")
226

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

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

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

    
246
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
247
                                    for idx, (ip, net) in enumerate(value)
248
                                      if net == name)
249

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

    
254

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

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

262
  @rtype: int
263
  @return: the desired exit code
264

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

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

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

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

    
287

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

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

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

    
302

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

    
362

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