gnt_network.py 12 KB
Newer Older
1 2 3
#
#

4
# Copyright (C) 2011, 2012, 2013 Google Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""IP pool related commands"""

23
# pylint: disable=W0401,W0614
24 25 26
# W0401: Wildcard import ganeti.cli
# W0614: Unused import %s from wildcard import (since we need cli)

27
import textwrap
28
import itertools
29

30 31 32 33
from ganeti.cli import *
from ganeti import constants
from ganeti import opcodes
from ganeti import utils
34
from ganeti import errors
35
from ganeti import objects
36 37 38


#: default list of fields for L{ListNetworks}
39
_LIST_DEF_FIELDS = ["name", "network", "gateway",
40
                    "mac_prefix", "group_list", "tags"]
41 42 43


def _HandleReservedIPs(ips):
44 45 46 47 48 49
  if ips is None:
    return None
  elif not ips:
    return []
  else:
    return utils.UnescapeAndSplit(ips, sep=",")
50

51

52 53 54 55 56 57 58 59 60 61 62 63
def AddNetwork(opts, args):
  """Add a network to the cluster.

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

  """
  (network_name, ) = args

64 65 66 67
  if opts.network is None:
    raise errors.OpPrereqError("The --network option must be given",
                               errors.ECODE_INVAL)

68 69 70 71 72
  if opts.tags is not None:
    tags = opts.tags.split(",")
  else:
    tags = []

73 74 75 76 77 78 79 80 81 82 83
  reserved_ips = _HandleReservedIPs(opts.add_reserved_ips)

  op = opcodes.OpNetworkAdd(network_name=network_name,
                            gateway=opts.gateway,
                            network=opts.network,
                            gateway6=opts.gateway6,
                            network6=opts.network6,
                            mac_prefix=opts.mac_prefix,
                            add_reserved_ips=reserved_ips,
                            conflicts_check=opts.conflicts_check,
                            tags=tags)
84
  SubmitOrSend(op, opts)
85 86


87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
def _GetDefaultGroups(cl, groups):
  """Gets list of groups to operate on.

  If C{groups} doesn't contain groups, a list of all groups in the cluster is
  returned.

  @type cl: L{luxi.Client}
  @type groups: list
  @rtype: list

  """
  if groups:
    return groups

  return list(itertools.chain(*cl.QueryGroups([], ["uuid"], False)))


104
def ConnectNetwork(opts, args):
105 106 107 108
  """Map a network to a node group.

  @param opts: the command line options selected by the user
  @type args: list
109
  @param args: Network, mode, physlink and node groups
110 111 112 113
  @rtype: int
  @return: the desired exit code

  """
114
  cl = GetClient()
115

116 117 118 119
  network = args[0]
  nicparams = objects.FillDict(constants.NICC_DEFAULTS, opts.nicparams)

  groups = _GetDefaultGroups(cl, args[1:])
120

121
  # TODO: Change logic to support "--submit"
122 123 124
  for group in groups:
    op = opcodes.OpNetworkConnect(group_name=group,
                                  network_name=network,
125 126 127
                                  network_mode=nicparams[constants.NIC_MODE],
                                  network_link=nicparams[constants.NIC_LINK],
                                  network_vlan=nicparams[constants.NIC_VLAN],
128
                                  conflicts_check=opts.conflicts_check)
129
    SubmitOpCode(op, opts=opts, cl=cl)
130 131


132
def DisconnectNetwork(opts, args):
133 134 135 136
  """Unmap a network from a node group.

  @param opts: the command line options selected by the user
  @type args: list
137
  @param args: Network and node groups
138 139 140 141
  @rtype: int
  @return: the desired exit code

  """
142 143
  cl = GetClient()

144 145
  (network, ) = args[:1]
  groups = _GetDefaultGroups(cl, args[1:])
146

147
  # TODO: Change logic to support "--submit"
