Tangle
Check-in [7c28e7c533]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Version 0.1
Timelines: family | ancestors | descendants | both | trunk | 0.1
Files: files | file ages | folders
SHA1:7c28e7c533847fa6673365078e6dd170c836cefb
User & Date: alaric 2012-04-11 13:27:34
Context
2012-04-11
13:28
Version 0.2 check-in: 10a6f3b93e user: alaric tags: trunk, 0.2
13:27
Version 0.1 check-in: 7c28e7c533 user: alaric tags: trunk, 0.1
13:17
initial empty check-in check-in: 6d177dc2ca user: alaric tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added LICENCE.txt.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
Copyright (c) 2003-2006, Warhead.org.uk Ltd

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the names of Warhead.org.uk Ltd, Snell Systems, nor Kitten Technologies, nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Added README.txt.





























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# Introduction

Tangle is a tool to help you document networks.

It takes a text file that lists:

 * Endpoint devices (eg, servers, workstations)
 * Switches, routers, firewalls
 * Management devices (eg, console/KVM servers, managed PDUs)
 * Network cables
 * Power cables
 * Serial/KVM cables
 * VLANs
 * IPv4 subnets
 * External networks (ISP networks, the phone network, etc)
 * Organisations (that own equipment)

...and how they interconnect.

It can then convert that file into a heavily cross-referenced HTML
document listing all the components of your network. Every device will list every cable that connects to it (specifying the VLAN(s), IPv4 addresses and so on), and clicking on a cable will lead to a list of all devices and VLANs on that cable; clicking on a VLAN will lead to a list of all devices and IPv4 subnets on the cable; and clicking on an IPv4 address or subnet will go to a list of all the IPv4 addresses on that subnet, and so on.

It also outputs several "dot" files for GraphViz. The default makefile produces three diagrams: one for physical network cabling, one for logical network connectivity (showing what devices are on which VLANs), and one showing management cabling (power, serial, and KVM).

It is written in Python, and consists of two layers: a network parser library which reads the network description file, checks it for errors (duplicate IP addresses, etc), and produces an in-memory cross-referenced object graph; and then a set of scripts that use that library to generate the HTML and "dot" output formats. You can write your own scripts that do other things with the data (such as generating reverse DNS zonefiles).

# Using it

A simple (all too simple) driver shell script is supplied, called
`document-network.sh`, that runs parts of Tangle to make a veritable
soup of network documentation.

Try it out on the supplied examples. From this directory, run:

    ./document-network.sh examples/home-lan.tangle

...then look at the HTML and PNG files that appear in the examples directory.

# The tangle file format

The network consists of cables, vlans, devices, and ip4 subnets.

## Cables

Each cable starts with a line of the form:

    {utp|serial|fibre|power|kvm|virtual|usb|telephone|parallel|other|unused} <name> {

Cables all need unique names. Ideally, they should be numbered, with
the number written on the cable (http://www.partex.com/ sell nice
clip-on cable numbers). If you have a multi-location system you can
reuse cable numbers within a location, and write the cable names in
your Tangle file as "<location>.<number>".

Virtual cables are used for internal management interfaces in
switches; they don't exist in the real world, but exist to show that a
virtual port inside a device is connected to something, somehow.

Unused cables are special virtual cables used to group unused ports on
devices together. Each `unused` declaration creates a pool of unused
ports, which is connected with `device` statements to unused ports on
devices. Within the system an unused port pool is really just a cable,
but the display of the cable is modified slightly - it's not
considered to actually link any ports together, and unused port pools
are listed separately to cables in the table of contents. You don't
have to declare your unused ports, but doing so makes it easy to see
what ports you have spare.

A cable declaration is ended with a closing brace:

    }

Within are lines defining the details of the cable:

    device <name>/<port>
    
Declares that this cable goes to the given device on the given
port. Since this is a cabling document, the device names should be in
terms of people looking at the outside of the device - how the
physical socket is labelled, or some other obvious designation; a
server may refer to `eth0` internally, but unless you stick a label
saying `eth0` on the outside of your server (which is a good idea!), a
name like `left` might be more useful to the people who go to the
datacenter to re-cable your server.

Device names can be of the form `<owner>:<device>`. If so, the owning
organisation can be declared with an `organisation` block, to attach
metadata, as described below.

    vlan <vlan>
    
For Ethernet cables, the untagged VLAN carried on this cable. VLAN
names must be unique; if you reuse VLAN names or numbers in different
contexts, name them `<location>.<id>`. It is suggested that you use
the actual VLAN ID as the ID (eg, the number you configure into the
switch), but you can use any alphanumeric string as the ID.

    tagged vlans <vlan>,<vlan>,...
    
For Ethernet cables, the list of tagged VLANs carried on this cable.

    note "<text>"
    
General notes to sysadmins. There can be more than one.

## Devices

We can also optionally provide extra data about devices with a device declaration:

    device <name> {
      ...
    }

If a cable refers to a device with no device declaration, that's fine
- we just don't know anything about the device other than what cables
plug into it. It's a black box.

Within a device declaration, we allow `note` declarations, and these
specialist declarations:

    type {server|switch|router|manager|power|external|virtual|workstation|printer|telephone|firewall|other}

This declares the type of device, which affects how it is displayed in
diagrams, and how it is categorised in the HTML output.


    ip4 <port> [<vlan>] <ip> [shared|stub]
    
