Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_network.py @ 1fa2c40b

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

    
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
                            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})