Revision beb81ea5

b/lib/client/gnt_network.py
20 20

  
21 21
"""IP pool related commands"""
22 22

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

  
......
68 68
                            network6=opts.network6,
69 69
                            mac_prefix=opts.mac_prefix,
70 70
                            network_type=opts.network_type,
71
                            add_reserved_ips=_HandleReservedIPs(opts.add_reserved_ips),
71
                            add_reserved_ips=\
72
                              _HandleReservedIPs(opts.add_reserved_ips),
72 73
                            tags=tags)
73 74
  SubmitOpCode(op, opts=opts)
74 75

  
......
167 168
                           not opts.no_headers)
168 169

  
169 170

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

  
173 174
  @param opts: the command line options selected by the user
......
190 191

  
191 192
  for (name, network, gateway, network6, gateway6,
192 193
       mac_prefix, network_type, free_count, reserved_count,
193
       map, group_list, instances, ext_res) in result:
194
       mapping, group_list, instances, ext_res) in result:
194 195
    size = free_count + reserved_count
195 196
    ToStdout("Network name: %s", name)
196 197
    ToStdout("  subnet: %s", network)
......
204 205
             100 * float(free_count)/float(size))
205 206
    ToStdout("  usage map:")
206 207
    idx = 0
207
    for line in wrap(map, width=64):
208
    for line in wrap(mapping, width=64):
208 209
      ToStdout("     %s %s %d", str(idx).rjust(3), line.ljust(64), idx + 63)
209 210
      idx += 64
210 211
    ToStdout("         (X) used    (.) free")
......
228 229
                                                ["nic.ips", "nic.networks"],
229 230
                                                use_locking=False)
230 231

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

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

  
......
264 265
    ToStderr("Please give at least one of the parameters.")
265 266
    return 1
266 267

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

  
271 271
  # TODO: add feedback to user, e.g. list the modifications
272 272
  SubmitOrSend(op, opts)
b/lib/cmdlib.py
40 40
import shutil
41 41
import itertools
42 42
import operator
43
import ipaddr
44 43

  
45 44
from ganeti import ssh
46 45
from ganeti import utils
......
1315 1314
  """Wrapper over L{_ExpandItemName} for instance."""
1316 1315
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
1317 1316

  
1318
def _BuildNetworkHookEnv(name, network, gateway, network6, gateway6,
1317

  
1318
def _BuildNetworkHookEnv(name, subnet, gateway, network6, gateway6,
1319 1319
                         network_type, mac_prefix, tags):
1320
  """Builds network related env variables for hooks
1321

  
1322
  This builds the hook environment from individual variables.
1323

  
1324
  @type name: string
1325
  @param name: the name of the network
1326
  @type network: string
1327
  @param network: the ipv4 subnet
1328
  @type gateway: string
1329
  @param gateway: the ipv4 gateway
1330
  @type network6: string
1331
  @param network6: the ipv6 subnet
1332
  @type gateway6: string
1333
  @param gateway6: the ipv6 gateway
1334
  @type network_type: string
1335
  @param network_type: the type of the network
1336
  @type mac_prefix: string
1337
  @param mac_prefix: the mac_prefix
1338
  @type tags: list
1339
  @param tags: the tags of the network
1340

  
1341
  """
1320 1342
  env = dict()
1321 1343
  if name:
1322 1344
    env["NETWORK_NAME"] = name
1323
  if network:
1324
    env["NETWORK_SUBNET"] = network
1345
  if subnet:
1346
    env["NETWORK_SUBNET"] = subnet
1325 1347
  if gateway:
1326 1348
    env["NETWORK_GATEWAY"] = gateway
1327 1349
  if network6:
......
1338 1360
  return env
1339 1361

  
1340 1362

  
1341
def _BuildNetworkHookEnvByObject(lu, network):
1363
def _BuildNetworkHookEnvByObject(net):
1364
  """Builds network related env varliables for hooks
1365

  
1366
  @type lu: L{objects.LogicalUnit}
1367
  @param lu: the corresponding LU
1368
  @type network: L{objects.Network}
1369
  @param network: the network object
1370

  
1371
  """
1342 1372
  args = {
1343
    "name": network.name,
1344
    "network": network.network,
1345
    "gateway": network.gateway,
1346
    "network6": network.network6,
1347
    "gateway6": network.gateway6,
1348
    "network_type": network.network_type,
1349
    "mac_prefix": network.mac_prefix,
1350
    "tags" : network.tags,
1373
    "name": net.name,
1374
    "subnet": net.network,
1375
    "gateway": net.gateway,
1376
    "network6": net.network6,
1377
    "gateway6": net.gateway6,
1378
    "network_type": net.network_type,
1379
    "mac_prefix": net.mac_prefix,
1380
    "tags": net.tags,
1351 1381
  }
1352
  return _BuildNetworkHookEnv(**args)
1382

  
1383
  return _BuildNetworkHookEnv(**args) # pylint: disable=W0142
1353 1384

  
1354 1385

  
1355 1386
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
......
1411 1442
  }