This declares that a given port of the device, optionally specifying a
vlan for tagged ports, has a given IPv4 address. There can be more
than one ip4 declaration for a given vlan on a given port, and more
than one vlan on a port, as you would expect. An IP address that
appears on more than one port (eg, HSRP / CARP) should be marked
`shared` to suppress warnings about the duplication. An IP address
that does not need to match a subnet (eg, a /32 address set up on a
Cisco router's loopback interface) can be declared 'stub' to suppress
warnings about that, too.

Some devices are virtual - VMs, for example. We can
express this fact by declaring that the physical server hosts the
virtual server like so:

    hosts <device>

Note that the system makes no real distinction between physical and
virtual devices. They can nest arbitrarily; you can have VMs within VMs.

VM host servers should declare a virtual cable that carries
appropriate vlans to ports on virtual machines, and which plugs into
an internal virtual port in the VM server, to explain how the VMs get
network connectivity.

## VLANs

Likewise, we can provide extra information about a VLAN with a vlan declaration:

    vlan <name> {
      ...
    }

Again, we can use `note` declarations within a VLAN.

    title "<title>"

This gives the VLAN a meaningful title, since VLAN 'names' are usually just the VLAN numbers.

    ip4 subnet <ip>/<prefixlen> "<title>" [multiple]

This declares that a given IPv4 subnet exists on the VLAN. There can
be more than one. The same ip range can exist on different VLANs, too,
but this will cause a warning unless the `multiple` flag is given, as
this state of affairs is sometimes legitimate (eg, when doing BGP
anycast routing, or an IPv4 subnet appears on different VLANs in
different locations)

    ip4 reserved <ip1>-<ip2> "<description>"

This declares that a range of ip4 addresses are reserved for
something. This allocates the IP4s as being in use, as if a port on
the vlan were assigned an IP, but without a port being required. It's
perfect for IP ranges set aside for future use, or for DHCP / VPN /
dialup address pools.

## Organisations

Finally, we can declare information about organisations.

    organisation <code> {

The code of the organisation is the short name used before the colon in the name of a device.

Within an organisation, we can specify a longer name using a title declaration:

    title "<name>"
    
And general notes:

    note "<text>"

And details of authorised and emergency contacts:

    contact [authorised|emergency] "<text>"

# TODOs

## Generalise VLANs

Having multiple virtual circuits over one cable can be useful for:

* Polyphase power cables
* Serial/KVM "splitter" cables
* ...and maybe other uses in future.

We can currently create VLANs on non-Ethernet cables, just it looks
odd; they should be renamed from "VLANs" to "virtual circuits" or some
shorter phrasing.

## More examples

We really need to show off how we do management interfaces in
switches, virtual machines, Cisco router loopback addresses, and other
such more esoteric tricks with virtual cables.

Added document-network.sh.





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/bin/sh

## FIXME: Check command line arguments make sense, complain if not.
## FIXME: Support specifynig an explicit BASENAME, to put output somewhere other than alongside input.
## FIXME: Support having Tangle "installed" somewhere, and finding it on the PATH.

INPUT=$1
BASENAME=`echo $INPUT | sed s/\\.[^.]*$//`
OUTPUT_HTML=$BASENAME.html
OUTPUT_VLANS=${BASENAME}_vlans.png
OUTPUT_NETWORK_CABLES=${BASENAME}_network_cables.png
OUTPUT_MANAGEMENT_CABLES=${BASENAME}_management_cables.png
TMPDIR=/tmp/tangle-run-$$
TMP_VLANS=$TMPDIR/vlans.dot
TMP_NETWORK_CABLES=$TMPDIR/network_cables.dot
TMP_MANAGEMENT_CABLES=$TMPDIR/management_cables.dot

mkdir $TMPDIR

echo "Generating HTML..."
python make-network-html.py < $INPUT > $OUTPUT_HTML

echo "Generating diagrams..."
python make-network-vlan-diagram.py < $INPUT > $TMP_VLANS
python make-network-cabling-diagram.py utp fibre virtual < $INPUT > $TMP_NETWORK_CABLES
python make-network-cabling-diagram.py power kvm serial usb telephone parallel other < $INPUT > $TMP_MANAGEMENT_CABLES

echo "Rendering diagrams..."
neato -Tpng -o $OUTPUT_VLANS $TMP_VLANS
neato -Tpng -o $OUTPUT_NETWORK_CABLES $TMP_NETWORK_CABLES
neato -Tpng -o $OUTPUT_MANAGEMENT_CABLES $TMP_MANAGEMENT_CABLES

echo "Tidying up..."
rm -rf $TMPDIR

Added examples/home-lan.tangle.

















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
device mumpc {
       note "Mum's PC"
       note "Pentium 4 2GHz"
       type workstation

       ip4 wifi 10.0.0.15
}

device dadpc {
       note "Dad's PC"
       type workstation

       ip4 ethernet 10.0.0.10
}

utp dadpc-switch {
    device dadpc/ethernet
    device switch/3
    vlan home
}

device laptop {
       type workstation
       note "No IP address assigned, as it DHCPs"
}

device printer {
       type printer
       
       ip4 ethernet 10.0.0.3
}

utp printer-switch {
      device printer/ethernet
      device switch/2
      vlan home
}

device switch {
       type switch
       note "Eight-port 100Mbit thingy"
       note "Located in the office"
}

unused switch-ports {
       device switch/8
       device switch/7
       device switch/6
       device switch/5
       device switch/4
}

device router {
       type router
       note "ADSL router with integrated wifi thingy"

       ip4 LAN 10.0.0.1
}

utp router-switch {
    device router/LAN
    device switch/1
    vlan home
}

device phone-network {
       type external
       note "2Mbit/sec ADSL"
}

telephone router-adsl {
    device router/WAN
    device phone-network/downstairs-socket
    note "Cable from ADSL router to phone socket on the wall"
}

virtual wifi {
	device mumpc/wifi
	device laptop/wifi
	device router/wifi
	vlan home
}

vlan home {
     ip4 subnet 10.0.0.0/24 "Home"
     ip4 reserved 10.0.0.100-10.0.0.254 "DHCP"
}

Added make-network-cabling-diagram.py.











































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

import network
import sys
import re

names = {}
idCounter = 0
def makeName(name):
   global idCounter
   if name not in names:
      names[name] = idCounter
      idCounter = idCounter + 1
   return names[name]

def printCablingDiagram (cabling, filterSet):
   print "graph cabling {"
   print "edge [len=4];"
   print
   print "// Devices"
   print
   
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
      deviceType = device.deviceType
      
      if deviceType == "router":
         print "device%s [shape=\"hexagon\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "switch":
         print "device%s [shape=\"trapezium\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "manager" or deviceType == "power":
         print "device%s [shape=\"parallelogram\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "external":
         print "device%s [shape=\"triangle\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "virtual":
         print "device%s [shape=\"box\" style=\"dashed\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      else:
         print "device%s [shape=\"box\" label=\"%s\"];" % (makeName(deviceName),deviceName)

   print
   print "// Virtualisation"
   print
   
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
   
      for hosteeName in device.hostedDevices:
         print "device%s -- device%s [style=\"dashed\" headlabel=\"host\" taillabel=\"vm\"]" % (makeName(hosteeName),makeName(deviceName))

   print
   print "// Cables"
   print
   
   def cableStyle(cableType):
      if cableType == "utp":
         return ""
      elif cableType == "fibre":
         return "style=\"dashed\""

      elif cableType == "power":
         return "style=\"bold\""

      elif cableType == "serial":
         return "style=\"dotted\""
      elif cableType == "usb":
         return "style=\"dotted\""
      elif cableType == "parallal":
         return "style=\"dotted\""
      elif cableType == "kvm":
         return "style=\"dotted\""

      elif cableType == "virtual":
         return "style=\"dotted\""


      elif cableType == "telephone":
         return "style=\"dashed\""

      elif cableType == "other":
         return "style=\"dashed\""

      else:
         return ""
      
   for cableName in cabling.cables:
      cable = cabling.cables[cableName]
      cableType = cable.cableType
      
      if filterSet != [] and cableType not in filterSet:
         continue

      if cable.cableType == "unused" or len(cable.devices)<2:
         continue
         
      if len(cable.devices) == 2:
         (deviceName0,port0) = cable.devices[0]
         (deviceName1,port1) = cable.devices[1]
         
         print "device%s -- device%s [taillabel=\"%s\" label=\"%s\" headlabel=\"%s\" %s];" % (makeName(deviceName0), makeName(deviceName1), port0, cableName, port1, cableStyle(cableType))
      else:
         print "cable%s [label=\"%s\"];" % (makeName(cableName),cableName)
      
         for link in cable.devices:
            (deviceName,port) = link
         
            print "cable%s -- device%s [headlabel=\"%s\" %s];" % (makeName(cableName), makeName(deviceName), port, cableStyle(cableType))
         
   print "}"

# 1) Load and process configration

cabling = network.loadCabling (sys.stdin)

# 2) Print it out nicely

filterSet = sys.argv[1:]

printCablingDiagram (cabling, filterSet)

Added make-network-html.py.













































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#
# List all the ports on all the devices, documenting what cable is plugged into each, then do the same for vlans, cables, subnets, etc.
#

import network
import sys
import re

def printHTMLCabling (cabling):
   print "<html><head><title>Devices and Ports</title>"

   print "<link rel=\"stylesheet\" href=\"network.css\" type=\"text/css\">"

   print "</head><body>"

   print "<div id=\"nav1\">"
   print "<a href=\"#nav-devs\">Devices</a>"
   print "<a href=\"#nav-vlans\">VLANs</a>"
   print "<a href=\"#nav-cables\">Cables</a><br>"
   print "<a href=\"#nav-unused\">Unused Ports</a>"
   print "<a href=\"#nav-ip4subnets\">IP4</a>"
   print "<a href=\"#nav-orgs\">Organisations</a>"
   print "</div>"

   print "<div id=\"nav2\">"

   deviceNames = cabling.devices.keys()
   deviceNames.sort()

   vlanNames = cabling.vlans.keys()
   vlanNames.sort()

   cableNames = cabling.cables.keys()
   cableNames.sort()

   subnetNames = cabling.ip4subnets.keys()
   subnetNames.sort()
   
   orgNames = cabling.organisations.keys()
   orgNames.sort()

   print "<h2 id=\"nav-devs\">Devices</h2>"

   for devType in ["server","switch","router","manager","power","external","virtual","workstation","printer","telephone","firewall","other"]:
      found_any = False
      for deviceName in deviceNames:
         if cabling.devices[deviceName].deviceType == devType:
            found_any = True

      if not found_any:
         continue

      if devType == "server":
         print "<h3>Servers</h3>"
      elif devType == "switch":
         print "<h3>Switches</h3>"
      elif devType == "router":
         print "<h3>Routers</h3>"
      elif devType == "firewall":
         print "<h3>Firewalls</h3>"
      elif devType == "manager":
         print "<h3>Management devices</h3>"
      elif devType == "power":
         print "<h3>Power equipment</h3>"
      elif devType == "external":
         print "<h3>External Networks</h3>"
      elif devType == "virtual":
         print "<h3>Virtual Servers</h3>"
      elif devType == "workstation":
         print "<h3>Workstations</h3>"
      elif devType == "printer":
         print "<h3>Printers</h3>"
      elif devType == "telephone":
         print "<h3>Telephones</h3>"
      elif devType == "other":
         print "<h3>Other Devices</h3>"
      print "<ul>"
      for deviceName in deviceNames:
         if cabling.devices[deviceName].deviceType == devType:
            print "<li><a href=\"#%s\">%s</a></li>" % (deviceName,cabling.devices[deviceName])
      print "</ul>"

   print "<h2 id=\"nav-vlans\">VLANs</h2>"

   print "<ul>"
   for vlanName in vlanNames:
      print "<li><a href=\"#vlan-%s\">%s</a></li>" % (vlanName,cabling.vlans[vlanName])
   print "</ul>"   

   print "<h2 id=\"nav-cables\">Cables</h2>"

   print "<ul>"
   for cableName in cableNames:
      if cabling.cables[cableName].cableType != "unused":
         print "<li><a href=\"#cable-%s\">%s</a> %s</li>" % (cableName,cableName,cabling.cables[cableName].cableType)
   print "</ul>"   

   print "<h2 id=\"nav-unused\">Unused Ports</h2>"

   print "<ul>"
   for cableName in cableNames:
      if cabling.cables[cableName].cableType == "unused":
         print "<li><a href=\"#cable-%s\">%s</a></li>" % (cableName,cableName)
   print "</ul>"   

   print "<h2 id=\"nav-ip4subnets\">IP4 Subnets</h2>"

   print "<ul>"
   for subnetName in subnetNames:
      subnet = cabling.ip4subnets[subnetName]
      print "<li><a href=\"#subnet-%s\">%s</a></li>" % (subnet.id,subnet.nice_title())
   print "</ul>"   

   print "<h2 id=\"nav-orgs\">Organisations</h2>"

   print "<ul>"
   for orgName in orgNames:
      print "<li><a href=\"#org-%s\">%s</a></li>" % (orgName,cabling.organisations[orgName])
   print "</ul>"   

   print "</div>"

   numberRE = re.compile(r"[0-9]+")
   def portcmp(a,b):
      # Sort two port names, but noticing if they're all numeric and doing a numeric
      # comparison if so
      if numberRE.match(a[0]) and numberRE.match(b[0]):
         return cmp(int(a[0]),int(b[0]))
      else:
         return cmp(a[0],b[0])

   print "<div id=\"details\">"

   print "<h1>Devices</h1>"

   for deviceName in deviceNames:
      device = cabling.devices[deviceName]
      print "<h2 id=\"%s\">%s (%s)</h1>" % (deviceName,device, device.deviceType)
   
      print "<p>Owner: <a href=\"#org-%s\">%s</a></p>" % (device.owner.code,device.owner.name)
      
      if len(device.hostedDevices) > 0:
         print "<p>Hosted virtual devices</p>"
         print "<ul>"
         for hosteeName in device.hostedDevices:
            print "<li><a href=\"#%s\">%s</a></li>" % (hosteeName, hosteeName)
         print "</ul>"
      
      if len(device.hostedBy) > 0:
         for hostName in device.hostedBy:
            print "<p>This is a virtual device hosted by <a href=\"#%s\">%s</a>" % (hostName,hostName)
   
      for note in device.notes:
         print "<p>%s</p>" % note
   
      ports = device.ports
      ip4s = device.ip4s
   
      ports.sort(portcmp)
   
      print "<table class=\"device\">"
      for portData in ports:
         (port,cable) = portData
         print "<tr class=\"dev-hdr\" id=\"%s-%s\"><td>port <b>%s</b></td><td>%s <a href=\"#cable-%s\">%s</a></td></th>" % (deviceName,port,port,cable.cableType, cable.name,cable.name)
         if cable.tagged == True:
            first = True
            for vlan in cable.vlans:
               if first:
                  print "<tr class=\"dev-vlans\"><td>Tagged VLANs</td>"
                  first = False
               else:
                  print "<tr class=\"dev-vlans\"><td></td>"
               
               print "<td><a href=\"#vlan-%s\">%s</a></td></tr>" % (vlan,cabling.vlans[vlan])
         elif cable.tagged == False:
            print "<tr class=\"dev-vlans\"><td>VLAN</td><td>"
            print "<a href=\"#vlan-%s\">%s</a>" % (cable.vlan,cabling.vlans[cable.vlan])
            print "</td></tr>"
         else:
            # Not Ethernet
            pass
      
         if len(cable.devices)>1 and cable.cableType != "unused":
            first = True
            for oDevice in cable.devices:
               (oDevName,oDevPort) = oDevice
               if oDevName == deviceName:
                  continue # Don't list ourselves

               if first:
                  print "<tr class=\"dev-links\"><td>Links to</td>"
                  first = False
               else:
                  print "<tr class=\"dev-links\"><td></td>"
               print "<td><a href=\"#%s-%s\">%s/%s</a></td></tr>" % (oDevName, oDevPort, oDevName, oDevPort)

         if ip4s.has_key(port):
            first = True
            for ip4 in ip4s[port]:
               if first:
                  print "<tr class=\"dev-ip4\"><td>IPv4</td>"
                  first = False
               else:
                  print "<tr><td></td>"
               
               print "<td>"
            
               if ip4.vlan == None:
                  print "%s" % (network.unparse_ip(ip4.ip))
               else:
                  subnetFound = False

                  for snName in cabling.ip4subnets:
                     sn = cabling.ip4subnets[snName]
                     if ip4.vlan == sn.vlan:
                        for Oip4 in sn.ip4s:
                           for Oport in Oip4.ports:
                              if Oport[0] == deviceName and Oport[1] == port:
                                 subnetFound = True
                                 print "<a href=\"#subnet-%s-%d.%d.%d.%d\">" % (sn.id, ip4.ip[0], ip4.ip[1], ip4.ip[2], ip4.ip[3])
               
                  if subnetFound:
                     print "%s</a>" % network.unparse_ip(ip4.ip)
                  else:
                     print network.unparse_ip(ip4.ip)
               
                  print "(vlan <a href=\"#vlan-%s\">%s</a>)" % (ip4.vlan, ip4.vlan)
            
               if ip4.shared:
                  print "<i>(shared)</i>"
            
               print "</td></tr>"
         
      print "</table>"

   print "<h1>VLANs</h1>"

   for vlanName in vlanNames:
      vlanLinks = cabling.vlans[vlanName].ports
   
      print "<h2 id=\"vlan-%s\">VLAN %s</h2>" % (vlanName, cabling.vlans[vlanName])
   
      for note in cabling.vlans[vlanName].notes:
         print "<p>%s</p>" % note
   
      print "<ul>"

      for sn in cabling.vlans[vlanName].ip4subnets:
         print "<li>IPv4: <a href=\"#subnet-%s\">%s</a></li>" % (sn.id, sn.nice_title())

      print "</ul>"
   
      print "<table class=\"vlan\">"
   
      # Sort by cable then device then port
      vlanLinks.sort(lambda a,b: cmp("%s/%s/%s" % (a[2],a[0],a[1]), "%s/%s/%s" % (b[2],b[0],b[1])))
   
      lastCable = None
   
      for vlanLink in vlanLinks:
         (dev,port,cable) = vlanLink
      
         if cable != lastCable:
            print "<tr class=\"vlan-cable-hdr\">"
            print "<th>%s <a href=\"#cable-%s\">%s</a></th>" % (cable.cableType, cable.name,cable.name)
            lastCable = cable
         else:
            print "<tr>"
            print "<td></td>"
         print "<td><a href=\"#%s-%s\">%s/%s</a></td>" % (dev,port,dev,port)
      
         print "</tr>"

      print "</table>"

   def documentCable(cableName,cable,showVLANs):
      print "<tr id=\"cable-%s\"><th>%s</th>" % (cableName, cable)

      print "<td>"
      for device in cable.devices:
         (dev,port) = device
         print "<a href=\"#%s-%s\">%s/%s</a><br>" % (dev,port,dev,port)
      
      print "</td>"

      if showVLANs:
         if cable.tagged == None:
            print "<td></td>"
         elif cable.tagged:
            print "<td>"
            for vlan in cable.vlans:
               print "<a href=\"#vlan-%s\">%s</a><br>" % (vlan,vlan)
         
            print "</td>"
         else:
            print "<td>untagged <a href=\"#vlan-%s\">%s</a></td>" % (cable.vlan,cable.vlan)
         print "</tr>"

      if len(cable.notes)>0:
         if showVLANs:
            print "<tr class=\"cable-notes\"><td colspan=\"3\">"
         else:
            print "<tr class=\"cable-notes\"><td colspan=\"2\">"
         for note in cable.notes:
            print "<p>%s</p>" % note
         print "</td></tr>"
      

   print "<h1>Cables</h1>"

   print "<table class=\"cables\">"
   print "<tr><th>Cable</th><th>Ports</th><th>VLANs</th></tr>"
   for cableName in cableNames:
      cable = cabling.cables[cableName]
      if cable.cableType != "unused":
         documentCable(cableName, cable, True)
         
   print "</table>"

   print "<h1>Unused Ports</h1>"

   print "<table class=\"cables\">"
   print "<tr><th>Group</th><th>Ports</th></tr>"
   for cableName in cableNames:
      cable = cabling.cables[cableName]
      if cable.cableType == "unused":
         documentCable(cableName, cable, False)
         
   print "</table>"
   
   print "<h1>IP4 Subnets</h1>"

   for subnetName in subnetNames:
      subnet = cabling.ip4subnets[subnetName]
      
      print "<h2 id=\"subnet-%s\">%s on vlan <a href=\"#vlan-%s\">%s</a>" % (subnet.id,network.unparse_ip(subnet.net), subnet.vlan, cabling.vlans[subnet.vlan])
      if subnet.title != None:
         print "(%s)" % subnet.title
   
      print "</h2>"
   
      print "<table class=\"subnet\">"
      subnet.ip4s.sort(lambda a,b: cmp(a.ip,b.ip))
      lastIP4 = None
      for ip4 in subnet.ip4s:
         first = True
         
         if lastIP4 != None and network.next_ip(lastIP4) != ip4.ip:
            print "<tr><td colspan=\"2\">...</td></tr>"
            
         lastIP4 = ip4.ip
         
         for port in ip4.ports:
            if first:
            
               #print "<a href=\"#subnet-%s-%d.%d.%d.%d\">" % (sn.id, ip4.ip[0], ip4.ip[1], ip4.ip[2], ip4.ip[3])
            
               print "<tr class=\"subnet-hdr\" id=\"subnet-%s-%d.%d.%d.%d\"><th>%s</th>" % (subnet.id, ip4.ip[0], ip4.ip[1], ip4.ip[2], ip4.ip[3], network.unparse_ip(ip4.ip))
               first = False
            else:
               print "<tr><td></td>"
            
            if port[0] == None: # reserved IP
               print "<td>(%s)</td>" % port[1]
            else:
               print "<td><a href=\"#%s-%s\">%s/%s</a></td></tr>" % (port[0],port[1],port[0],port[1])
      print "</table>"

   print "<h1>Organisations</h1>"

   for orgName in orgNames:
      org = cabling.organisations[orgName]
      if org.name != org.code:
         print "<h2 id=\"org-%s\">%s (%s)</h2>" % (org.code, org.name, org.code)
      else:
         print "<h2 id=\"org-%s\">%s</h2>" % (org.code, org.name)
      
      for note in org.notes:
         print "<p>%s</p>" % note
      
      if len(org.emergencyContacts) > 0:
         print "<p>In emergency, contact:"
         first = True
         for contact in org.emergencyContacts:
            if not first:
               print ", "
            first = False
            print contact
      
      print "<h3>Owned Devices</h3>"
      print "<ul>"
      for device in org.devices:
         print "<li><a href=\"#%s\">%s</a></li>" % (device.name, device.name)
      print "</ul>"

   print "</div>"

   print "</body></html>"

# 1) Load and process configration

cabling = network.loadCabling (sys.stdin)

# 2) Print it out nicely

printHTMLCabling (cabling)

Added make-network-vlan-diagram.py.





































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

import network
import sys
import re

names = {}
idCounter = 0
def makeName(name):
   global idCounter
   if name not in names:
      names[name] = idCounter
      idCounter = idCounter + 1
   return names[name]

def printVLANDiagram (cabling):
   print "graph vlans {"
   print "edge [len=3];"
   print
   print "// Devices"
   print
   
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
      deviceType = device.deviceType
      
      if deviceType == "router":
         print "device%s [shape=\"hexagon\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "switch":
         print "device%s [shape=\"trapezium\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "manager" or deviceType == "power":
         print "device%s [shape=\"parallelogram\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "external":
         print "device%s [shape=\"triangle\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      elif deviceType == "virtual":
         print "device%s [shape=\"box\" style=\"dashed\" label=\"%s\"];" % (makeName(deviceName),deviceName)
      else: # Anything else
         print "device%s [shape=\"box\" label=\"%s\"];" % (makeName(deviceName),deviceName)

   print
   print "// Virtualisation"
   print

   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]

      for hosteeName in device.hostedDevices:
         print "device%s -- device%s [style=\"dashed\" headlabel=\"host\" taillabel=\"vm\"]" % (makeName(hosteeName),makeName(deviceName))

   print
   print "// VLANs"
   print
      
   for vlanName in cabling.vlans:
      vlan = cabling.vlans[vlanName]
         
      print "vlan%s [label=\"%s\"];" % (makeName(vlanName),vlanName)
      
      for link in vlan.ports:
         (deviceName,port,cable) = link
         
         deviceType = cabling.devices[deviceName].deviceType
         cableType = cabling.cables[cable.name].cableType
         
         # Only show switches if this is a virtual cable, eg their admin port
         if deviceType == "switch":
            if cableType == "virtual":
               print "vlan%s -- device%s [headlabel=\"%s\" style=\"dotted\"];" % (makeName(vlanName), makeName(deviceName), port)
            else:
               pass # Ignore
         else:
            print "vlan%s -- device%s [headlabel=\"%s\"];" % (makeName(vlanName), makeName(deviceName), port)
            
         
   print "}"

# 1) Load and process configration

cabling = network.loadCabling (sys.stdin)

# 2) Print it out nicely

printVLANDiagram (cabling)

Added network.css.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
body {
	font-family: sans-serif;
	font-size: small;
}

div#nav1 {
	position: fixed;
	top: 0em;
	left: 0em;
	width: 15em;
	height: 2em;
}

