Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ 9675661c

History | View | Annotate | Download (11.2 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 textwrap import wrap
32

    
33

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

    
38

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

    
47

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

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

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

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

    
65
  op = opcodes.OpNetworkAdd(
66
                    network_name=network_name,
67
                    gateway=opts.gateway,
68
                    network=opts.network,
69
                    gateway6=opts.gateway6,
70
                    network6=opts.network6,
71
                    mac_prefix=opts.mac_prefix,
72
                    network_type=opts.network_type,
73
                    add_reserved_ips=_HandleReservedIPs(opts.add_reserved_ips),
74
                    tags=tags)
75
  SubmitOpCode(op, opts=opts)
76

    
77

    
78
def MapNetwork(opts, args):
79
  """Map a network to a node group.
80

81
  @param opts: the command line options selected by the user
82
  @type args: list
83
  @param args: a list of length 3 with network, nodegroup, mode, physlink
84
  @rtype: int
85
  @return: the desired exit code
86

87
  """
88
  network = args[0]
89
  groups = args[1]
90
  mode = args[2]
91
  link = args[3]
92

    
93
  # TODO: allow comma separated group names
94
  if groups == "all":
95
    cl = GetClient()
96
    (groups, ) = cl.QueryGroups([], ["name"], False)
97
  else:
98
    groups = [groups]
99

    
100
  for group in groups:
101
    op = opcodes.OpNetworkConnect(group_name=group,
102
                                  network_name=network,
103
                                  network_mode=mode,
104
                                  network_link=link,
105
                                  conflicts_check=opts.conflicts_check)
106
    SubmitOpCode(op, opts=opts)
107

    
108

    
109
def UnmapNetwork(opts, args):
110
  """Unmap a network from a node group.
111

112
  @param opts: the command line options selected by the user
113
  @type args: list
114
  @param args: a list of length 3 with network, nodegorup
115
  @rtype: int
116
  @return: the desired exit code
117

118
  """
119
  network = args[0]
120
  groups = args[1]
121

    
122
  #TODO: allow comma separated group names
123
  if groups == "all":
124
    cl = GetClient()
125
    (groups, ) = cl.QueryGroups([], ["name"], False)
126
  else:
127
    groups = [groups]
128

    
129
  for group in groups:
130
    op = opcodes.OpNetworkDisconnect(group_name=group,
131
                                     network_name=network,
132
                                     conflicts_check=opts.conflicts_check)
133
    SubmitOpCode(op, opts=opts)
134

    
135

    
136
def ListNetworks(opts, args):
137
  """List Ip pools and their properties.
138

139
  @param opts: the command line options selected by the user
140
  @type args: list
141
  @param args: networks to list, or empty for all
142
  @rtype: int
143
  @return: the desired exit code
144

145
  """
146
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
147
  fmtoverride = {
148
    "group_list": (",".join, False),
149
    "inst_list": (",".join, False),
150
    "tags": (",".join, False),
151
  }
152

    
153
  return GenericList(constants.QR_NETWORK, desired_fields, args, None,
154
                     opts.separator, not opts.no_headers,
155
                     verbose=opts.verbose, format_override=fmtoverride)
156

    
157

    
158
def ListNetworkFields(opts, args):
159
  """List network fields.
160

161
  @param opts: the command line options selected by the user
162
  @type args: list
163
  @param args: fields to list, or empty for all
164
  @rtype: int
165
  @return: the desired exit code
166

167
  """
168
  return GenericListFields(constants.QR_NETWORK, args, opts.separator,
169
                           not opts.no_headers)
170

    
171

    
172
def ShowNetworkConfig(_, args):
173
  """Show network information.
174

175
  @type args: list
176
  @param args: should either be an empty list, in which case
177
      we show information about all nodes, or should contain
178
      a list of networks (names or UUIDs) to be queried for information
179
  @rtype: int
180
  @return: the desired exit code
181

182
  """
183
  cl = GetClient()
184
  result = cl.QueryNetworks(fields=["name", "network", "gateway",
185
                                    "network6", "gateway6",
186
                                    "mac_prefix", "network_type",
187
                                    "free_count", "reserved_count",
188
                                    "map", "group_list", "inst_list",
189
                                    "external_reservations",
190
                                    "serial_no", "uuid"],
191
                            names=args, use_locking=False)
192

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

    
216
    if ext_res:
217
      ToStdout("  externally reserved IPs:")
218
      for line in wrap(ext_res, width=64):
219
        ToStdout("    %s" % line)
220

    
221
    if group_list:
222
      ToStdout("  connected to node groups:")
223
      for group in group_list:
224
        ToStdout("    %s", group)
225
    else:
226
      ToStdout("  not connected to any node group")
227

    
228
    if instances:
229
      ToStdout("  used by %d instances:", len(instances))
230
      for inst in instances:
231
        ((ips, networks), ) = cl.QueryInstances([inst],
232
                                                ["nic.ips", "nic.networks"],
233
                                                use_locking=False)
234

    
235
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
236
                                    for idx, (ip, net) in enumerate(value)
237
                                      if net == name)
238

    
239
        ToStdout("    %s : %s", inst, l(zip(ips, networks)))
240
    else:
241
      ToStdout("  not used by any instances")
242

    
243

    
244
def SetNetworkParams(opts, args):
245
  """Modifies an IP address pool's parameters.
246

247
  @param opts: the command line options selected by the user
248
  @type args: list
249
  @param args: should contain only one element, the node group name
250

251
  @rtype: int
252
  @return: the desired exit code
253

254
  """
255

    
256
  # TODO: add "network": opts.network,
257
  all_changes = {
258
    "gateway": opts.gateway,
259
    "add_reserved_ips": _HandleReservedIPs(opts.add_reserved_ips),
260
    "remove_reserved_ips": _HandleReservedIPs(opts.remove_reserved_ips),
261
    "mac_prefix": opts.mac_prefix,
262
    "network_type": opts.network_type,
263
    "gateway6": opts.gateway6,
264
    "network6": opts.network6,
265
  }
266

    
267
  if all_changes.values().count(None) == len(all_changes):
268
    ToStderr("Please give at least one of the parameters.")
269
    return 1
270

    
271
  # pylint: disable=W0142
272
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
273

    
274
  # TODO: add feedback to user, e.g. list the modifications
275
  SubmitOrSend(op, opts)
276

    
277

    
278
def RemoveNetwork(opts, args):
279
  """Remove an IP address pool from the cluster.
280

281
  @param opts: the command line options selected by the user
282
  @type args: list
283
  @param args: a list of length 1 with the id of the IP address pool to remove
284
  @rtype: int
285
  @return: the desired exit code
286

287
  """
288
  (network_name,) = args
289
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
290
  SubmitOpCode(op, opts=opts)
291

    
292

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

    
348

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