Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ ee93aa8a

History | View | Annotate | Download (11.7 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 ConnectNetwork(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: Network, mode, physlink and node groups
92
  @rtype: int
93
  @return: the desired exit code
94

95
  """
96
  (network, mode, link) = args[:3]
97
  groups = args[3:]
98

    
99
  cl = GetClient()
100

    
101
  if not groups:
102
    (groups, ) = cl.QueryGroups([], ["uuid"], False)
103

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

    
113

    
114
def DisconnectNetwork(opts, args):
115
  """Unmap a network from a node group.
116

117
  @param opts: the command line options selected by the user
118
  @type args: list
119
  @param args: Network and node groups
120
  @rtype: int
121
  @return: the desired exit code
122

123
  """
124
  (network, ) = args[:1]
125
  groups = args[1:]
126

    
127
  cl = GetClient()
128

    
129
  if not groups:
130
    (groups, ) = cl.QueryGroups([], ["uuid"], False)
131

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

    
139

    
140
def ListNetworks(opts, args):
141
  """List Ip pools and their properties.
142

143
  @param opts: the command line options selected by the user
144
  @type args: list
145
  @param args: networks to list, or empty for all
146
  @rtype: int
147
  @return: the desired exit code
148

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

    
160
  return GenericList(constants.QR_NETWORK, desired_fields, args, None,
161
                     opts.separator, not opts.no_headers,
162
                     verbose=opts.verbose, format_override=fmtoverride)
163

    
164

    
165
def ListNetworkFields(opts, args):
166
  """List network fields.
167

168
  @param opts: the command line options selected by the user
169
  @type args: list
170
  @param args: fields to list, or empty for all
171
  @rtype: int
172
  @return: the desired exit code
173

174
  """
175
  return GenericListFields(constants.QR_NETWORK, args, opts.separator,
176
                           not opts.no_headers)
177

    
178

    
179
def ShowNetworkConfig(_, args):
180
  """Show network information.
181

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

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

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

    
223
    if ext_res:
224
      ToStdout("  externally reserved IPs:")
225
      for line in textwrap.wrap(ext_res, width=64):
226
        ToStdout("    %s" % line)
227

    
228
    if group_list:
229
      ToStdout("  connected to node groups:")
230
      for group in group_list:
231
        ToStdout("    %s", group)
232
    else:
233
      ToStdout("  not connected to any node group")
234

    
235
    if instances:
236
      ToStdout("  used by %d instances:", len(instances))
237
      for inst in instances:
238
        ((ips, networks), ) = cl.QueryInstances([inst],
239
                                                ["nic.ips", "nic.networks"],
240
                                                use_locking=False)
241

    
242
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
243
                                    for idx, (ip, net) in enumerate(value)
244
                                      if net == name)
245

    
246
        ToStdout("    %s : %s", inst, l(zip(ips, networks)))
247
    else:
248
      ToStdout("  not used by any instances")
249

    
250

    
251
def SetNetworkParams(opts, args):
252
  """Modifies an IP address pool's parameters.
253

254
  @param opts: the command line options selected by the user
255
  @type args: list
256
  @param args: should contain only one element, the node group name
257

258
  @rtype: int
259
  @return: the desired exit code
260

261
  """
262
  # TODO: add "network": opts.network,
263
  all_changes = {
264
    "gateway": opts.gateway,
265
    "add_reserved_ips": _HandleReservedIPs(opts.add_reserved_ips),
266
    "remove_reserved_ips": _HandleReservedIPs(opts.remove_reserved_ips),
267
    "mac_prefix": opts.mac_prefix,
268
    "network_type": opts.network_type,
269
    "gateway6": opts.gateway6,
270
    "network6": opts.network6,
271
  }
272

    
273
  if all_changes.values().count(None) == len(all_changes):
274
    ToStderr("Please give at least one of the parameters.")
275
    return 1
276

    
277
  # pylint: disable=W0142
278
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
279

    
280
  # TODO: add feedback to user, e.g. list the modifications
281
  SubmitOrSend(op, opts)
282

    
283

    
284
def RemoveNetwork(opts, args):
285
  """Remove an IP address pool from the cluster.
286

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

293
  """
294
  (network_name,) = args
295
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
296
  SubmitOrSend(op, opts)
297

    
298

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

    
359

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