div#nav2 {
	position: fixed;
	top: 2em;
	left: 0em;
	width: 20em;
	bottom: 0em;
	overflow-y: scroll
}

div#details {
	position: absolute;
	top: 1em;
	left: 21em;
	right: 1em;
}

table {
	background-color: #eeeeff;
	font-size: 10px;
}

tr.dev-hdr td, tr.dev-hdr th {
	background-color: #aaaaff;
}

table.device td.hdr {
	background-color: #aaaaff;
}

tr.vlan-cable-hdr {
	background-color: #aaaaff;
}

table.subnet th {
	background-color: #aaaaff;
}

tr.cable-notes {
	background-color: #eeeeff;
}

a {
	color: black;
}

Added network.py.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769

import sys
import re

# TODO:
# Make a list of stub addresses, and put a table of them in the ip4 subnets section of the report, as a special 'null subnet'
# Allow a way of saying that two VLANs are bridged, and so share a list of ip4 subnets. Bridge lon1.1183 with dub1.1030 and lon1.1309 with dub1.1031.
# If an ip4 is declared in a device, create a port object anyway that's not attached to any cables, and warn about it
# Complain about two cables going to the same port on a device, unless the port is called '?'
# Warn about two cables in same port (pertinent when forgetting to un-unused a port!)


