Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ b34864e8

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
from ganeti.cli import *
28
from ganeti import constants
29
from ganeti import opcodes
30
from ganeti import utils
31
from ganeti import errors
32
from textwrap import wrap
33

    
34

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

    
39

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

    
48

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

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

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

    
61
  if opts.network is None:
62
    raise errors.OpPrereqError("The --network option must be given",
63
                               errors.ECODE_INVAL)
64

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

    
70
  reserved_ips = _HandleReservedIPs(opts.add_reserved_ips)
71

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

    
84

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

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

94
  """
95
  network = args[0]
96
  groups = args[1]
97
  mode = args[2]
98
  link = args[3]
99

    
100
  # TODO: allow comma separated group names
101
  if groups == "all":
102
    cl = GetClient()
103
    (groups, ) = cl.QueryGroups([], ["name"], False)
104
  else:
105
    groups = [groups]
106

    
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)
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, nodegorup
122
  @rtype: int
123
  @return: the desired exit code
124

125
  """
126
  network = args[0]
127
  groups = args[1]
128

    
129
  #TODO: allow comma separated group names
130
  if groups == "all":
131
    cl = GetClient()
132
    (groups, ) = cl.QueryGroups([], ["name"], False)
133
  else:
134
    groups = [groups]
135

    
136
  for group in groups:
137
    op = opcodes.OpNetworkDisconnect(group_name=group,
138
                                     network_name=network,
139
                                     conflicts_check=opts.conflicts_check)
140
    SubmitOpCode(op, opts=opts)
141

    
142

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

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

152
  """
153
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
154
  fmtoverride = {
155
    "group_list": (",".join, 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 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 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

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

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

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

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

    
284

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

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

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

    
299

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

    
357

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