Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ beb81ea5

History | View | Annotate | Download (11.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2011 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
def AddNetwork(opts, args):
48
  """Add a network to the cluster.
49

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

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

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

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

    
76

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

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

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

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

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

    
107

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

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

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

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

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

    
134

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

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

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

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

    
156

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

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

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

    
170

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

174
  @param opts: the command line options selected by the user
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
                            names=args, use_locking=False)
191

    
192
  for (name, network, gateway, network6, gateway6,
193
       mac_prefix, network_type, free_count, reserved_count,
194
       mapping, group_list, instances, ext_res) in result:
195
    size = free_count + reserved_count
196
    ToStdout("Network name: %s", name)
197
    ToStdout("  subnet: %s", network)
198
    ToStdout("  gateway: %s", gateway)
199
    ToStdout("  subnet6: %s", network6)
200
    ToStdout("  gateway6: %s", gateway6)
201
    ToStdout("  mac prefix: %s", mac_prefix)
202
    ToStdout("  type: %s", network_type)
203
    ToStdout("  size: %d", size)
204
    ToStdout("  free: %d (%.2f%%)", free_count,
205
             100 * float(free_count)/float(size))
206
    ToStdout("  usage map:")
207
    idx = 0
208
    for line in wrap(mapping, width=64):
209
      ToStdout("     %s %s %d", str(idx).rjust(3), line.ljust(64), idx + 63)
210
      idx += 64
211
    ToStdout("         (X) used    (.) free")
212

    
213
    if ext_res:
214
      ToStdout("  externally reserved IPs:")
215
      for line in wrap(ext_res, width=64):
216
        ToStdout("    %s" % line)
217

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

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

    
232
        l = lambda value: ", ".join(str(idx)+":"+str(ip)
233
                                    for idx, (ip, net) in enumerate(value)
234
                                      if net == name)
235

    
236
        ToStdout("    %s : %s", inst, l(zip(ips, networks)))
237
    else:
238
      ToStdout("  not used by any instances")
239

    
240

    
241
def SetNetworkParams(opts, args):
242
  """Modifies an IP address pool's parameters.
243

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

248
  @rtype: int
249
  @return: the desired exit code
250

251
  """
252

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

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

    
268
  # pylint: disable=W0142
269
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
270

    
271
  # TODO: add feedback to user, e.g. list the modifications
272
  SubmitOrSend(op, opts)
273

    
274

    
275
def RemoveNetwork(opts, args):
276
  """Remove an IP address pool from the cluster.
277

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

284
  """
285
  (network_name,) = args
286
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
287
  SubmitOpCode(op, opts=opts)
288

    
289

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

    
345

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