class Cable:
   def __init__(self):
      self.cableType = None
      self.name = None
      self.devices = []
      self.tagged = None
      self.notes = []

      # Ethernet cables only
      self.vlan = None
      self.vlans = []
      
   def __repr__(self):
      return "%s %s" % (self.cableType, self.name)
   pass

class VLAN:
   def __init__(self):
      self.name = None
      self.ports = []
      self.notes = []
      self.ip4subnets = []
      self.title = None
      self.ip4reservations = []

   def __repr__(self):
      if self.title == None:
         return "%s" % (self.name)
      else:
         return "%s (%s)" % (self.name, self.title)

class Device:
   def __init__(self):
      self.name = None
      self.ports = []  # List of (portname,cable) pairs
      self.notes = []
      self.ip4s = {} # indexed on port name
      self.deviceType = "server" # default
      self.owner = None
      self.hostedDevices = [] # List of names of devices we 'host' as VMs
      self.hostedBy = [] # Name of device(s) that host(s) this one, if it's virtual

   def __repr__(self):
      return "%s" % self.name
      
   def has_port(self,port_name):
      for port in self.ports:
         if port[0] == port_name:
            return True
      return False

class Organisation:
   def __init__(self,code):
      self.code = code
      self.name = code
      self.emergencyContacts = []
      self.authorisedContacts = []
      self.notes = []
      self.devices = []
      
   def __repr__(self):
      return self.name