1412 1443
  if nics:
1413 1444
    nic_count = len(nics)
1414
    for idx, (ip, mac, mode, link, network, netinfo) in enumerate(nics):
1445
    for idx, (ip, mac, mode, link, net, netinfo) in enumerate(nics):
1415 1446
      if ip is None:
1416 1447
        ip = ""
1417 1448
      env["INSTANCE_NIC%d_IP" % idx] = ip
......
1419 1450
      env["INSTANCE_NIC%d_MODE" % idx] = mode
1420 1451
      env["INSTANCE_NIC%d_LINK" % idx] = link
1421 1452
      if network:
1422
        env["INSTANCE_NIC%d_NETWORK" % idx] = network
1453
        env["INSTANCE_NIC%d_NETWORK" % idx] = net
1423 1454
        if netinfo:
1424 1455
          nobj = objects.Network.FromDict(netinfo)
1425 1456
          if nobj.network:
......
1464 1495

  
1465 1496
  return env
1466 1497

  
1498

  
1467 1499
def _NICToTuple(lu, nic):
1468 1500
  """Build a tupple of nic information.
1469 1501

  
......
1473 1505
  @param nic: nic to convert to hooks tuple
1474 1506

  
1475 1507
  """
1476
  cluster = lu.cfg.GetClusterInfo()
1477 1508
  ip = nic.ip
1478 1509
  mac = nic.mac
1510
  cluster = lu.cfg.GetClusterInfo()
1479 1511
  filled_params = cluster.SimpleFillNIC(nic.nicparams)
1480 1512
  mode = filled_params[constants.NIC_MODE]
1481 1513
  link = filled_params[constants.NIC_LINK]
1482
  network = nic.network
1514
  net = nic.network
1483 1515
  netinfo = None
1484
  if network:
1485
    net_uuid = lu.cfg.LookupNetwork(network)
1516
  if net:
1517
    net_uuid = lu.cfg.LookupNetwork(net)
1486 1518
    if net_uuid:
1487 1519
      nobj = lu.cfg.GetNetwork(net_uuid)
1488 1520
      netinfo = objects.Network.ToDict(nobj)
1489
  return (ip, mac, mode, link, network, netinfo)
1521
  return (ip, mac, mode, link, net, netinfo)
1522

  
1490 1523

  
1491 1524
def _NICListToTuple(lu, nics):
1492 1525
  """Build a list of nic information tuples.
......
1501 1534

  
1502 1535
  """
1503 1536
  hooks_nics = []
1504
  cluster = lu.cfg.GetClusterInfo()
1505 1537
  for nic in nics:
1506 1538
    hooks_nics.append(_NICToTuple(lu, nic))
1507 1539
  return hooks_nics
1508 1540

  
1541

  
1509 1542
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1510 1543
  """Builds instance related env variables for hooks from an object.
1511 1544

  
......
9476 9509

  
9477 9510
  """
9478 9511
  nics = []
9479
  for idx, nic in enumerate(op.nics):
9512
  for nic in op.nics:
9480 9513
    nic_mode_req = nic.get(constants.INIC_MODE, None)
9481 9514
    nic_mode = nic_mode_req
9482 9515
    if nic_mode is None or nic_mode == constants.VALUE_AUTO:
......
10238 10271
                     (idx, netparams.values()))
10239 10272
        nic.nicparams = dict(netparams)
10240 10273
        if nic.ip is not None:
10241
          filled_params = cluster.SimpleFillNIC(nic.nicparams)
10242 10274
          if nic.ip.lower() == constants.NIC_IP_POOL:
10243 10275
            try:
10244 10276
              nic.ip = self.cfg.GenerateIp(net, self.proc.GetECId())
......
12962 12994
                                         errors.ECODE_NOTUNIQUE)
12963 12995
        elif new_ip.lower() == constants.NIC_IP_POOL:
12964 12996
          raise errors.OpPrereqError("ip=pool, but no network found",
12965
                                     ECODEE_INVAL)
12997
                                     errors.ECODE_INVAL)
12966 12998
        else:
12967 12999
          # new net is None
12968 13000
          if self.op.conflicts_check:
......
13228 13260
                                   nic.nicparams, cluster, pnode)