148 149
  for group in groups:
    op = opcodes.OpNetworkDisconnect(group_name=group,
150
                                     network_name=network)
151
    SubmitOpCode(op, opts=opts, cl=cl)
152 153 154 155 156 157 158 159 160 161 162 163 164 165


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

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

  """
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
  fmtoverride = {
166
    "group_list":
167 168 169
      (lambda data:
        utils.CommaJoin("%s (%s, %s, %s)" % (name, mode, link, vlan)
                        for (name, mode, link, vlan) in data),
170
       False),
171
    "inst_list": (",".join, False),
172
    "tags": (",".join, False),
173
    }
174

175
  cl = GetClient(query=True)
176 177
  return GenericList(constants.QR_NETWORK, desired_fields, args, None,
                     opts.separator, not opts.no_headers,
178 179
                     verbose=opts.verbose, format_override=fmtoverride,
                     cl=cl)
180 181 182 183 184 185 186 187 188 189 190 191


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

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

  """
192 193
  cl = GetClient(query=True)

194
  return GenericListFields(constants.QR_NETWORK, args, opts.separator,
195
                           not opts.no_headers, cl=cl)
196 197


198
def ShowNetworkConfig(_, args):
199 200 201 202 203 204 205 206 207 208 209 210 211
  """Show network information.

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

  """
  cl = GetClient()
  result = cl.QueryNetworks(fields=["name", "network", "gateway",
                                    "network6", "gateway6",
212
                                    "mac_prefix",
213 214
                                    "free_count", "reserved_count",
                                    "map", "group_list", "inst_list",
215 216
                                    "external_reservations",
                                    "serial_no", "uuid"],
217 218 219
                            names=args, use_locking=False)

  for (name, network, gateway, network6, gateway6,
220
       mac_prefix, free_count, reserved_count,
221
       mapping, group_list, instances, ext_res, serial, uuid) in result:
222 223
    size = free_count + reserved_count
    ToStdout("Network name: %s", name)
224 225 226 227 228 229 230 231 232
    ToStdout("UUID: %s", uuid)
    ToStdout("Serial number: %d", serial)
    ToStdout("  Subnet: %s", network)
    ToStdout("  Gateway: %s", gateway)
    ToStdout("  IPv6 Subnet: %s", network6)
    ToStdout("  IPv6 Gateway: %s", gateway6)
    ToStdout("  Mac Prefix: %s", mac_prefix)
    ToStdout("  Size: %d", size)
    ToStdout("  Free: %d (%.2f%%)", free_count,
233
             100 * float(free_count) / float(size))
234
    ToStdout("  Usage map:")
235
    idx = 0
236
    for line in textwrap.wrap(mapping, width=64):
237 238 239 240 241 242
      ToStdout("     %s %s %d", str(idx).rjust(3), line.ljust(64), idx + 63)
      idx += 64
    ToStdout("         (X) used    (.) free")

    if ext_res:
      ToStdout("  externally reserved IPs:")
243
      for line in textwrap.wrap(ext_res, width=64):
244 245 246 247
        ToStdout("    %s" % line)

    if group_list:
      ToStdout("  connected to node groups:")
248 249 250
      for group, nic_mode, nic_link, nic_vlan in group_list:
        ToStdout("    %s (mode:%s link:%s vlan:%s)",
                 group, nic_mode, nic_link, nic_vlan)
251 252 253 254 255
    else:
      ToStdout("  not connected to any node group")

    if instances:
      ToStdout("  used by %d instances:", len(instances))
256
      for name in instances:
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
257
        ((ips, networks), ) = cl.QueryInstances([name],
258 259 260
                                                ["nic.ips", "nic.networks"],
                                                use_locking=False)

261
        l = lambda value: ", ".join(str(idx) + ":" + str(ip)
262
                                    for idx, (ip, net) in enumerate(value)
263
                                      if net == uuid)