class IP4Port:
   # An IP address on a port
   # Optionally specific to a VLAN on that port
   def __init__(self,vlan,ip,shared,stub):
      self.vlan = vlan
      self.ip = ip
      self.shared = shared
      self.stub = stub
      
   def __repr__(self):
      return "%s on vlan %s" % (unparse_ip(self.ip),self.vlan)

class IP4Subnet:
   # A subnet with the same IP address but different vlans is a different subnet
   def __init__(self,net,title,multiple):
      global IP4SubnetCounter
      self.net = net
      self.vlan = None
      self.ip4s = []
      self.title = title
      self.multiple = multiple
      self.id = None

   def __repr__(self):
      return "%s on vlan %s" % (unparse_ip(self.net),self.vlan)

   def nice_title(self):
      if self.title == None:
         return repr(self)
      else:
         return "%s (%s)" % (repr(self), self.title)

class IP4:
   def __init__(self,ip):
      self.ip = ip
      self.ports = []
      self.shared = False

   def __repr__(self):
      return "%s on %s" % (unparse_ip(self.ip),",".join(map(lambda(port): "%s/%s" % port,self.ports)))

class CablingScheme:
   def __init__(self,cables,vlans,devices,ip4subnets,organisations):
      self.cables = cables
      self.vlans = vlans
      self.devices = devices
      self.ip4subnets = ip4subnets
      self.organisations = organisations

# IPs are represented as 5-tuples: 127.0.0.1 = (127,0,0,1,32)
# 10.0.0.0/8 = (10,0,0,0,8)
def parse_ip(ip_str):
   parts = ip_str.split(".")
   if len(parts) != 4:
      raise ValueError, "Invalid IP address"
   result = (int(parts[0]),int(parts[1]),int(parts[2]),int(parts[3]),32)
   return result

def parse_net(net_str):
   (ip_str,bits) = net_str.split("/")
   parts = ip_str.split(".")
   if len(parts) != 4:
      raise ValueError, "Invalid IP address"
   result = (int(parts[0]),int(parts[1]),int(parts[2]),int(parts[3]),int(bits))
   return result