13229 13261
      return None
13230 13262

  
13231
    def _PrepareNicRemove(_, params, private):
13263
    def _PrepareNicRemove(_, params, __):
13232 13264
      ip = params.ip
13233 13265
      net = params.network
13234 13266
      if net is not None and ip is not None:
......
13454 13486
    """
13455 13487
    mac = params[constants.INIC_MAC]
13456 13488
    ip = params.get(constants.INIC_IP, None)
13457
    network = params.get(constants.INIC_NETWORK, None)
13489
    net = params.get(constants.INIC_NETWORK, None)
13458 13490
    #TODO: not private.filled?? can a nic have no nicparams??
13459 13491
    nicparams = private.filled
13460 13492

  
13461
    return (objects.NIC(mac=mac, ip=ip, network=network, nicparams=nicparams), [
13493
    return (objects.NIC(mac=mac, ip=ip, network=net, nicparams=nicparams), [
13462 13494
      ("nic.%d" % idx,
13463 13495
       "add:mac=%s,ip=%s,mode=%s,link=%s,network=%s" %
13464 13496
       (mac, ip, private.filled[constants.NIC_MODE],
13465 13497
       private.filled[constants.NIC_LINK],
13466
       network)),
13498
       net)),
13467 13499
      ])
13468 13500

  
13469 13501
  @staticmethod
......
15571 15603
    """
15572 15604
    args = {
15573 15605
      "name": self.op.network_name,
15574
      "network": self.op.network,
15606
      "subnet": self.op.network,
15575 15607
      "gateway": self.op.gateway,
15576 15608
      "network6": self.op.network6,
15577 15609
      "gateway6": self.op.gateway6,
......
15579 15611
      "network_type": self.op.network_type,
15580 15612
      "tags": self.op.tags,
15581 15613
      }
15582
    return _BuildNetworkHookEnv(**args)
15614
    return _BuildNetworkHookEnv(**args) # pylint: disable=W0142
15583 15615

  
15584 15616
  def Exec(self, feedback_fn):
15585 15617
    """Add the ip pool to the cluster.
......
15662 15694
    # Verify that the network is not conncted.
15663 15695
    node_groups = [group.name
15664 15696
                   for group in self.cfg.GetAllNodeGroupsInfo().values()
15665
                   for network in group.networks.keys()
15666
                   if network == self.network_uuid]
15697
                   for net in group.networks.keys()
15698
                   if net == self.network_uuid]
15667 15699

  
15668 15700
    if node_groups:
15669 15701
      self.LogWarning("Nework '%s' is connected to the following"
......
15779 15811
    """
15780 15812
    args = {
15781 15813
      "name": self.op.network_name,
15782
      "network": self.network.network,
15814
      "subnet": self.network.network,
15783 15815
      "gateway": self.gateway,
15784 15816
      "network6": self.network6,
15785 15817
      "gateway6": self.gateway6,
......
15787 15819
      "network_type": self.network_type,
15788 15820
      "tags": self.tags,
15789 15821
      }
15790
    return _BuildNetworkHookEnv(**args)
15822
    return _BuildNetworkHookEnv(**args) # pylint: disable=W0142
15791 15823

  
15792 15824
  def BuildHooksNodes(self):
15793 15825
    """Build hooks nodes.
......
15892 15924
    do_instances = query.NETQ_INST in self.requested_data
15893 15925
    do_groups = do_instances or (query.NETQ_GROUP in self.requested_data)
15894 15926
    do_stats = query.NETQ_STATS in self.requested_data
15895
    cluster = lu.cfg.GetClusterInfo()
15896 15927

  
15897 15928
    network_to_groups = None
15898 15929
    network_to_instances = None
......
15902 15933
    if do_groups:
15903 15934
      all_groups = lu.cfg.GetAllNodeGroupsInfo()
15904 15935
      network_to_groups = dict((uuid, []) for uuid in self.wanted)
15905
      default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
15906 15936

  
15907 15937
      if do_instances:
15908 15938
        all_instances = lu.cfg.GetAllInstancesInfo()
......
16015 16045
    ret["GROUP_NAME"] = self.group_name
16016 16046
    ret["GROUP_NETWORK_MODE"] = self.network_mode
16017 16047
    ret["GROUP_NETWORK_LINK"] = self.network_link
16018
    ret.update(_BuildNetworkHookEnvByObject(self, self.network))
16048
    ret.update(_BuildNetworkHookEnvByObject(self.network))
16019 16049
    return ret
16020 16050

  
16021 16051
  def BuildHooksNodes(self):
......
16049 16079
      instances = [(instance.name, idx, nic.ip)
16050 16080
                   for instance in groupinstances
16051 16081
                   for idx, nic in enumerate(instance.nics)
16052
                   if (not nic.network and pool._Contains(nic.ip))]
16082
                   if (not nic.network and pool.Contains(nic.ip))]
16053 16083
      if instances:
16054 16084
        self.LogWarning("Following occurences use IPs from network %s"
16055 16085
                        " that is about to connect to nodegroup %s: %s" %
......
16110 16140
  def BuildHooksEnv(self):
16111 16141
    ret = dict()
16112 16142
    ret["GROUP_NAME"] = self.group_name
16113
    ret.update(_BuildNetworkHookEnvByObject(self, self.network))
16143
    ret.update(_BuildNetworkHookEnvByObject(self.network))
16114 16144
    return ret
16115 16145

  
16116 16146
  def BuildHooksNodes(self):
......
16192 16222
  @param node: node name
16193 16223

  
16194 16224
  """