264

Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
265
        ToStdout("    %s: %s", name, l(zip(ips, networks)))
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    else:
      ToStdout("  not used by any instances")


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

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

  @rtype: int
  @return: the desired exit code

  """
  # TODO: add "network": opts.network,
  all_changes = {
    "gateway": opts.gateway,
    "add_reserved_ips": _HandleReservedIPs(opts.add_reserved_ips),
    "remove_reserved_ips": _HandleReservedIPs(opts.remove_reserved_ips),
    "mac_prefix": opts.mac_prefix,
    "gateway6": opts.gateway6,
    "network6": opts.network6,
  }

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

295 296
  # pylint: disable=W0142
  op = opcodes.OpNetworkSetParams(network_name=args[0], **all_changes)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

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


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

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

  """
  (network_name,) = args
  op = opcodes.OpNetworkRemove(network_name=network_name, force=opts.force)
314
  SubmitOrSend(op, opts)
315 316 317 318 319


commands = {
  "add": (
    AddNetwork, ARGS_ONE_NETWORK,
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
320
    [DRY_RUN_OPT, NETWORK_OPT, GATEWAY_OPT, ADD_RESERVED_IPS_OPT,
321
     MAC_PREFIX_OPT, NETWORK6_OPT, GATEWAY6_OPT,
322
     NOCONFLICTSCHECK_OPT, TAG_ADD_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    "<network_name>", "Add a new IP network to the cluster"),
  "list": (
    ListNetworks, ARGS_MANY_NETWORKS,
    [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT],
    "[<network_id>...]",
    "Lists the IP networks in the cluster. The available fields can be shown"
    " using the \"list-fields\" command (see the man page for details)."
    " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
  "list-fields": (
    ListNetworkFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
    "Lists all available fields for networks"),
  "info": (
    ShowNetworkConfig, ARGS_MANY_NETWORKS, [],
    "[<network_name>...]", "Show information about the network(s)"),
  "modify": (
    SetNetworkParams, ARGS_ONE_NETWORK,
339 340 341 342
    [DRY_RUN_OPT] + SUBMIT_OPTS +
    [ADD_RESERVED_IPS_OPT,
     REMOVE_RESERVED_IPS_OPT, GATEWAY_OPT, MAC_PREFIX_OPT, NETWORK6_OPT,
     GATEWAY6_OPT, PRIORITY_OPT],
343 344
    "<network_name>", "Alters the parameters of a network"),
  "connect": (
345 346 347
    ConnectNetwork,
    [ArgNetwork(min=1, max=1),
     ArgGroup()],
348
    [NOCONFLICTSCHECK_OPT, PRIORITY_OPT, NIC_PARAMS_OPT],
349
    "<network_name> <mode> <link> [<node_group>...]",
350 351 352
    "Map a given network to the specified node group"
    " with given mode and link (netparams)"),
  "disconnect": (
353 354
    DisconnectNetwork,
    [ArgNetwork(min=1, max=1), ArgGroup()],
355
    [PRIORITY_OPT],
356
    "<network_name> [<node_group>...]",
357 358
    "Unmap a given network from a specified node group"),
  "remove": (
359
    RemoveNetwork, ARGS_ONE_NETWORK,
360
    [FORCE_OPT, DRY_RUN_OPT] + SUBMIT_OPTS + [PRIORITY_OPT],
361 362
    "[--dry-run] <network_id>",
    "Remove an (empty) network from the cluster"),
363 364 365 366 367
  "list-tags": (
    ListTags, ARGS_ONE_NETWORK, [],
    "<network_name>", "List the tags of the given network"),
  "add-tags": (
    AddTags, [ArgNetwork(min=1, max=1), ArgUnknown()],
368
    [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
369 370 371
    "<network_name> tag...", "Add tags to the given network"),
  "remove-tags": (
    RemoveTags, [ArgNetwork(min=1, max=1), ArgUnknown()],
372
    [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
373
    "<network_name> tag...", "Remove tags from given network"),
374 375 376 377
}


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