# Trim off all bits to the right of the prefix
def trim_net (parsed_ip):
   bits = parsed_ip[4]
   orig_bits = bits
   bytes = parsed_ip[0:4]
   
   result = []

   while bits>=8:
      bits = bits - 8
      result.append (bytes[0])
      bytes = bytes[1:]
   
   if bits != 0:
      result.append (bytes[0] & (0xff00 >> bits))
   
   while len(result)<4:
      result.append (0)
      
   result.append(orig_bits)

   result = tuple(result)

   return result

if trim_net((1,2,3,4,32)) != (1,2,3,4,32):
   raise RuntimeError

if trim_net((1,2,3,4,24)) != (1,2,3,0,24):
   raise RuntimeError

if trim_net((1,2,3,4,0)) != (0,0,0,0,0):
   raise RuntimeError

if trim_net((255,255,255,255,4)) != (0xf0,0,0,0,4):
   raise RuntimeError

if trim_net((255,255,255,255,25)) != (255,255,255,128,25):
   raise RuntimeError

def unparse_ip(parsed_ip):
   if parsed_ip[4] == 32:
      return "%d.%d.%d.%d" % parsed_ip[0:4]
   else:
      return "%d.%d.%d.%d/%d" % parsed_ip

# Compare two parsed networks
# returns 0 if a == b
# returns 1 if a contains b
# returns -1 if a is contained by b
# returns None if a and b don't overlap
def compare_nets(a,b):
   # Normalise
   a = trim_net(a)
   b = trim_net(b)
   
   # Equal?
   if a == b:
      return 0
      
   # superset?
   if a[4] > b[4]:
      # a is smaller than b
      a_as_b = trim_net ((a[0],a[1],a[2],a[3],b[4]))
      if a_as_b == b:
         return -1

   if a[4] < b[4]:
      # a is larger than b
      b_as_a = trim_net ((b[0],b[1],b[2],b[3],a[4]))
      if b_as_a == a:
         return 1
   
   return None

if compare_nets((1,2,3,0,24),(2,2,3,0,24)) != None:
   raise RuntimeError

if compare_nets((1,2,3,0,24),(1,2,3,0,24)) != 0:
   raise RuntimeError

if compare_nets((1,2,3,0,24),(1,2,3,128,25)) != 1:
   raise RuntimeError

if compare_nets((1,2,3,4,32),(1,2,3,4,25)) != -1:
   raise RuntimeError

def next_ip(ip):
   ip = (ip[0],ip[1],ip[2],ip[3]+1,32)
   if ip[3] == 256:
      ip = (ip[0],ip[1],ip[2]+1,0,32)
      if ip[2] == 256:
         ip = (ip[0],ip[1]+1,0,0,32)
         if ip[1] == 256:
            ip = (ip[0]+1,0,0,0,32)
            if ip[0] == 256:
               ip = (0,0,0,0,32)
   return ip

if next_ip((1,2,3,0,32)) != (1,2,3,1,32):
   raise RuntimeError

if next_ip((1,2,3,255,32)) != (1,2,4,0,32):
   raise RuntimeError

if next_ip((1,2,255,255,32)) != (1,3,0,0,32):
   raise RuntimeError

if next_ip((1,255,255,255,32)) != (2,0,0,0,32):
   raise RuntimeError

class IPRange:
   def __init__(self,fromIP,toIP):
      self.fromIP = fromIP
      self.toIP = toIP
      self.currentIP = fromIP
      self.finished = False
   
   def __iter__(self):
      return self
   
   def next(self):
      if self.finished:
         raise StopIteration
      else:
         self.currentIP = next_ip(self.currentIP)
         self.finished = self.currentIP == self.toIP
         return self.currentIP