16195
  (conf_net, conf_netparams) = lu.cfg.CheckIPInNodeGroup(ip, node)
16225
  (conf_net, _) = lu.cfg.CheckIPInNodeGroup(ip, node)
16196 16226
  if conf_net is not None:
16197 16227
    raise errors.OpPrereqError("Conflicting IP found:"
16198 16228
                               " %s <> %s." % (ip, conf_net),
b/lib/config.py
162 162

  
163 163
  return result
164 164

  
165
def _GenerateMACSuffix():
166
  """Generate one mac address
167

  
168
  """
169
  byte1 = random.randrange(0, 256)
170
  byte2 = random.randrange(0, 256)
171
  byte3 = random.randrange(0, 256)
172
  suffix = "%02x:%02x:%02x" % (byte1, byte2, byte3)
173
  return suffix
174

  
165 175

  
166 176
class ConfigWriter:
167 177
  """The interface to the cluster configuration.
......
235 245
      return wraps(view_func)(_decorator)
236 246
    return _get_mac_prefix
237 247

  
238
  def _GenerateMACSuffix(self):
239
    """Generate one mac address
240

  
241
    """
242
    byte1 = random.randrange(0, 256)
243
    byte2 = random.randrange(0, 256)
244
    byte3 = random.randrange(0, 256)
245
    suffix = "%02x:%02x:%02x" % (byte1, byte2, byte3)
246
    return suffix
247

  
248 248
  @locking.ssynchronized(_config_lock, shared=1)
249 249
  def GetNdParams(self, node):
250 250
    """Get the node params populated with cluster defaults.
......
299 299

  
300 300
    """
301 301
    existing = self._AllMACs()
302
    gen_mac = self._GenerateMACPrefix(net)(self._GenerateMACSuffix)
302
    gen_mac = self._GenerateMACPrefix(net)(_GenerateMACSuffix)
303 303
    return self._temporary_ids.Generate(existing, gen_mac, ec_id)
304 304

  
305 305
  @locking.ssynchronized(_config_lock, shared=1)
......
343 343
    as reserved.
344 344

  
345 345
    """
346
    nobj = self._UnlockedGetNetwork(net_uuid)
347
    pool = network.AddressPool(nobj)
348 346
    self._temporary_ips.Reserve(ec_id, ('release', address, net_uuid))
349 347

  
350 348
  @locking.ssynchronized(_config_lock, shared=1)
351
  def ReleaseIp(self, network, address, ec_id):
349
  def ReleaseIp(self, net, address, ec_id):
352 350
    """Give a specified IP address back to an IP pool.
353 351

  
354 352
    This is just a wrapper around _UnlockedReleaseIp.
355 353

  
356 354
    """
357
    net_uuid = self._UnlockedLookupNetwork(network)
355
    net_uuid = self._UnlockedLookupNetwork(net)
358 356
    if net_uuid:
359 357
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
360 358

  
......
375 373
        raise errors.ReservationError("Cannot generate IP. Network is full")
376 374
      return ("reserve", ip, net_uuid)
377 375

  
378
    _ ,address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
376
    _, address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
379 377
    return address
380 378

  
381 379
  def _UnlockedReserveIp(self, net_uuid, address, ec_id):
......
2409 2407
    """Get a list of network names
2410 2408

  
2411 2409
    """
2412
    names = [network.name
2413
             for network in self._config_data.networks.values()]
2410
    names = [net.name
2411
             for net in self._config_data.networks.values()]
2414 2412
    return names
2415 2413

  
2416 2414
  def _UnlockedGetNetwork(self, uuid):
......
2568 2566
    for net_uuid in nodegroup_info.networks.keys():
2569 2567
      net_info = self._UnlockedGetNetwork(net_uuid)
2570 2568
      pool = network.AddressPool(net_info)
2571
      if pool._Contains(ip):
2569
      if pool.Contains(ip):
2572 2570
        return (net_info.name, nodegroup_info.networks[net_uuid])
2573 2571

  
2574 2572
    return (None, None)
b/lib/network.py
63 63
      self.reservations = bitarray(self.net.reservations)
64 64
    else:
65 65
      self.reservations = bitarray(self.network.numhosts)
66
      # pylint: disable=E1103
66 67
      self.reservations.setall(False)
67 68

  
68 69
    if self.net.ext_reservations:
69 70
      self.ext_reservations = bitarray(self.net.ext_reservations)
70 71
    else:
71 72
      self.ext_reservations = bitarray(self.network.numhosts)
73
      # pylint: disable=E1103
72 74
      self.ext_reservations.setall(False)
73 75

  
74 76
    assert len(self.reservations) == self.network.numhosts
75 77
    assert len(self.ext_reservations) == self.network.numhosts
76 78

  
77
  def _Contains(self, address):
79
  def Contains(self, address):
78 80
    if address is None:
79 81
      return False
80 82
    addr = ipaddr.IPAddress(address)
......
90 92

  
91 93
    return int(addr) - int(self.network.network)
92 94

  
93
  def _Update(self):
95
  def Update(self):
94 96
    """Write address pools back to the network object"""
97
    # pylint: disable=E1103
95 98
    self.net.ext_reservations = self.ext_reservations.to01()
96 99
    self.net.reservations = self.reservations.to01()
97 100

  
......
101 104
      self.ext_reservations[idx] = value
102 105
    else:
103 106
      self.reservations[idx] = value
104
    self._Update()
107
    self.Update()
105 108

  
106 109
  def _GetSize(self):
107 110
    return 2**(32 - self.network.prefixlen)
......
173 176
    def _iter_free():
174 177
      for idx in self.all_reservations.search("0", 64):
175 178
        yield str(self.network[idx])
176

  
179
    # pylint: disable=E1101
177 180
    return _iter_free().next
178 181

  
179 182
  def GetExternalReservations(self):
......
189 192

  
190 193
    """
191 194
    obj = cls(net)
192
    obj._Update()
195
    obj.Update()
193 196
    for ip in [obj.network[0], obj.network[-1]]:
194 197
      obj.Reserve(ip, external=True)
195 198
    if obj.net.gateway is not None:
b/lib/query.py
2494 2494

  
2495 2495
_NETWORK_STATS_FIELDS = {
2496 2496
  "free_count": ("FreeCount", QFT_NUMBER, 0, "How many addresses are free"),
2497
  "reserved_count": ("ReservedCount", QFT_NUMBER, 0, "How many addresses are reserved"),
2497
  "reserved_count": ("ReservedCount", QFT_NUMBER, 0,
2498
                     "How many addresses are reserved"),
2498 2499
  "map": ("Map", QFT_TEXT, 0, "The actual mapping"),
2499
  "external_reservations": ("ExternalReservations", QFT_TEXT, 0, "The external reservations"),
2500
  "external_reservations": ("ExternalReservations", QFT_TEXT, 0,
2501
                            "The external reservations"),
2500 2502
  }
2501 2503

  
2502

  
2503
def _GetNetworkStatsField(field, kind, ctx, net):
2504
def _GetNetworkStatsField(field, kind, ctx):
2504 2505
  """Gets the value of a "stats" field from L{NetworkQueryData}.
2505 2506

  
2506 2507
  @param field: Field name
......
2541 2542
  fields.extend([
2542 2543
    (_MakeField(name, title, kind, doc),
2543 2544
     NETQ_CONFIG, 0, _GetItemAttr(name))
2544
     for (name, (title, kind, flags, doc)) in _NETWORK_SIMPLE_FIELDS.items()
2545
     for (name, (title, kind, _, doc)) in _NETWORK_SIMPLE_FIELDS.items()
2545 2546
    ])
2546 2547

  
2547 2548
  def _GetLength(getter):
......
2573 2574
  fields.extend([
2574 2575
    (_MakeField(name, title, kind, doc), NETQ_STATS, 0,
2575 2576
    compat.partial(_GetNetworkStatsField, name, kind))
2576
    for (name, (title, kind, flags, doc)) in _NETWORK_STATS_FIELDS.items()
2577
    for (name, (title, kind, _, doc)) in _NETWORK_STATS_FIELDS.items()
2577 2578
    ])
2578 2579

  
2579 2580
  return _PrepareFieldList(fields, [])

Also available in: Unified diff