def parseCabling(infile):

   # ... # ...
   commentRE = re.compile(r"([^#]*)#.*")

   # <type> <id> {
   cableStartRE = re.compile(r"(utp|serial|fibre|power|kvm|virtual|usb|telephone|parallel|other|unused) +([^ ]+) *{")

   # device <name>/<port>
   deviceRE = re.compile(r"device +([^ /]+) */ *([^ ]+)")

   # vlan <num>
   vlanRE = re.compile(r"vlan +([^ ]+)")

   # tagged vlans <nums>
   taggedVlansRE = re.compile(r"tagged +vlans +([^ ]+)")

   # note "<text>"
   noteRE = re.compile(r"note +\"([^\"]*)\"")

   # title "<text>"
   titleRE = re.compile(r"title +\"([^\"]*)\"")

   # device <name> {
   deviceStartRE = re.compile(r"device +([^ /]+) *{")
   
   # type <type>
   deviceTypeRE = re.compile(r"type +((server|switch|router|manager|power|external|virtual|workstation|printer|telephone|firewall|other))")

   deviceHostsRE = re.compile(r"hosts +([^ /]+)")

   # ip4 <port> <vlan> <ip> [shared|stub]
   ip4vlanRE = re.compile(r"ip4 +([^ ]+) +([^ ]+) +([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) *((shared|stub)?)")

   # ip4 <port> <ip> [shared|stub]
   ip4RE = re.compile(r"ip4 +([^ ]+) +([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) *((shared|stub)?)")

   # vlan <name> {
   vlanStartRE = re.compile(r"vlan +([^ /]+) *{")

   # ip4 subnet <ip>/<prefix> "<title>" [multiple]
   ip4subnetRE = re.compile(r"ip4 +subnet +([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+) +\"([^\"]+)\" *((multiple)?)")
   
   # ip4 reserved <ip>-<ip> "<description>"
   ip4reservedRE = re.compile(r"ip4 +reserved +([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)-([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) +\"([^\"]+)\"")

   # organisation <code> {
   organisationStartRE = re.compile(r"organisation +([^ :]+) *{")

   # contact emergency "<text>"
   orgEmergContactRE = re.compile(r"contact +emergency +\"([^\"]+)\"")

   # contact authorised "<text>"
   orgAuthContactRE = re.compile(r"contact +authorised +\"([^\"]+)\"")

   endRE = re.compile(r"}")
   
   cables = {}
   cable = None

   vlans = {}
   vlan = None

   devices = {}
   device = None
   
   ip4subnets = {}
   ip4subnet = None
   
   organisations = {}
   organisation = None

   lineNumber = 0
   for line in infile:
      m = commentRE.match (line)
      if m:
         line = m.group(1)

      line = line.strip()
      lineNumber = lineNumber+1
   
      # print >> sys.stderr, "%d:(%s/%s/%s) %s" % (lineNumber, cable, device, vlan, line)
   
      if line == "":
         continue
   
      if cable == None and vlan == None and device == None and organisation == None:
         m = cableStartRE.match(line)
         if m:
            cable = Cable()
            cable.cableType = m.group(1)
            cable.name = m.group(2)
         
            if cables.has_key(cable.name):
               print >> sys.stderr, "line %d: The cable %s is declared twice" % (lineNumber,cable.name)
               sys.exit(1)
         
            continue
         else:
            m = deviceStartRE.match(line)
            if m:
               device = Device()
               device.name = m.group(1)
            
               if devices.has_key(device.name):
                  print >> sys.stderr, "line %d: The device %s is declared twice" % (lineNumber,device.name)
                  sys.exit(1)

               nameparts = device.name.split(":")
               if len(nameparts) == 1:
                  orgname = "unknown"
               else:
                  orgname = nameparts[0]

               if organisations.has_key(orgname):
                  device.owner = organisations[orgname]
               else:
                  org = Organisation(orgname)
                  device.owner = org
                  organisations[orgname] = org

               device.owner.devices.append(device)
               continue
            else:
               m = vlanStartRE.match(line)
               if m:
                  vlan = VLAN()
                  vlan.name = m.group(1)
               
                  if vlans.has_key(vlan.name):
                     print >> sys.stderr, "line %d: The vlan %s is declared twice" % (lineNumber,vlan.name)
                     sys.exit(1)
                  continue
               else:
                  m = organisationStartRE.match(line)
                  if m:
                     organisation = Organisation(m.group(1))
                     
                     if organisations.has_key(organisation.code):
                        print >> sys.stderr, "line %d: The organisation %s is declared twice" % (lineNumber, organisation.code)
                     continue
                  else:
                     print >> sys.stderr, "line %d: Syntax error in global scope:" % lineNumber
                     print >> sys.stderr, line
                     sys.exit(1)
   
      if organisation != None:
         m = noteRE.match(line)
         if m:
            organisation.notes.append(m.group(1))
         else:
            m = titleRE.match(line)
            if m:
               organisation.name = m.group(1)
            else:
               m = orgEmergContactRE.match(line)
               if m:
                  organisation.emergencyContacts.append (m.group(1))
               else:
                  m = orgAuthContactRE.match(line)
                  if m:
                     organisation.authorisedContacts.append (m.group(1))
                  else:
                     m = endRE.match(line)
                     if m:
                        organisations[organisation.code] = organisation
                        organisation = None
                     else:
                        print >> sys.stderr, "line %d: Syntax error in organisation scope:" % lineNumber
                        print >> sys.stderr, line
                        sys.exit(1)
                        
   
      if device != None:
         m = noteRE.match(line)
         if m:
            device.notes.append(m.group(1))
         else:
            m = endRE.match(line)
            if m:
               devices[device.name] = device
               device = None
            else:
               m = ip4vlanRE.match(line)
               if m:
                  if not device.ip4s.has_key(m.group(1)):
                     device.ip4s[m.group(1)] = []
               
                  shared = m.group(4) == "shared"
                  stub = m.group(4) == "stub"
                  device.ip4s[m.group(1)].append(IP4Port(m.group(2),parse_ip(m.group(3)),shared,stub))
               else:
                  m = ip4RE.match(line)
                  if m:
                     if not device.ip4s.has_key(m.group(1)):
                        device.ip4s[m.group(1)] = []

                     shared = m.group(3) == "shared"
                     stub = m.group(3) == "stub"
                     device.ip4s[m.group(1)].append(IP4Port(None,parse_ip(m.group(2)),shared,stub))
                  else:
                     m = deviceTypeRE.match(line)
                     if m:
                        device.deviceType = m.group(1)
                     else:
                        m = deviceHostsRE.match(line)
                        if m:
                           device.hostedDevices.append(m.group(1))
                        else:
                           print >> sys.stderr, "line %d: Syntax error in device scope:" % lineNumber
                           print >> sys.stderr, line
                           sys.exit(1)

      if vlan != None:
         m = noteRE.match(line)
         if m:
            vlan.notes.append(m.group(1))
         else:
            m = endRE.match(line)
            if m:
               vlans[vlan.name] = vlan
               vlan = None
            else:
               m = ip4subnetRE.match(line)
               if m:
                  net = parse_net(m.group(1))
                  trimmed = trim_net(net)
                  if trimmed != net:
                     print >> sys.stderr, "line %d: Subnet %s is not canonical (should be %s)" % (lineNumber, unparse_ip(net), unparse_ip(trimmed))
                  
                  multiple = m.group(3) == "multiple"
                  vlan.ip4subnets.append((trimmed,m.group(2),multiple))
               else:
                  # ip4 reserved <ip>-<ip> "<description>"
                  m = ip4reservedRE.match(line)
                  if m:
                     fromIP = parse_ip(m.group(1))
                     toIP = parse_ip(m.group(2))
                     descr = m.group(3)
                     
                     # FIXME: Check for overlap
                     vlan.ip4reservations.append((fromIP,toIP,descr))
                        
                  else:
                     m = titleRE.match(line)
                     if m:
                        vlan.title = m.group(1)
                     else:
                        print >> sys.stderr, "line %d: Syntax error in vlan scope:" % lineNumber
                        print >> sys.stderr, line
                        sys.exit(1)
   
      if cable != None:
         m = endRE.match(line)
         if m:
            cables[cable.name] = cable
            cable = None
         else:
            m = deviceRE.match(line)
            if m:
               cable.devices.append ((m.group(1),m.group(2)))
            else:
               m = vlanRE.match(line)
               if m:
                  if cable.cableType == "unused":
                     print >> sys.stderr, "line %d: Syntax error in unused port pool scope:" % lineNumber
                     print >> sys.stderr, line
                     sys.exit(1)
               
                  cable.tagged = False
                  cable.vlan = m.group(1)
               else:
                  m = taggedVlansRE.match(line)
                  if m:
                     if cable.cableType == "unused":
                        print >> sys.stderr, "line %d: Syntax error in unused port pool scope:" % lineNumber
                        print >> sys.stderr, line
                        sys.exit(1)
                  
                     cable.tagged = True
                     for _vlan in m.group(1).split(","):
                        if _vlan != "":
                           cable.vlans.append (_vlan.strip())
                  else:
                     m = noteRE.match(line)
                     if m:
                        cable.notes.append(m.group(1))
                     else:
                        print >> sys.stderr, "line %d: Syntax error in cable scope:" % lineNumber
                        print >> sys.stderr, line
                        sys.exit(1)

   return CablingScheme(cables, vlans, devices, ip4subnets, organisations)

def crossRefHosts(cabling):
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
      for hosteeName in device.hostedDevices:
         if cabling.devices.has_key(hosteeName):
            cabling.devices[hosteeName].hostedBy.append(deviceName)
         else:
            print >> sys.stderr, "Device %s claims to host nonexistant device %s" % (deviceName, hosteeName)
            sys.exit(1)

def crossRefPorts(cabling):
   for cableName in cabling.cables:
      cable = cabling.cables[cableName]
      for device in cable.devices:
         (dev,port) = device
      
         # Create devices that were not declared explicitly in the
         # file, but implied by having a cable going to them
         if not cabling.devices.has_key(dev):
            device = Device()
            cabling.devices[dev] = device
            device.name = dev
            
            nameparts = device.name.split(":")
            if len(nameparts) == 1:
               orgname = "unknown"
            else:
               orgname = nameparts[0]

            if cabling.organisations.has_key(orgname):
               device.owner = cabling.organisations[orgname]
            else:
               org = Organisation(orgname)
               device.owner = org
               cabling.organisations[orgname] = org

            device.owner.devices.append(device)
            
         # Is something already plugged into that port?
         # Disable warning if port name is '?' since that means we don't know what's what
         if port != "?":
            for devPort in cabling.devices[dev].ports:
               if devPort[0] == port:
                  print >> sys.stderr, "The port %s/%s is already attached to %s, and %s is also attempting to plug into it" % (dev, port, devPort[1], cable)
         cabling.devices[dev].ports.append ((port,cable))
      
         if cable.tagged == False:
            # Fix up any ip4s without VLAN specified
            for portName in cabling.devices[dev].ip4s:
               if portName == port:
                  ip4s = cabling.devices[dev].ip4s[portName]
                  for ip4 in ip4s:
                     if ip4.vlan == None:
                        # print >>sys.stderr, "Assigning vlan %s from cable %s to ip %s of %s/%s" % (cable.vlan, cable, ip4, portName, dev)
                        # print >>sys.stderr, "We shared this cable with %s" % cable.devices
                        ip4.vlan = cable.vlan

def crossRefVLANs(cabling):
   for cableName in cabling.cables:
      cable = cabling.cables[cableName]
   
      if cable.tagged == None:
         pass # Not Ethernet
      elif cable.tagged: # Lots of VLANs
         for vlan in cable.vlans:
            # Create any vlans that were not explicitly declared
            # in the configuration, but implied by being present on a cable
            if not cabling.vlans.has_key(vlan):
               cabling.vlans[vlan] = VLAN()
               cabling.vlans[vlan].name = vlan

            # Build list of ports on each vlan
            for device in cable.devices:
               (dev,port) = device
               cabling.vlans[vlan].ports.append((dev,port,cable))
         
      else: # Just one VLAN
         # Create any vlans that were not explicitly declared
         # in the configuration, but implied by being present on a cable
         if not cabling.vlans.has_key(cable.vlan):
            cabling.vlans[cable.vlan] = VLAN()
            cabling.vlans[cable.vlan].name = cable.vlan
      
         # Build list of ports on each vlan
         for device in cable.devices:
            (dev,port) = device
            cabling.vlans[cable.vlan].ports.append((dev,port,cable))


def crossRefIP4Subnets(cabling):
   # Examine ip4 subnets delcared on vlans
   for vlanName in cabling.vlans:
      vlan = cabling.vlans[vlanName]
      
      processedSubnets = []
   
      for subnetDetails in vlan.ip4subnets:
         (subnet,title,multiple) = subnetDetails
         for existingSubnetName in cabling.ip4subnets:
            existingSubnet = cabling.ip4subnets[existingSubnetName]
            comparison = compare_nets(existingSubnet.net,subnet)
         
            if comparison != None:
               # Same subnet on two VLANS is fine, it can be bridged
               # Or it might be being used for BGP anycast
               # Best warn anyway, though.
               # Overlapping subnets are a bit odd, though.
               if comparison == 0:
                  if not (multiple and existingSubnet.multiple):
                     print >>sys.stderr, "The subnet %s (from vlan %s) also exists on vlan %s" % (unparse_ip(subnet), vlan,  existingSubnet.vlan)
               else:
                  print >>sys.stderr, "The subnet %s (from vlan %s) overlaps the existing subnet %s" % (unparse_ip(subnet), vlan, existingSubnet)
               break
      
         newSubnet = IP4Subnet(subnet,title,multiple)
         newSubnet.vlan = vlanName
         cabling.ip4subnets[repr(newSubnet)] = newSubnet
         processedSubnets.append (newSubnet)
      
      vlan.ip4subnets = processedSubnets

   # Assign an ID to each subnet

   for subnetName in cabling.ip4subnets:
      subnet = cabling.ip4subnets[subnetName]
   
      subnet.id = "%d.%d.%d.%d.%d-%s" % (subnet.net[0],subnet.net[1],subnet.net[2],subnet.net[3],subnet.net[4],subnet.vlan)
      
   # Examine ip reservations
   
   for vlanName in cabling.vlans:
      vlan = cabling.vlans[vlanName]
      for resv in vlan.ip4reservations:
         (fromIP,toIP,descr) = resv
         for subnetName in cabling.ip4subnets:
            subnet = cabling.ip4subnets[subnetName]
            if vlanName == subnet.vlan and compare_nets(fromIP, subnet.net) == -1:
               ipRange = IPRange(fromIP,toIP)
               for ip in ipRange:
                  newIp4 = IP4(ip)
                  newIp4.ports.append((None,descr))
                  newIp4.shared = False
                  subnet.ip4s.append(newIp4)

   # Examine ip addresses on ports on devices
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
   
      for ip4portName in device.ip4s:
         if not device.has_port(ip4portName):
            print >>sys.stderr, "An IP is declared on port %s/%s, but no cable graces that port" % (deviceName, ip4portName)
         ip4ports = device.ip4s[ip4portName]
         for ip4port in ip4ports:
            ip4 = ip4port.ip

            if ip4port.vlan == None and not ip4port.stub:
               print >>sys.stderr, "Port %s/%s declares IP %s, but the vlan is not declared and we cannot derive one automatically" % (deviceName,ip4portName, unparse_ip(ip4))
               continue
            
            #print >>sys.stderr, "Examining port %s" % ip4port
      
            matchedSubnets = []
            for subnetName in cabling.ip4subnets:
               subnet = cabling.ip4subnets[subnetName]
               #print >>sys.stderr, "considering %s vs %s: %s" % (ip4, subnet.net, compare_nets(ip4, subnet.net))
               #print >>sys.stderr, "vlan is %s vs. %s" % (ip4port.vlan, subnet.vlan)
               if (ip4port.vlan == subnet.vlan) and compare_nets(ip4, subnet.net) == -1:
                  # We have found our subnet
                  matchedSubnets.append(subnet)
                  #print >>sys.stderr, "ip address %s from %s/%s (vlan %s)" % (unparse_ip(ip4), deviceName, ip4portName, ip4port.vlan)
                  #print >>sys.stderr, "matches subnet %s" % subnet
            
                  existing = False
                  for existingIp4 in subnet.ip4s:
                     if existingIp4.ip == ip4:
                        if not (ip4port.shared and existingIp4.shared):
                           #print >>sys.stderr, "%s / %s" % (ip4port.shared, existingIp4.shared)
                           print >>sys.stderr, "The IP %s on %s/%s collides with %r" % (ip4port, deviceName, ip4portName, existingIp4)
                     
                        existing = True
                        existingIp4.ports.append((deviceName,ip4portName))
                     
                  if not existing:
                     newIp4 = IP4(ip4)
                     newIp4.ports.append((deviceName,ip4portName))
                     newIp4.shared = ip4port.shared
                     subnet.ip4s.append(newIp4)

            if ip4port.stub:
               if len(matchedSubnets) != 0:
                  print >>sys.stderr, "The IP %s is marked as a stub, but matches some subnets (%s)" % (ip4port,matchedSubnets)
            else:
               if len(matchedSubnets) == 0:
                  print >>sys.stderr, "The IP %s does not match any subnets" % ip4port
               elif len(matchedSubnets) != 1:
                  print >>sys.stderr, "The IP %s matched more than one subnet (%s)" % (ip4port,matchedSubnets)

def loadCabling (infile):
   cabling = parseCabling (infile)
   crossRefHosts (cabling)
   crossRefPorts (cabling)
   crossRefVLANs (cabling)
   crossRefIP4Subnets (cabling)
   
   return cabling