Tangle
Check-in [3c3bf83fcd]
Login

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

Overview
Comment:Version 0.5
Timelines: family | ancestors | descendants | both | trunk | 0.5
Files: files | file ages | folders
SHA1: 3c3bf83fcd5b7865176327da699c81c806fb2273
User & Date: alaric 2012-04-11 13:29:57
Context
2012-04-11
13:36
Renamed README.txt to README.wiki, but failed to actually change it to wiki syntax yet. check-in: de4fc2582b user: alaric tags: trunk
13:29
Version 0.5 check-in: 3c3bf83fcd user: alaric tags: trunk, 0.5
13:28
Version 0.3 check-in: 3a2fdd376f user: alaric tags: trunk, 0.3
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to 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
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





















# 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/USB/parallel cables
 * Telephone cables (for analogue phones that don't go over UTP)


 * Telephones
 * 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
    ./document-network.sh examples/office-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.

If you don't know what port it's plugged into, as you have incomplete
information, just use `?` as the port name. This will suppress errors
about multiple cables going into the same port, as many cables will
probably go to the `?` port on a device.


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.

    mac <port> [<vlan>] <mac> [shared]

This declares that a given port of the device (again, optionally
specifying a vlan for tagged ports), has a given MAC address. The
address should be in `xx:xx:xx:xx:xx:xx` form, but omitting the colons
or using other characters (spaces, hypens) is also
acceptable. Re-using the same MAC will cause warnings, unless `shared`
is specified.

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>"

# History


















## Version 0.3

Added MAC address support

## Version 0.2

Added the office-lan example, and improved the rendering logic

## Version 0.1

Initial public release



# 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.




Suggestion: s/vlan/circuit/ but keep "vlan" as a parser-level synonym.




And add a "type" declaration within a circuit declaration, with values




matching the same types allowed for cables.


































## Generalise device/cable types




The core engine has a fixed list of device and cable types (and vlan
types?), even though it doesn't really care what they are. Front-end
scripts tend to care more, as they often invoke special rendering for
particular types of object.

Adding to this list involves extending the parser regexps, extending
the documentation, and then extending the various rendering scripts.

It might be nice to have a configuration file that lists all the types
of typable things, and then listing key=value properties for them. The
parser can generate its regexps from the lists, and then frontends can
look up keys to find styling information for specific types.

Make better use of more node shapes:

http://www.graphviz.org/doc/info/shapes.html

Also, make use of colour to better distinguish node and link types in
the graphviz outputs.












## Minor issues







* Make ip4 reserved ranges appear as a single row in the IP4 displays
  in the HTML.

* Make it a proper installable Python thing where you do `python
  setup.py install`


































>
>

|


>
|




|
>

|


















<
<




>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
<
<
<

|














>
|
|
>
|
>

>
|
|
|
>
|
|
>
|
|
>

>
|
|
>
>
|
>


|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
>

















|
|

|
|
|






|


|















|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|

|



|



|
>
>
>
>
>
>
>



|
|


|






|








>
|
>
|
>




|










>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












<
<


>
|
>
>
>
>
>
>
>
>
>
>
>

>
|
>
>
>
>

>
|
>
>
>
|
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
>
>
>
>
>
|
>
>
>
>
|
>
>
>
|
|
>
>
>
|
|
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>
|



















>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>

|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# 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/USB/parallel cables
 * Telephone cables (for analogue phones that don't go over UTP)
 * Structured cabling systems (eg, patch panels, wall sockets, and the
   trunk lines between them)
 * Telephones
 * Logical circuits (eg, VLANs, power phases)
 * IPv4 subnets
 * External networks (ISP networks, the phone network, etc)
 * Locations (where equipment is)
 * Organisations (that own equipment and locations)

...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 logical circuit(s), IPv4 addresses and so on), and clicking on a cable will lead to a list of all devices and circuits on that cable; clicking on a circuit will lead to a list of all devices and IPv4 subnets on the circuit; 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 circuits), 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
    ./document-network.sh examples/office-lan.tangle

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

# The tangle file format



## Cables

Each cable starts with a line of the form:

    <type> <name> {
      ...
    }

Valid cable types, with their common uses, are:

 * `utp`, `fibre`, `wifi`, or `virtual` for Ethernet cables. `virtual`
   cables are used for logical network connections that join virtual
   machines to the network, or the internal ports by which switches
   connect their management processor into the switching
   fabric. `wifi` cables, in particular, tend to have lots and lots of
   devices on them, but any cable can have any number of devices.

 * `serial` and `parallel` for RS232 and parallel links. `serial`
   cables are often used for management consoles on devices.

 * `usb` for USB connections (often found joining printers to print
   servers, or for attaching low-end UPSes to management servers; we
   don't suggest you document your keyboard and mouse in Tangle).

 * `kvm` for combined keyboard/video/mouse connections used as part of
   a remote management solution.

 * `telephone` for dedicated telephone cables. If your phone system
   uses UTP cabling, call it `utp`.

 * `power`, or if you want to be specific, `power240vAC`,
   `power110vAC`, `power48vDC` or `power12vDC`, for power cables.

Note that what matters is the *physical* type of cable; if you're
running RS232 or telephones or KVM or even power over UTP, then call
it `utp`.

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>".















Within the cable declaration 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.

If you don't know what port it's plugged into, as you have incomplete
information, just use `?` as the port name. This will suppress errors
about multiple cables going into the same port, as many cables will
probably go to the `?` port on a device.

    panel <panel>/<port>

This declares that the cable plugs into the specified port of a patch
panel or wall socket.

A cable can have any number of `device` and `panel` declarations.

    circuit <circuit>
    vlan <circuit>

The logical circuit carried on this cable. For an Ethernet cable,
that's an untagged VLAN. Circuit names must be unique; if you reuse
VLAN names or numbers in different contexts, name them
`<location>.<id>`. It is suggested that you use a physical identifier
such as the actual VLAN ID, phase name as from the supplier, etc as
the ID (eg, the number you configure into the switch), but you can use
any alphanumeric string as the ID. The synonym `vlan` for `circuit` is
accepted. This declaration is only allowed once.

    circuits <circuit>,<circuit>,...
    tagged vlans <circuit>,<circuit>,...

For cables that carry multiple circuits (such as tagged VLANs,
polyphase power cables, KVM octopus cables, etc), the list of circuits
carried on this cable. `tagged vlans` is a synonym for
`circuits`. This declaration is only allowed once.

    note "<text>"

General notes to sysadmins. There can be more than one.

## Panels

Patch panels and wall sockets are all modelled as "panels" in
Tangle. Each panel must be declared like so:

    panel <panel> {
      ...
    }

Within the panel declaration, the following are legal:

     title "<title>"

Gives the panel a long name.

     note "<note>"

Attaches a note to the panel.

     location <location>

Assigns a location to the panel.

Panels may be assigned owners, by giving them a name of the form `<owner>:<panel>`.

However, the ports on a panel are not declared in the panel itself;
they are declared implicitly, by having cables plugged into them and
trunks declared between them

## Trunks

The fixed cabling that joins panels is known as a "trunk" in
Tangle. As trunks are often large groups of cables, they are always
declared as part of a "trunk group", like so:

    <type> trunk <name> {
       ...
    }

The `<type>` is from the same set of types used for cables, and
indicates the type of cabling in this trunk group.

Within the trunk group, the following declarations are allowed:

    title "<name>"

Assigns a long name to the trunk group.

    note "<note>"

Attaches a note to the trunk group.

    trunk <label> <panel>/<port> <panel>/<port>

Declares a single trunk between the given panel/port pairs, with the
given label. The label need only be unique within the trunk group.

    trunk <panel>/<port> <panel>/<port>

Declares a single trunk between the given panel/port pairs, with a
label made by adding 1 to the label of the previous trunk
declared. This is only legal when the label of the previous trunk was
a number (at the start of a trunk group, the previous label is
considered to be `0`).

    group <panel>/<port>-<port> <panel>/<port>-<port>

Declares a number of trunks between the specified range of ports on
the specified panels. This is only useful when panels have numeric
port names. It also implies automatic trunk number, so it is only
legal when the previous trunk label was numeric, or if this is the
first trunk declaration within a trunk group.

## Links

When a single cable joins ports on devices, it makes a
link. However, when a cable connects to panels and trunks, then
multiple cables - at least one patch cable at each end, and a trunk in
the middle - join together to join ports on devices. That group of
interconnected cables is known as a "link". Cables and panels and
trunks are the physical things you tell Tangle about; it works out
what the resulting links are itself.

A single-cable link will be named after the cable; but a multi-cable
link will end up with a name composed of its component cables.

Do not confuse a link - which is a single physical path joining some
devices - with a circuit, which is a more abstract notion like a VLAN.

## 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> [<circuit>] <ip> [shared|stub]

This declares that a given port of the device, optionally specifying a
circuit for tagged-VLAN ports, has a given IPv4 address. There can be more
than one ip4 declaration for a given circuit on a given port, and more
than one circuit 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.

    mac <port> [<circuit>] <mac> [shared]

This declares that a given port of the device (again, optionally
specifying a circuit for tagged VLAN ports), has a given MAC address. The
address should be in `xx:xx:xx:xx:xx:xx` form, but omitting the colons
or using other characters (spaces, hypens) is also
acceptable. Re-using the same MAC will cause warnings, unless `shared`
is specified.

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 vlan circuits 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.

We can also give devices physical locations, like so:

    location <location>

## Unused ports

It can be nice to document unused ports on devices, too, so you know
what's spare. This is done with an `unused` declaration:

    unused <name> {
      ...
    }

The block of unused ports needs to be given a name. How you structure
these is up to you - if a bank of switches are all functionally
identical, then you might group all their unused ports into one block;
or you might have separate blocks for different kinds of ports on the
one device.

Within an unused ports declaration, you can use the `device`
declaration to name a device/port pair that is unused, exactly like in
a cable declaration. You can also use `note` to attach notes.

## Locations

Locations must be declared with a `location` declaration:

    location <location> {
      ...
    }

Locations accept `note` declarations, like most objects in Tangle, and
an optional `title` declaration that assigns a long title that
may contain spaces.

Locations may, in turn, be within a parent location:

    location <location>

And they can have zero or more addresses:

    address <type> "<address>"

The address type can be any single word; I recommend using `postal`
for postal addresses, `latlong` for latitude/longitude, etc.

Also, like devices, locations can be given a name of the form
`<organisation>:<name>`, declaring that they belong to a specific organisation.

## Circuits / VLANs

Likewise, we can provide extra information about a circuit with a `circuit` declaration:

    circuit <name> {
      ...
    }

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

    title "<title>"

This gives the circuit a meaningful title, since circuit 'names' are
usually just physical identifiers such as VLAN numbers.

Each circuit has a type, which can be specified with:

    type {ethernet|serial|parallel|power|kvm|usb|telephone}

Ethernet circuits can carry IP4 subnets. These are declared like so:

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

This declares that a given IPv4 subnet exists on the circuit. There can
be more than one. The same ip range can exist on different circuits, 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 circuits 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 circuit 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 or location.

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>"

# History

## Version 0.6

Fixed bug in IP ranges, which was missing the first IP of the range.

## Version 0.5

Added support for locations.

## Version 0.4

Generalised VLANs into "circuits", which can apply to more than just
Ethernet (eg, power; a polyphase power system can carry multiple power
circuits in a cable, which split out into single-phase cables, for
instance).

"vlan" is now a parser synonym for "circuit".

## Version 0.3

Added MAC address support

## Version 0.2

Added the office-lan example, and improved the rendering logic

## Version 0.1

Initial public release



# TODOs

## More flexible mappings from cable types to circuit types

Right now, we have a fixed mapping, that each cable type (eg, `utp`)
has a corresponding circuit type (eg, `ethernet`) that it can
carry. However, UTP in particular can carry ethernet, serial, KVM, and
others. This, currently, will cause warnings as the system will
complain that a UTP cable is meant for Ethernet! It'd be best to make
each cable type map to a list of circuit types so the warnings can be
handled better. It makes it harder to guess the type of a circuit,
though - we'd need to try to find, for undeclared-type circuits that
don't have IP4 subnets or MAC addresses (which would make them
definitely Ethernets) a common type, or just leave them as of unknown
type.

## Structured cabling

Right now cables are rather simple beasts. To better support
structured cabling systems, it would be nice to explain how a physical
link gets from some switch port to another, via a structured cabling
system.

Proposal:

Allow the creation of "panels", which have a series of named ports,
just like a switch. But they are not a "device" to tangle. Ports have
a type, from the same set as cables.

"trunk group" objects join pairs of panel ports together. Provide an
easy way to make a series of trunks between contiguous ranges of
numbered ports. Eg, "Ports 1-4 on patch A are trunked to ports 5-8 on
patch B". Trunks, like any other cables, may join any number of panel
ports (consider busses, such as power cabling).

Cables may now join device ports or panel ports.

Inside tangle, what is currently called a "cable" becomes a "link". A
link is just like a cable, except it has a different name per
attachment point, and it has an internal structure composed of one or
more cables, with trunks between two panel ports joining cables.

So, we might have:

    panel patch-a {
          title "Second floor patch panel"
          # Patch ports are created implicitly by trunking them
    }

    panel patch-b {
          title "Basement patch panel"
    }
    
    utp trunk st {
        title "Stairwell trunk"
        group patch-a/1-4 patch-b/5-8
    
        # Could also be written out as:
    
        # trunk patch-a/1 patch-b/5
        # trunk patch-a/2 patch-b/6
        # trunk patch-a/3 patch-b/7
        # trunk patch-a/4 patch-b/8
    
        # Each trunk line lists *one or more* endpoints, although
        # there's little use for a one-end trunk; perhaps unfinished
        # cabling!
    
        # Each connection in the trunk is assigned a label, by default
        # str(int(previous_label)+1), so both of the above would
        # label them '1' to '4'.
    
        # But we can also name or number them explicitly, eg if we have
        # identification by pair colour in a big cable:
    
        # trunk red patch-a/1 patch-b/5
        # trunk blue patch-a/2 patch-b/6
        # trunk green patch-a/3 patch-b/7
        # trunk yellow patch-a/4 patch-b/8
    }
    
    utp A01 { # Patch two ports together
        panel patch-a/1
        panel patch-a/2
    }
    
    utp B01 {
        panel patch-b/5
        device server/eth
    }
    
    utp B02 {
        panel patch-b/6
        device switch/6
    }

Now, we have a link from server/eth to switch/6, which tangle will
treat as it currently treats cables. But that link knows it's called
"B01" where it connects to server/eth, and "B02" where it connects to
switch/6, and it knows it has this structure:

utp B01 -> panel patch-b/5 -> trunk st/1 -> panel patch-a/1
-> utp A01 -> panel patch-a/2 -> trunk st/2 -> panel
patch-b/6 -> utp B02

...which can be explored in the HTML view of the cable.
#
Each panel would have its own table of what things plug into its
ports, and what trunks link it to where, too.

### TASKS:

 * Generalise the notion of "cable" to "link" in the existing
   codebase, but with the current cable-parsing code as input; just
   modify the data model, rename classes, update the output renderers
   to handle links having different names at different attachments,
   and make everything work again. - DONE

 * Modify the input parser to create new panel, trunk group, and cable
   objects. A "trunk" is always identified as trunk group + label of
   the trunk within it, for easier management. - DONE

 * Add a phase, after parsing, to create links from the
   panels/trunks/cables it finds. - DONE

 * Extend the HTML renderer to display the detailed structure of links. - DONE

 * Extend the HTML renderer to display panels. - DONE

 * Add a third dot renderer that shows panels (rectangles) and trunk
   groups (thick lines), and devices (ovals) and cables (thin
   lines).

 * Document it - DONE

## Generalise device/cable types

PROGRESS: Cable+circuit types now come from a `CABLE_TYPES` dict in
network.py; provide an option to load more.

The core engine has a fixed list of device and cable types (and circuit
types?), even though it doesn't really care what they are. Front-end
scripts tend to care more, as they often invoke special rendering for
particular types of object.

Adding to this list involves extending the parser regexps, extending
the documentation, and then extending the various rendering scripts.

It might be nice to have a configuration file that lists all the types
of typable things, and then listing key=value properties for them. The
parser can generate its regexps from the lists, and then frontends can
look up keys to find styling information for specific types.

Make better use of more node shapes:

http://www.graphviz.org/doc/info/shapes.html

Also, make use of colour to better distinguish node and link types in
the graphviz outputs.

## Better rendering

Add an option to the dot generators, passing in an optional HTML
filename; if present, then an image map is created, linking objects in
the diagrams to the corresponding objects in the HTML report.

Add an option to generate a graph of the cables and trunks forming a
link which, when image-mapped, can be included in the HTML
documentation, for each link. Or find some other way to graph the
potentially complex interconnections of trunks and cables in a link.

## Minor issues

* Add support for multi-drop trunks. The core data structures support
  it, but the parser needs to be a little more sophisticated.

* Note the filename+line number of definition of all the objects, for
  ease of back-referencing. (How to display nicely in the HTML view?)

* Make ip4 reserved ranges appear as a single row in the IP4 displays
  in the HTML, rather than one per IP.

* Make it a proper installable Python thing where you do `python
  setup.py install`

* Make a list of stub addresses, and put a table of them in the ip4
  subnets section of the HTML report, as a special "others" subnet

* If an ip4 is declared on a device but there isn't a cable 'creating'
  that port on the device, create a port without any cables (and warn
  about it).

* Refactor the naming of `code`, `name`, and `title`
  fields. Standardise on `name` and `title`, most likely, for code
  name and full title.

* Normalise how owners and locations are handled; make `location`
  valid in any object (even trunks can be confined to a building), and
  have a generalised owner/location cross-referencing function that
  can be called on any array of objects with `name` and `location`
  properties, given the name of an array in the `organisation` and
  `location` objects to add objects to.

* Improve the CSS, to make table rows clearer, and better separation
  of top-level headings between objects in the main pane.

Changes to 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 telephone virtual < $INPUT > $TMP_NETWORK_CABLES
python make-network-cabling-diagram.py power kvm serial usb 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









|



|









|
|
|


|




|
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_CIRCUITS=${BASENAME}_circuits.png
OUTPUT_NETWORK_CABLES=${BASENAME}_network_cables.png
OUTPUT_MANAGEMENT_CABLES=${BASENAME}_management_cables.png
TMPDIR=/tmp/tangle-run-$$
TMP_CIRCUITS=$TMPDIR/circuits.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-circuit-diagram.py < $INPUT > $TMP_CIRCUITS
python make-network-cabling-diagram.py ethernet telephone virtual < $INPUT > $TMP_NETWORK_CABLES
python make-network-cabling-diagram.py power kvm serial usb parallel < $INPUT > $TMP_MANAGEMENT_CABLES

echo "Rendering diagrams..."
neato -Tpng -o $OUTPUT_CIRCUITS $TMP_CIRCUITS
neato -Tpng -o $OUTPUT_NETWORK_CABLES $TMP_NETWORK_CABLES
neato -Tpng -o $OUTPUT_MANAGEMENT_CABLES $TMP_MANAGEMENT_CABLES

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

Changes to examples/home-lan.tangle.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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







|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

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








|











70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

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

wifi wireless-net {
	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"
}

Changes to examples/office-lan.tangle.

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
     ip4 subnet 192.168.3.0/24 "Internal servers"
}

vlan core.400 {
     title "Management"
     ip4 subnet 192.168.100.0/24 "Management"
}






# Server Room






## Core Network

device core-switch {
       type switch

       # This IP address is attached to the "management" port
       # of the switch, via a virtual cable (see below)
       ip4 management 192.168.100.10
       mac management 00:26:9e:25:70:27
}

virtual core-switch-mgmt {
	# Here we show how the management interface of a switch
	# works. It's a virtual cable with only one "end",
	# thereby assigning a VLAN to the port "management" on the switch.
	device core-switch/management
	vlan core.400
}

device hades {
       type router

       note "Cisco 2800"
       note "Border router"
       ip4 loopback 123.123.123.8 stub
       ip4 internal core.210 123.123.123.17
       mac internal core.210 f2:0b:a4:c9:c1:0d
       ip4 internal core.220 123.123.123.33
       mac internal core.220 f2:0b:a4:c9:c1:0d








>
>
>
>
>

>
>
>
>
>





>
















>







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
     ip4 subnet 192.168.3.0/24 "Internal servers"
}

vlan core.400 {
     title "Management"
     ip4 subnet 192.168.100.0/24 "Management"
}

location main-building {
	 title "Main building"
	 address postal "123 Any Street, Any Town, Any Country, Earth"
}

# Server Room

location server-room {
	 title "Server room"
	 location main-building
}

## Core Network

device core-switch {
       type switch
       location server-room
       # This IP address is attached to the "management" port
       # of the switch, via a virtual cable (see below)
       ip4 management 192.168.100.10
       mac management 00:26:9e:25:70:27
}

virtual core-switch-mgmt {
	# Here we show how the management interface of a switch
	# works. It's a virtual cable with only one "end",
	# thereby assigning a VLAN to the port "management" on the switch.
	device core-switch/management
	vlan core.400
}

device hades {
       type router
       location server-room
       note "Cisco 2800"
       note "Border router"
       ip4 loopback 123.123.123.8 stub
       ip4 internal core.210 123.123.123.17
       mac internal core.210 f2:0b:a4:c9:c1:0d
       ip4 internal core.220 123.123.123.33
       mac internal core.220 f2:0b:a4:c9:c1:0d
101
102
103
104
105
106
107

108
109
110
111
112
113
114
      vlan core.100
}

device bovril {
       type firewall
       note "Cisco ASA"
       note "Firewall"

       note "Provides DHCP to 192.168.2.1 on core.310"
       ip4 external 123.123.123.18
       mac external 00:c4:12:3e:e3:01
       ip4 internal core.300 192.168.1.254
       mac internal core.300 00:c4:12:3e:e3:01
       ip4 internal core.310 192.168.2.1
       mac internal core.310 00:c4:12:3e:e3:01







>







113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
      vlan core.100
}

device bovril {
       type firewall
       note "Cisco ASA"
       note "Firewall"
       location server-room
       note "Provides DHCP to 192.168.2.1 on core.310"
       ip4 external 123.123.123.18
       mac external 00:c4:12:3e:e3:01
       ip4 internal core.300 192.168.1.254
       mac internal core.300 00:c4:12:3e:e3:01
       ip4 internal core.310 192.168.2.1
       mac internal core.310 00:c4:12:3e:e3:01
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
    tagged vlans core.300,core.310,core.320,core.400
}

## External Servers

device alice {
       type server

       note "Web/mail server"
       ip4 eth0 123.123.123.34
}

utp 004 {
    device alice/eth0
    device core-switch/4
    vlan  core.220
}

## Internal Servers

device internal-switch {
       type switch

       ip4 management 192.168.100.11
       mac management 00:c4:12:4f:08:12
}

virtual internal-switch-mgmt {
	device internal-switch/management
	vlan core.400
}

utp 005 {
    device core-switch/5
    device internal-switch/1
    tagged vlans core.320,core.400,core.310,core.300
}

device boris {
       type server

       note "Workgroup Fileserver"
       ip4 eth0 192.168.3.10
}

utp i002 {
    device internal-switch/2
    device boris/eth0
    vlan core.320
}

device keith {
       type server

       note "VM host"
       ip4 eth0 192.168.3.12
       hosts build-linux
       hosts build-freebsd
}

utp i003 {







>














>

















>












>







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
    tagged vlans core.300,core.310,core.320,core.400
}

## External Servers

device alice {
       type server
       location server-room
       note "Web/mail server"
       ip4 eth0 123.123.123.34
}

utp 004 {
    device alice/eth0
    device core-switch/4
    vlan  core.220
}

## Internal Servers

device internal-switch {
       type switch
       location server-room
       ip4 management 192.168.100.11
       mac management 00:c4:12:4f:08:12
}

virtual internal-switch-mgmt {
	device internal-switch/management
	vlan core.400
}

utp 005 {
    device core-switch/5
    device internal-switch/1
    tagged vlans core.320,core.400,core.310,core.300
}

device boris {
       type server
       location server-room
       note "Workgroup Fileserver"
       ip4 eth0 192.168.3.10
}

utp i002 {
    device internal-switch/2
    device boris/eth0
    vlan core.320
}

device keith {
       type server
       location server-room
       note "VM host"
       ip4 eth0 192.168.3.12
       hosts build-linux
       hosts build-freebsd
}

utp i003 {
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
virtual keith-vswitch {
	device build-linux/eth0
	device build-freebsd/rtk0
	device keith/vif0
	vlan core.320
}

device laserjet {
       type printer
       ip4 ethernet 192.168.3.20
       mac ethernet 00:00:24:c3:8a:1c
}

utp i004 {
    device internal-switch/4
    device laserjet/ethernet
    vlan core.320
}

## Power management

device pdu1 {
       type manager

       ip4 ethernet 192.168.100.5
       mac ethernet 00:00:24:c2:44:9f
}

utp i007 {
    device internal-switch/7
    device pdu1/ethernet







<
<
<
<
<
<










>







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
virtual keith-vswitch {
	device build-linux/eth0
	device build-freebsd/rtk0
	device keith/vif0
	vlan core.320
}







utp i004 {
    device internal-switch/4
    device laserjet/ethernet
    vlan core.320
}

## Power management

device pdu1 {
       type manager
       location server-room
       ip4 ethernet 192.168.100.5
       mac ethernet 00:00:24:c2:44:9f
}

utp i007 {
    device internal-switch/7
    device pdu1/ethernet
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
      device exchange/ac
}

## Phone system

device exchange {
       type router

       note "Telephone local exchange unit"
       ip4 voip 123.123.123.35
}

utp i008 {
    device internal-switch/8
    device exchange/management
    vlan core.400
}

utp i009 {
    device internal-switch/9
    device exchange/voip
    vlan core.220
}

# Main Office













device office-switch {
       type switch

       ip4 management 192.168.100.12
       mac management 00:e0:81:2c:4d:43
}

virtual office-switch-mgmt {
	device office-switch/management
	vlan core.400
}

utp i005 {
    device internal-switch/5
    device office-switch/48
    tagged vlans core.400,core.320
}

## Workstations

device pc001 {
       type workstation

       ip4 eth 192.168.1.1
}

utp o001 {
      device pc001/eth
      device office-switch/1
      vlan core.300
}

device pc002 {
       type workstation

       ip4 eth 192.168.1.2
}

utp o002 {
      device pc002/eth
      device office-switch/2
      vlan core.300
}

device pc003 {
       type workstation

       ip4 eth 192.168.1.3
}

utp o003 {
      device pc003/eth
      device office-switch/3
      vlan core.300
}

device pc004 {
       type workstation

       ip4 eth 192.168.1.4
}

utp o004 {
      device pc004/eth
      device office-switch/4
      vlan core.300
}

device pc005 {
       type workstation

       ip4 eth 192.168.1.5
}

utp o005 {
      device pc005/eth
      device office-switch/5
      vlan core.300
}

device pc006 {
       type workstation

       ip4 eth 192.168.1.6
}

utp o006 {
      device pc006/eth
      device office-switch/6
      vlan core.300
}

device pc007 {
       type workstation

       ip4 eth 192.168.1.7
}

utp o007 {
      device pc007/eth
      device office-switch/7
      vlan core.300
}

device pc008 {
       type workstation

       ip4 eth 192.168.1.8
}

utp o008 {
      device pc008/eth
      device office-switch/8
      vlan core.300
}

device pc009 {
       type workstation

       ip4 eth 192.168.1.9
}

utp o009 {
      device pc009/eth
      device office-switch/9
      vlan core.300
}

device pc010 {
       type workstation

       ip4 eth 192.168.1.10
}

utp o010 {
      device pc010/eth
      device office-switch/10
      vlan core.300
}

## Wifi

device wifi-bridge {
       type other

       ip4 ethernet core.400 192.168.100.20
}

virtual wifi {
	device wifi-bridge/wifi
	vlan core.310
}

utp i006 {
    device wifi-bridge/ethernet
    device internal-switch/6
    tagged vlans core.400,core.310
}

## Phones

device phone001 {
       type telephone

}

telephone p001 {
	  device exchange/1
	  device phone001/tel
	  vlan phones
}

device phone002 {
       type telephone

}

telephone p002 {
	  device exchange/2
	  device phone002/tel
	  vlan phones
}

device phone003 {
       type telephone

}

telephone p003 {
	  device exchange/3
	  device phone003/tel
	  vlan phones
}

device phone004 {
       type telephone

}

telephone p004 {
	  device exchange/4
	  device phone004/tel
	  vlan phones
}

device phone005 {
       type telephone

}

telephone p005 {
	  device exchange/5
	  device phone005/tel
	  vlan phones
}

device phone006 {
       type telephone

}

telephone p006 {
	  device exchange/6
	  device phone006/tel
	  vlan phones
}

device phone007 {
       type telephone

}

telephone p007 {
	  device exchange/7
	  device phone007/tel
	  vlan phones
}

device phone008 {
       type telephone

}

telephone p008 {
	  device exchange/8
	  device phone008/tel
	  vlan phones
}

device phone009 {
       type telephone

}

telephone p009 {
	  device exchange/9
	  device phone009/tel
	  vlan phones
}

device phone010 {
       type telephone

}

telephone p010 {
	  device exchange/10
	  device phone010/tel
	  vlan phones
}







>

















>
>
>
>
>
>
>
>
>
>
>
>



>



















>











>











>











>











>











>











>











>











>











>













>


















>










>










>










>










>










>










>










>










>










>







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
      device exchange/ac
}

## Phone system

device exchange {
       type router
       location server-room
       note "Telephone local exchange unit"
       ip4 voip 123.123.123.35
}

utp i008 {
    device internal-switch/8
    device exchange/management
    vlan core.400
}

utp i009 {
    device internal-switch/9
    device exchange/voip
    vlan core.220
}

# Main Office

location office {
	 title "Main office"
	 location main-building
}

device laserjet {
       type printer
       location office
       ip4 ethernet 192.168.3.20
       mac ethernet 00:00:24:c3:8a:1c
}

device office-switch {
       type switch
       location office
       ip4 management 192.168.100.12
       mac management 00:e0:81:2c:4d:43
}

virtual office-switch-mgmt {
	device office-switch/management
	vlan core.400
}

utp i005 {
    device internal-switch/5
    device office-switch/48
    tagged vlans core.400,core.320
}

## Workstations

device pc001 {
       type workstation
       location office
       ip4 eth 192.168.1.1
}

utp o001 {
      device pc001/eth
      device office-switch/1
      vlan core.300
}

device pc002 {
       type workstation
       location office
       ip4 eth 192.168.1.2
}

utp o002 {
      device pc002/eth
      device office-switch/2
      vlan core.300
}

device pc003 {
       type workstation
       location office
       ip4 eth 192.168.1.3
}

utp o003 {
      device pc003/eth
      device office-switch/3
      vlan core.300
}

device pc004 {
       type workstation
       location office
       ip4 eth 192.168.1.4
}

utp o004 {
      device pc004/eth
      device office-switch/4
      vlan core.300
}

device pc005 {
       type workstation
       location office
       ip4 eth 192.168.1.5
}

utp o005 {
      device pc005/eth
      device office-switch/5
      vlan core.300
}

device pc006 {
       type workstation
       location office
       ip4 eth 192.168.1.6
}

utp o006 {
      device pc006/eth
      device office-switch/6
      vlan core.300
}

device pc007 {
       type workstation
       location office
       ip4 eth 192.168.1.7
}

utp o007 {
      device pc007/eth
      device office-switch/7
      vlan core.300
}

device pc008 {
       type workstation
       location office
       ip4 eth 192.168.1.8
}

utp o008 {
      device pc008/eth
      device office-switch/8
      vlan core.300
}

device pc009 {
       type workstation
       location office
       ip4 eth 192.168.1.9
}

utp o009 {
      device pc009/eth
      device office-switch/9
      vlan core.300
}

device pc010 {
       type workstation
       location office
       ip4 eth 192.168.1.10
}

utp o010 {
      device pc010/eth
      device office-switch/10
      vlan core.300
}

## Wifi

device wifi-bridge {
       type other
       location office
       ip4 ethernet core.400 192.168.100.20
}

virtual wifi {
	device wifi-bridge/wifi
	vlan core.310
}

utp i006 {
    device wifi-bridge/ethernet
    device internal-switch/6
    tagged vlans core.400,core.310
}

## Phones

device phone001 {
       type telephone
       location office
}

telephone p001 {
	  device exchange/1
	  device phone001/tel
	  vlan phones
}

device phone002 {
       type telephone
       location office
}

telephone p002 {
	  device exchange/2
	  device phone002/tel
	  vlan phones
}

device phone003 {
       type telephone
       location office
}

telephone p003 {
	  device exchange/3
	  device phone003/tel
	  vlan phones
}

device phone004 {
       type telephone
       location office
}

telephone p004 {
	  device exchange/4
	  device phone004/tel
	  vlan phones
}

device phone005 {
       type telephone
       location office
}

telephone p005 {
	  device exchange/5
	  device phone005/tel
	  vlan phones
}

device phone006 {
       type telephone
       location office
}

telephone p006 {
	  device exchange/6
	  device phone006/tel
	  vlan phones
}

device phone007 {
       type telephone
       location office
}

telephone p007 {
	  device exchange/7
	  device phone007/tel
	  vlan phones
}

device phone008 {
       type telephone
       location office
}

telephone p008 {
	  device exchange/8
	  device phone008/tel
	  vlan phones
}

device phone009 {
       type telephone
       location office
}

telephone p009 {
	  device exchange/9
	  device phone009/tel
	  vlan phones
}

device phone010 {
       type telephone
       location office
}

telephone p010 {
	  device exchange/10
	  device phone010/tel
	  vlan phones
}

Changes to make-network-cabling-diagram.py.

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
      elif deviceType == "telephone":
         print "device%s [shape=\"diamond\" 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)







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











|


|
|

<
<

|


|

|

|

|


|


<
|


|




|
|
|
|

|


|


|
|
|

|

|

|
|

|












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
      elif deviceType == "telephone":
         print "device%s [shape=\"diamond\" 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 "// Locations"
   print

   for locName in cabling.locations:
      loc = cabling.locations[locName]
      if loc.location == None:
         # It's a root
         def declareSubgraph(loc):
            print "subgraph cluster%s {" % makeName(loc.code)
            print "label=\"%s\"" % loc.name
            for dev in loc.devices:
               print "device%s" % makeName(dev.name)
            for subloc in loc.locations:
               declareSubgraph(subloc)
            print "}"
         declareSubgraph(loc)

   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 "// Links"
   print
   
   def linkStyle(circuitType):
      if circuitType == "ethernet":
         return ""



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

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

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


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

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

      else:
         return ""

   for linkName in cabling.links:
      link = cabling.links[linkName]
      circuitType = network.getCircuitType(link.cableType)
      
      if filterSet != [] and circuitType not in filterSet:
         continue

      if circuitType == "unused" or len(link.devices)<2:
         continue
         
      if len(link.devices) == 2:
         (deviceName0,port0,cable0) = link.devices[0]
         (deviceName1,port1,cable1) = link.devices[1]
         
         print "device%s -- device%s [taillabel=\"%s\" label=\"%s\" headlabel=\"%s\" %s];" % (makeName(deviceName0), makeName(deviceName1), port0, linkName, port1, linkStyle(circuitType))
      else:
         print "link%s [label=\"%s\"];" % (makeName(linkName),linkName)
      
         for link in link.devices:
            (deviceName,port,cable) = link
         
            print "link%s -- device%s [headlabel=\"%s\" %s];" % (makeName(linkName), makeName(deviceName), port, linkStyle(circuitType))
         
   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-circuit-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

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 printCircuitDiagram (cabling):
   print "graph circuits {"
   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 "// Locations"
   print

   for locName in cabling.locations:
      loc = cabling.locations[locName]
      if loc.location == None:
         # It's a root
         def declareSubgraph(loc):
            print "subgraph cluster%s {" % makeName(loc.code)
            print "label=\"%s\"" % loc.name
            for dev in loc.devices:
               print "device%s" % makeName(dev.name)
            for subloc in loc.locations:
               declareSubgraph(subloc)
            print "}"
         declareSubgraph(loc)

   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 "// Circuits"
   print

   for circuitName in cabling.circuits:
      circuit = cabling.circuits[circuitName]

      print "circuit%s [label=\"%s\"];" % (makeName(circuitName),circuitName)

      for link in circuit.ports:
         (deviceName,port,link) = link

         deviceType = cabling.devices[deviceName].deviceType
         cableType = cabling.links[link.name].cableType

         # Only show switches if this is a virtual link, eg their admin port
         if cableType == "virtual":
            print "circuit%s -- device%s [headlabel=\"%s\" style=\"dotted\"];" % (makeName(circuitName), makeName(deviceName), port)
         else:
            if deviceType == "switch":
               pass # ignore non-virtual links to switches, it just clutters stuff
            else:
               print "circuit%s -- device%s [headlabel=\"%s\"];" % (makeName(circuitName), makeName(deviceName), port)


   print "}"

# 1) Load and process configration

cabling = network.loadCabling (sys.stdin)

# 2) Print it out nicely

printCircuitDiagram (cabling)

Changes to 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
#
# 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-macs\">MACs</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()

   macNames = cabling.macs.keys()
   macNames.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:

|





>










|
|
>
>




>







|
|

|
|









>
>
>
>
>
>
>
>
>







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
#
# List all the ports on all the devices, documenting what cable is plugged into each, then do the same for circuits, 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-circuits\">Circuits</a>"
   print "<a href=\"#nav-links\">Links</a><br>"
   print "<a href=\"#nav-panels\">Patch Panels</a><br>"
   print "<a href=\"#nav-trunkgroups\">Trunk Groups</a><br>"
   print "<a href=\"#nav-unused\">Unused Ports</a>"
   print "<a href=\"#nav-ip4subnets\">IP4</a>"
   print "<a href=\"#nav-macs\">MACs</a>"
   print "<a href=\"#nav-orgs\">Organisations</a>"
   print "<a href=\"#nav-locs\">Locations</a>"
   print "</div>"

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

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

   circuitNames = cabling.circuits.keys()
   circuitNames.sort()

   linkNames = cabling.links.keys()
   linkNames.sort()

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

   macNames = cabling.macs.keys()
   macNames.sort()

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

   locNames = cabling.locations.keys()
   locNames.sort()

   panelNames = cabling.panels.keys()
   panelNames.sort()

   trunkGroupNames = cabling.trunkGroups.keys()
   trunkGroupNames.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:
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
         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]







|


|
|


|


|
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>





|
|
|







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
         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-circuits\">Circuits</h2>"

   print "<ul>"
   for circuitName in circuitNames:
      print "<li><a href=\"#circuit-%s\">%s</a></li>" % (circuitName,cabling.circuits[circuitName])
   print "</ul>"

   print "<h2 id=\"nav-links\">Links</h2>"

   print "<ul>"
   for linkName in linkNames:
      if cabling.links[linkName].cableType != "unused":
         print "<li><a href=\"#link-%s\">%s</a> %s</li>" % (linkName,linkName,cabling.links[linkName].cableType)
   print "</ul>"

   print "<h2 id=\"nav-panels\">Patch Panels</h2>"

   print "<ul>"
   for panelName in panelNames:
      print "<li><a href=\"#panel-%s\">%s</a></li>" % (panelName,panelName)
   print "</ul>"

   print "<h2 id=\"nav-trunkgroups\">Trunk Groups</h2>"

   print "<ul>"
   for trunkGroupName in trunkGroupNames:
      print "<li><a href=\"#trunkgroup-%s\">%s</a></li>" % (trunkGroupName,trunkGroupName)
   print "</ul>"

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

   print "<ul>"
   for linkName in linkNames:
      if cabling.links[linkName].cableType == "unused":
         print "<li><a href=\"#link-%s\">%s</a></li>" % (linkName,linkName)
   print "</ul>"

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

   print "<ul>"
   for subnetName in subnetNames:
      subnet = cabling.ip4subnets[subnetName]
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

   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
      macs = device.macs










      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)

         # Let's map vlan names to pairs ([macs],[ip4s])
         port_vlans = {}

#         print >> sys.stderr, "%s MACS: %r IP4s: %r" % (device,macs,ip4s)

         if macs.has_key(port):
            for mac in macs[port]:
               if mac.vlan == None:
                  vlan = False
               else:
                  vlan = mac.vlan

               if not port_vlans.has_key(vlan):
                  port_vlans[vlan] = ([],[])
               port_vlans[vlan][0].append(mac)

         if ip4s.has_key(port):
            for ip4 in ip4s[port]:
               if ip4.vlan == None:
                  vlan = False
               else:
                  vlan = ip4.vlan

               if not port_vlans.has_key(vlan):
                  port_vlans[vlan] = ([],[])
               port_vlans[vlan][1].append(ip4)


         for vlan in port_vlans:
            (port_macs,port_ip4s) = port_vlans[vlan]
            first = True

            for mac in port_macs:
               if first:
                  if vlan == False:
                     print "<tr class=\"dev-ip4\"><td><i>unspecified vlan</i></td>"
                  else:
                     print "<tr class=\"dev-ip4\"><td>vlan <a href=\"#vlan-%s\">%s</a></td>" % (vlan,cabling.vlans[vlan])
                  first = False
               else:
                  print "<tr class=\"dev-mac\"><td></td>"

               print "<td>MAC <tt>%s</tt>" % mac.mac
               if mac.shared:
                  print "<i>(shared)</i>"
               print "</td></tr>"

            for ip4 in port_ip4s:
               if first:
                  if vlan == False:
                     print "<tr class=\"dev-ip4\"><td><i>unspecified vlan</i></td>"
                  else:
                     print "<tr class=\"dev-ip4\"><td>vlan <a href=\"#vlan-%s\">%s</a></td>" % (vlan,cabling.vlans[vlan])

                  first = False
               else:
                  print "<tr class=\"dev-ip4\"><td></td>"

               print "<td>IP4 "

               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:








|

|
|
|
|
>
>
>
>
>
|
|
>
>
>
>
|
>
|
>











>
>
>


















>
>
>
>
>
>
>
>
>




|
|
|

|

|


|

|
|
|
|





|

|
|








|

|
|





|
|

|

|
|
|



|
|

|

|
|
|


|
|




|
|

|











|
|

|







|






|







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

   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 "<h2 id=\"nav-locs\">Locations</h2>"

   # Express the hierarchy
   def listChildLocations(locations):
      if len(locations) > 0:
         print "<ul>"
         for loc in locations:
            print "<li><a href=\"#loc-%s\">%s</a>" % (loc.code,loc)
            listChildLocations(loc.locations)
            print "</li>"
         print "</ul>"

   print "<ul>"
   for locName in locNames:
      if cabling.locations[locName].location == None:
         print "<li><a href=\"#loc-%s\">%s</a>" % (locName,cabling.locations[locName])
         listChildLocations(cabling.locations[locName].locations)
         print "</li>"
   print "</ul>"

   print "</div>"

   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 device.location:
         print "<p>Location: <a href=\"#loc-%s\">%s</a></p>" % (device.location, cabling.locations[device.location])

      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
      macs = device.macs

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

      ports.sort(portcmp)

      print "<table class=\"device\">"
      for portData in ports:
         (port,link) = portData
         print "<tr class=\"dev-hdr\" id=\"%s-%s\"><td>port <b>%s</b></td><td>%s <a href=\"#link-%s\">%s</a></td></th>" % (deviceName,port,port,link.cableType, link.name,link.name)
         if link.tagged == True:
            first = True
            for circuit in link.circuits:
               if first:
                  print "<tr class=\"dev-circuits\"><td>Tagged Circuits</td>"
                  first = False
               else:
                  print "<tr class=\"dev-circuits\"><td></td>"

               print "<td><a href=\"#circuit-%s\">%s</a></td></tr>" % (circuit,cabling.circuits[circuit])
         elif link.tagged == False:
            print "<tr class=\"dev-circuits\"><td>Circuit</td><td>"
            print "<a href=\"#circuit-%s\">%s</a>" % (link.circuit,cabling.circuits[link.circuit])
            print "</td></tr>"
         else:
            # Not Ethernet
            pass

         if len(link.devices)>1 and link.cableType != "unused":
            first = True
            for oDevice in link.devices:
               (oDevName,oDevPort,oDevCable) = 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> via %s</td></tr>" % (oDevName, oDevPort, oDevName, oDevPort, oDevCable)

         # Let's map circuit names to pairs ([macs],[ip4s])
         port_circuits = {}

#         print >> sys.stderr, "%s MACS: %r IP4s: %r" % (device,macs,ip4s)

         if macs.has_key(port):
            for mac in macs[port]:
               if mac.circuit == None:
                  circuit = False
               else:
                  circuit = mac.circuit

               if not port_circuits.has_key(circuit):
                  port_circuits[circuit] = ([],[])
               port_circuits[circuit][0].append(mac)

         if ip4s.has_key(port):
            for ip4 in ip4s[port]:
               if ip4.circuit == None:
                  circuit = False
               else:
                  circuit = ip4.circuit

               if not port_circuits.has_key(circuit):
                  port_circuits[circuit] = ([],[])
               port_circuits[circuit][1].append(ip4)


         for circuit in port_circuits:
            (port_macs,port_ip4s) = port_circuits[circuit]
            first = True

            for mac in port_macs:
               if first:
                  if circuit == False:
                     print "<tr class=\"dev-ip4\"><td><i>unspecified circuit</i></td>"
                  else:
                     print "<tr class=\"dev-ip4\"><td>circuit <a href=\"#circuit-%s\">%s</a></td>" % (circuit,cabling.circuits[circuit])
                  first = False
               else:
                  print "<tr class=\"dev-mac\"><td></td>"

               print "<td>MAC <tt>%s</tt>" % mac.mac
               if mac.shared:
                  print "<i>(shared)</i>"
               print "</td></tr>"

            for ip4 in port_ip4s:
               if first:
                  if circuit == False:
                     print "<tr class=\"dev-ip4\"><td><i>unspecified circuit</i></td>"
                  else:
                     print "<tr class=\"dev-ip4\"><td>circuit <a href=\"#circuit-%s\">%s</a></td>" % (circuit,cabling.circuits[circuit])

                  first = False
               else:
                  print "<tr class=\"dev-ip4\"><td></td>"

               print "<td>IP4 "

               if ip4.circuit == None:
                  print "%s" % (network.unparse_ip(ip4.ip))
               else:
                  subnetFound = False

                  for snName in cabling.ip4subnets:
                     sn = cabling.ip4subnets[snName]
                     if ip4.circuit == sn.circuit:
                        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:
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
            print "<tr><th id=\"mac-%s\"><tt>%s</tt></th>" % (mac,mac)
            first = False
         else:
            print "<tr><td></td>"
         
         print "<td><a href=\"#%s-%s\">%s/%s</a>" % (macport.device, macport.port, macport.device, macport.port)

         if macport.vlan != None:
            print "(<a href=\"#vlan-%s\">vlan %s</a>)" % (macport.vlan, macport.vlan)

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







|
|





|

|
|

|

|




|




|

|
|

|

|
|

|
|
|
|









|
|


>
>
>
|
|
|
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
|

|

>
|
>
|



|


<
<
<
<
<
<
<
<
<
<
|

|
|
|
|
|
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|

|
|
|
|








|







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
            print "<tr><th id=\"mac-%s\"><tt>%s</tt></th>" % (mac,mac)
            first = False
         else:
            print "<tr><td></td>"
         
         print "<td><a href=\"#%s-%s\">%s/%s</a>" % (macport.device, macport.port, macport.device, macport.port)

         if macport.circuit != None:
            print "(<a href=\"#circuit-%s\">circuit %s</a>)" % (macport.circuit, macport.circuit)

         print "</td></tr>"

   print "</table>"

   print "<h1>Circuits</h1>"

   for circuitName in circuitNames:
      circuitLinks = cabling.circuits[circuitName].ports

      print "<h2 id=\"circuit-%s\">Circuit %s (%s)</h2>" % (circuitName, cabling.circuits[circuitName], cabling.circuits[circuitName].circuitType)

      for note in cabling.circuits[circuitName].notes:
         print "<p>%s</p>" % note

      print "<ul>"

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

      print "</ul>"

      print "<table class=\"circuit\">"

      # Sort by link then device then port
      circuitLinks.sort(lambda a,b: cmp("%s/%s/%s" % (a[2],a[0],a[1]), "%s/%s/%s" % (b[2],b[0],b[1])))

      lastLink = None

      for circuitLink in circuitLinks:
         (dev,port,cable) = circuitLink

         if link != lastLink:
            print "<tr class=\"circuit-link-hdr\">"
            print "<th>%s <a href=\"#link-%s\">%s</a></th>" % (link.cableType, link.name,link.name)
            lastLink = link
         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 documentLink(linkName,link,showCircuits):
      print "<tr id=\"link-%s\"><th>%s</th>" % (linkName, link)

      print "<td>"

      print "<ul>"
      if len (link.cables) == 1:
         for device in link.devices:
            (dev,port,cable) = device
            print "<li>device <a href=\"#%s-%s\">%s/%s</a></li>" % (dev,port,dev,port)
         for (panel,port,cable) in link.panels:
            print "<li>panel <a href=\"#panel%s-%s\">%s/%s</a></li>" % (panel,port,panel,port)

      else:
         for device in link.devices:
            (dev,port,cable) = device
            print "<li>device <a href=\"#%s-%s\">%s/%s</a> on %s</li>" % (dev,port,dev,port,cabling.cables[cable])
         for (panel,port,cable) in link.panels:
            print "<li>panel <a href=\"#panel%s-%s\">%s/%s</a> on %s</li>" % (panel,port,panel,port,cabling.cables[cable])

         for cable in link.cables:
            if len(cable.notes) == 0:
               print "<li>%s</li>" % cable
            else:
               print "<li>%s (%s)</li>" % (cable, ", ".join(cable.notes))

      print "</ul>"

      print "</td>"

      if showCircuits:
         if link.tagged == None:
            print "<td></td>"
         elif link.tagged:
            print "<td>"
            print "<p>Tagged:</p><ul>"
            for circuit in link.circuits:
               print "<li><a href=\"#circuit-%s\">%s</a></li>" % (circuit,circuit)
            print "</ul>"

            print "</td>"
         else:
            print "<td><a href=\"#circuit-%s\">%s</a></td>" % (link.circuit,link.circuit)
         print "</tr>"











   print "<h1>Links</h1>"

   print "<table class=\"links\">"
   print "<tr><th>Link</th><th>Connections</th><th>Circuits</th></tr>"
   for linkName in linkNames:
      link = cabling.links[linkName]
      if link.cableType != "unused":
         documentLink(linkName, link, True)

   print "</table>"

   print "<h1>Patch Panels</h1>"
   for panelName in panelNames:
      panel = cabling.panels[panelName]
      print "<h2 id=\"panel-%s\">%s</h2>" % (panelName, panel.title)

      print "<p>Owner: <a href=\"#org-%s\">%s</a></p>" % (panel.owner.code,panel.owner.name)

      if panel.location:
         print "<p>Location: <a href=\"#loc-%s\">%s</a></p>" % (panel.location, cabling.locations[panel.location])

      for note in panel.notes:
         print "<p>%s</p>" % note

      def panelportcmp(a,b):
         if numberRE.match(a) and numberRE.match(b):
            return cmp(int(a),int(b))
         else:
            return cmp(a,b)

      ports = list(set(panel.trunks.keys()) | set(panel.cables.keys()))
      ports.sort(panelportcmp)

      print "<table>"
      print "<tr><th>Port</th><th>Cable</th><th>Trunk</th><th>Link</th></tr>"
      for port in ports:
         print "<tr><th id=\"panel-%s-%s\">%s</th>" % (panelName, port, port)
         link = None

         if panel.cables.has_key(port):
            cable = panel.cables[port]
            if len(cable.devices)+len(cable.panels) == 1:
               print "<td>%s (dangling)</td>" % cable
            else:
               print "<td>%s to (" % cable
               for (device,port2) in cable.devices:
                  print "<a href=\"#%s-%s\">%s/%s</a> " % (device, port2, device, port2)
               for (panel2,port2) in cable.panels:
                  if panel2 == panelName and port2 == port:
                     pass
                  else:
                     print "<a href=\"#panel-%s-%s\">%s/%s</a> " % (panel2, port2, panel2, port2)
               print ")</td>"

            link = cable.link
         else:
            print "<td></td>"

         if panel.trunks.has_key(port):
            trunk = panel.trunks[port]
            print "<td><a href=\"#trunkgroup-%s-%s\">%s/%s</a> to (" % (trunk.trunkGroup, trunk.trunkGroupLabel, trunk.trunkGroup, trunk.trunkGroupLabel)
            for (panel2,port2) in trunk.panels:
               if panel2 == panelName and port2 == port:
                  pass
               else:
                  print "<a href=\"#panel-%s-%s\">%s/%s</a> " % (panel2, port2, panel2, port2)
            print ")</td>"
            link = trunk.link
         else:
            print "<td></td>"

         if link != None:
            print "<td><a href=\"#link-%s\">%s</a></td>" % (link.name,link)
         else:
            print "<td></td>"
         print "</tr>"
      print "</table>"

   print "<h1>Trunk Groups</h1>"
   for trunkGroupName in trunkGroupNames:
      trunkGroup = cabling.trunkGroups[trunkGroupName]
      print "<h2 id=\"trunkgroup-%s\">%s (%s)</h2>" % (trunkGroupName, trunkGroup.title, trunkGroup.cableType)

      for note in trunkGroup.notes:
         print "<p>%s</p>" % note

      print "<table>"
      print "<tr><th>Trunk</th><th>Endpoints</th></tr>"
      for trunk in trunkGroup.trunks:
         print "<tr><th id=\"trunkgroup-%s-%s\">%s/%s</th><td>" % (trunkGroupName, trunk.trunkGroupLabel, trunkGroupName, trunk.trunkGroupLabel)
         for (panel,port) in trunk.panels:
            print "<a href=\"panel-%s-%s\">%s/%s</a>" % (panel, port, panel, port)

         print "</td></tr>"
      print "</table>"

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

   print "<table class=\"links\">"
   print "<tr><th>Group</th><th>Ports</th></tr>"
   for linkName in linkNames:
      link = cabling.links[linkName]
      if link.cableType == "unused":
         documentLink(linkName, link, False)

   print "</table>"

   print "<h1>IP4 Subnets</h1>"

   for subnetName in subnetNames:
      subnet = cabling.ip4subnets[subnetName]

      print "<h2 id=\"subnet-%s\">%s on circuit <a href=\"#circuit-%s\">%s</a>" % (subnet.id,network.unparse_ip(subnet.net), subnet.circuit, cabling.circuits[subnet.circuit])
      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))
468
469
470
471
472
473
474







































475
476
477
478
479
480
481
482
483
484
485
486
            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)







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












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
            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 "<h3>Owned Locations</h3>"
      print "<ul>"
      for location in org.locations:
         print "<li><a href=\"#loc-%s\">%s</a></li>" % (location.code, location.name)
      print "</ul>"

   print "<h1>Locations</h1>"

   for locName in locNames:
      loc = cabling.locations[locName]
      if loc.name != loc.code:
         print "<h2 id=\"loc-%s\">%s (%s)</h2>" % (loc.code, loc.name, loc.code)
      else:
         print "<h2 id=\"loc-%s\">%s</h2>" % (loc.code, loc.name)

      if loc.location:
         print "<p>Contained within <a href=\"#loc-%s\">%s</a>" % (loc.location, cabling.locations[loc.location])

      print "<p>Owner: <a href=\"#org-%s\">%s</a></p>" % (loc.owner.code,loc.owner.name)

      for note in loc.notes:
         print "<p>%s</p>" % note

      for addrType in loc.addresses:
         address = loc.addresses[addrType]
         print "<p>%s: %s</p>" % (addrType, address)

      print "<h3>Devices in this Location</h3>"
      print "<ul>"
      for device in loc.devices:
         print "<li><a href=\"#%s\">%s</a></li>" % (device.name, device.name)
      print "</ul>"

      print "<h3>Locations within this Location</h3>"
      print "<ul>"
      for subloc in loc.locations:
         print "<li><a href=\"#loc-%s\">%s</a></li>" % (subloc.code, subloc.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)

Deleted 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 cableType == "virtual":
            print "vlan%s -- device%s [headlabel=\"%s\" style=\"dotted\"];" % (makeName(vlanName), makeName(deviceName), port)
         else:
            if deviceType == "switch":
               pass # ignore non-virtual cables to switches, it just clutters stuff
            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)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































Changes to 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

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 = []
      self.macs = {} # MAC -> list of MacPort objects

   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.macs = {} # 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 MacPort:
   # A MAC address on a port
   # Optionally specific to a VLAN on that port

   def __init__(self,vlan,device,port,mac,shared):
      self.vlan = vlan
      self.device = device
      self.port = port
      self.mac = mac
      self.shared = shared

   def __repr__(self):
      return "%s on vlan %s" % (self.mac,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,macs,ip4subnets,organisations):
      self.cables = cables
      self.vlans = vlans

      self.devices = devices
      self.macs = macs # Dict mapping a mac address to a list of MacPort objects with that mac
      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 %s" % ip_str



<
<
<
<
<
<
<
<





|
>


>
>
>

>
>
>

|
|


>
|
>
>


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|















|





>



















>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|
|
|





|



|

|
|






|


|



|






|

















|

|
>




>
>
>







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

import sys
import re









class Cable:
   def __init__(self):
      self.cableType = None
      self.name = None
      self.devices = [] # All connected devices, as (dev,port) pairs
      self.panels = [] # All connected panels, as (panel,port) pairs
      self.tagged = None
      self.notes = []
      self.isTrunk = False
      self.trunkGroup = None
      self.trunkGroupLabel = None

      # Which link is this cable part of?
      self.link = None

      # Ethernet cables only
      self.circuit = None
      self.circuits = []

   def __repr__(self):
      if self.isTrunk:
         return "%s trunk %s" % (self.cableType, self.name)
      else:
         return "%s cable %s" % (self.cableType, self.name)
   pass

class Panel:
   def __init__(self, name):
      self.name = name
      self.title = name
      self.location = None
      self.owner = None
      self.notes = []
      self.trunks = {} # dict of port -> cable (in trunk groups)
      self.cables = {} # another dict of port -> cable (not in trunk groups)
      pass

   def __repr__(self):
      return self.name

class TrunkGroup:
   def __init__(self, cableType, name):
      self.name = name
      self.title = name
      self.notes = []
      self.cableType = cableType
      self.trunks = [] # Trunks are just Cables

   def __repr__(self):
      return self.name

class Link:
   def __init__(self):
      self.cableType = None
      self.name = None
      self.devices = [] # All connected devices, as (dev,port,cable) triples
      self.cables = [] # All composing cables, including trunks
      self.panels = [] # All connected panels, as (dev,port,cable) triples

      # Cables without a declared circuit have self.circuit == None
      # and self.tagged = false
      self.circuit = None # for single-circuit cables
      self.tagged = None # true for multi-circuit cables
      self.circuits = [] # for multi-circuit cables

   def __repr__(self):
      if len(self.cables) == 1:
         return "%s cable %s" % (self.cableType, self.name)
      else:
         return "%s link %s" % (self.cableType, self.name)
   pass

class Circuit:
   def __init__(self):
      self.name = None
      self.circuitType = None
      self.ports = [] # list of (device,port,cable) triples
      self.notes = []
      self.ip4subnets = []
      self.title = None
      self.ip4reservations = []
      self.macs = {} # MAC -> list of MacPort objects

   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,link) pairs
      self.notes = []
      self.ip4s = {} # indexed on port name
      self.macs = {} # indexed on port name
      self.deviceType = "server" # default
      self.owner = None
      self.location = 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 = []

      # Contained devices and locations
      self.devices = []
      self.panels = []
      self.locations = []

   def __repr__(self):
      return self.name

class Location:
   def __init__(self,code):
      self.code = code
      self.name = code
      self.owner = None
      self.location = None
      self.notes = []
      self.addresses = {}

      # Down-links to contained objects
      self.devices = []
      self.locations = []
      self.panels = []

   def __repr__(self):
      return self.name

class IP4Port:
   # An IP address on a port
   # Optionally specific to a Circuit on that port
   def __init__(self,circuit,ip,shared,stub):
      self.circuit = circuit
      self.ip = ip
      self.shared = shared
      self.stub = stub

   def __repr__(self):
      return "%s on circuit %s" % (unparse_ip(self.ip),self.circuit)

class MacPort:
   # A MAC address on a port
   # Optionally specific to a Circuit on that port

   def __init__(self,circuit,device,port,mac,shared):
      self.circuit = circuit
      self.device = device
      self.port = port
      self.mac = mac
      self.shared = shared

   def __repr__(self):
      return "%s on circuit %s" % (self.mac,self.circuit)

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

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

   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,links,circuits,devices,macs,ip4subnets,organisations,locations,panels,trunkGroups):
      self.cables = cables
      self.links = links
      self.circuits = circuits
      self.devices = devices
      self.macs = macs # Dict mapping a mac address to a list of MacPort objects with that mac
      self.ip4subnets = ip4subnets
      self.organisations = organisations
      self.locations = locations
      self.panels = panels
      self.trunkGroups = trunkGroups

# 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 %s" % ip_str
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
   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)?)")

   # mac <port> <vlan> <mac> [shared]
   macVlanRE = re.compile(r"mac +([^ ]+) +([^ ]+) +([^ ]+) *((shared)?)")

   # mac <port> <mac> [shared]
   macRE = re.compile(r"mac +([^ ]+) +([^ ]+) *((shared)?)")

   # 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:
                           m = macVlanRE.match(line)
                           if m:
                              if not device.macs.has_key(m.group(1)):
                                 device.macs[m.group(1)] = []

                              shared = m.group(4) == "shared"
                              device.macs[m.group(1)].append(MacPort(m.group(2),device.name,m.group(1),parse_mac(m.group(3)),shared))


                           else:
                              m = macRE.match(line)
                              if m:
                                 if not device.macs.has_key(m.group(1)):
                                    device.macs[m.group(1)] = []

                                 shared = m.group(3) == "shared"
                                 device.macs[m.group(1)].append(MacPort(None,device.name,m.group(1),parse_mac(m.group(2)),shared))

                              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:







>

|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






>
>
>

|




>
>
>
|
|

|
|















|
|




|
|




|
|
>
>
>
















>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
|










>
>
>
>
>
>
>
>
>









|




>
|











|
|
|
|
|

|
|
|

|
|
|
|
|

|
|
<
<
<
<
<
<
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
|
>
>
>
>
>
>
>
|
>

>
>
>
>
|
>
|
|
>
>
>
>
>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>

>
>
>
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|

>




>
|
|
|
|
>
|
|
|
|
>
|
|
|
|
>
|
|
|
|
|
>
|
>
|
|
|

|




>
|
|
|
|
|
>
|
|
|
|
|

|
|
|
>
|
|
|
|
|

|
|
|
>
|
|
|
|
>
|
|
|
|
>
|
|
|
|
|

|
|
>

<
|
|
|
|

|
|
>
|
>
>
>
>
>
|
|
|

>
|


|
>
|
|
|
|
|
>
|
|
|
|
|
|
|

|
|
>
|
|
|
|
|
|
|

|
|
>

<
|
|
|
>
|
>
>
>
>
>
|
|
|

>





>
|
|
|
|
>
|
|
|
>
>
>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
|
<
<
|
|
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
|
>
|
>
|
<
|
|
|
|
>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|

>
|
>
>
>
>
>
>
>
>
>
>
>
>












|
|
|
|


|







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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792







793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106

1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159

1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217


1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254

1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
   def __iter__(self):
      return self

   def next(self):
      if self.finished:
         raise StopIteration
      else:
         currentIP = self.currentIP
         self.currentIP = next_ip(self.currentIP)
         self.finished = currentIP == self.toIP
#         print >> sys.stderr, "%s/%s/%s/%s" % (currentIP, self.currentIP, self.toIP, self.finished)
         return currentIP

# Map cable types to their corresponding circuit type
CABLE_TYPES = {
   "utp": "ethernet",
   "fibre": "ethernet",
   "wifi": "ethernet",
   "virtual": "ethernet",

   "serial": "serial",

   "parallel": "parallel",

   "power": "power",
   "power240vAC": "power",
   "power110vAC": "power",
   "power48vDC": "power",
   "power12vDC": "power",

   "kvm": "kvm",

   "usb": "usb",

   "telephone": "telephone",

   "unused": "unused"
}

def getCircuitType(cableType):
   # Work out the correct circuit type for a cable
   return CABLE_TYPES[cableType]

def crossRefPanels(cables, panels, trunkGroups, organisations):
   # What trunks go to what panels?
   for trunkGroupName in trunkGroups:
      trunkGroup = trunkGroups[trunkGroupName]
      for trunk in trunkGroup.trunks:
         for (panelName,port) in trunk.panels:
            if not panels.has_key(panelName):
               print >> sys.stderr, "Trunk group %s attempts to connect to port %s of panel %s, but that panel doesn't seem to exist" % (trunkGroupName, port, panelName)
               sys.exit(1)
            panel = panels[panelName]
            panel.trunks[port] = trunk

   # What cables go to what panels?
   for cableName in cables:
      cable = cables[cableName]
      for (panelName,port) in cable.panels:
         if not panels.has_key(panelName):
            print >> sys.stderr, "Cable %s attempts to connect to port %s of panel %s, but that panel doesn't seem to exist" % (cableName, port, panelName)
            sys.exit(1)
         panel = panels[panelName]
         panel.cables[port] = cable

   # Who owns panels, and where are they?
   for panelName in panels:
      panel = panels[panelName]

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

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

      panel.owner.panels.append(panel)

def joinCircuits(name1,tagged1,circuit1,circuits1,name2,tagged2,circuit2,circuits2):
   # Join together two circuit definitions, by returning
   # the combined definition of the circuit.
   # Complain if the two circuits are not joinable (and then just return
   # one of them)
   defined1 = (circuit1 != None or len(circuits1) != 0)
   defined2 = (circuit2 != None or len(circuits2) != 0)

   if defined1 and defined2:
      # Check they match
      if circuit1 <> circuit2:
         print >> sys.stderr, "%s carries circuit %s and is patched to %s which carries circuit %s" % (name1, circuit1, name2, circuit2)
      if set(circuits1) <> set(circuits2):
         circuits1.sort()
         circuits2.sort()
         print >> sys.stderr, "%s carries circuits %s and is patched to %s which carries circuits %s" % (name1, ",".join(circuits1), name2, ",".join(circuits2))
      return (tagged1,circuit1,circuits1)
   elif defined1 and not defined2:
      return (tagged1,circuit1,circuits1)
   elif not defined1 and defined2:
      return (tagged2,circuit2,circuits2)
   else:
      # Neither are defined
      return (None, None, [])

def findLinks(cables,panels,trunkGroups):
   # Given a dict of cables, build the dict of links by
   # seeing what cables are joined together

   links = []

   for cableName in cables:
      cable = cables[cableName]

      if cable.link:
         # We've already dealt with this one
         #print >> sys.stderr, "DEBUG: Cable %s already on link %s" % (cable, cable.link)
         continue

      if len(cable.panels) == 0:
         # Does the cable interface with any panels?
         # If not, it's a link unto itself

         link = Link()

         link.cableType = cable.cableType
         link.devices = []
         link.cables = [cable]
         link.panels = []
         for device in cable.devices:
            link.devices.append((device[0],device[1],cable.name))
         link.tagged = cable.tagged
         link.circuit = cable.circuit
         link.circuits = cable.circuits

         links.append(link)
         cable.link = link

         #print >> sys.stderr, "DEBUG: Cable %s assigned to singleton link %s" % (cable, cable.link)
      else:
         # Cable interacts with some panels. Therefore, it's
         # joined with other cables to form a link.
         # So we look at what other cables it joins to via the panels,
         # and find out how many links they are already assigned to.
         neighbourTrunks = []
         neighbourTrunksWithoutLink = []
         for (panel,port) in cable.panels:
            if panels[panel].trunks.has_key(port):
               trunk = panels[panel].trunks[port]
               neighbourTrunks.append(trunk)
               if trunk.link == None:
                  neighbourTrunksWithoutLink.append(trunk)

         neighbourLinks = []
         for neighbourTrunk in neighbourTrunks:
            if neighbourTrunk.link != None:
               neighbourLinks.append(neighbourTrunk.link)

         #print >> sys.stderr, "DEBUG: Cable %s peers with %r and links %r" % (cable, neighbourTrunks, neighbourLinks)

         # If it's zero, then we are a new link.
         if len(neighbourLinks) == 0:
            link = Link()

            link.cableType = cable.cableType
            link.devices = []
            for device in cable.devices:
               link.devices.append((device[0],device[1],cable.name))
            link.panels = []
            for panel in cable.panels:
               link.panels.append((panel[0],panel[1],cable.name))
            link.cables = [cable] + neighbourTrunksWithoutLink
            link.tagged = cable.tagged
            link.circuit = cable.circuit
            link.circuits = cable.circuits

            links.append(link)
            cable.link = link
            #print >> sys.stderr, "DEBUG: Cable %s assigned to new link %s" % (cable, cable.link)

            # Spread this link to all peers
            for neighbourTrunk in neighbourTrunks:
               if neighbourTrunk.link == None:
                  #print >> sys.stderr, "DEBUG: Propogating link %s to %s" % (link, neighbourTrunk)
                  neighbourTrunk.link = link

         # If it's one or more, then join the first
         elif len(neighbourLinks) >= 1:
            link = neighbourLinks[0]

            if link.cableType != cable.cableType:
               print >> sys.stderr, "Cable %s is patched into a link of type %s, but it's of type %s" % (cable, link.cableType, cable.cableType)

            for device in cable.devices:
               link.devices.append((device[0],device[1],cable.name))
            for panel in cable.panels:
               link.panels.append((panel[0],panel[1],cable.name))
            link.cables.append(cable)
            link.cables.extend(neighbourTrunksWithoutLink)

            # Merge circuit declarations
            (mergedTagged,mergedCircuit,mergedCircuits) = joinCircuits("cable %s" % cable, cable.tagged, cable.circuit, cable.circuits, "a link", link.tagged, link.circuit, link.circuits)
            link.tagged = mergedTagged
            link.circuit = mergedCircuit
            link.circuits = mergedCircuits
            cable.tagged = mergedTagged
            cable.circuit = mergedCircuit
            cable.circuits = mergedCircuits

            cable.link = link

            #print >> sys.stderr, "DEBUG: Cable %s assigned to existing link %s" % (cable, cable.link)

            # Now merge any other links into the first link
            for peerLink in neighbourLinks[1:]:
               if peerLink.cableType != cable.cableType:
                  print >> sys.stderr, "Cable %s is patched into a link of type %s, but it's of type %s" % (cable, peerLink.cableType, cable.cableType)

               #print >> sys.stderr, "DEBUG: Merging link %s into link %s" % (peerLink, link)

               link.devices.extend(peerLink.devices)
               link.panels.extend(peerLink.panels)
               link.cables.extend(peerLink.cables)

               (link.tagged, link.circuit, link.circuits) = joinCircuits("a link", link.tagged, link.circuit, link.circuits, "another link", peerLink.tagged, peerLink.circuit, peerLink.circuits)

               # Edit the peer link out of history
               for peerCable in peerLink.cables:
                  peerCable.link = link

               links.remove(peerLink)

            # Spread this link to all peers
            for neighbourTrunk in neighbourTrunks:
               if neighbourTrunk.link == None:
                  #print >> sys.stderr, "DEBUG: Propogating link %s to %s" % (link, neighbourTrunk)
                  neighbourTrunk.link = link


   linksDict = {}
   for link in links:
      if link.name == None:
         if len(link.cables) == 1:
            link.name = link.cables[0].name
         else:
            # FIXME: Use some kind of topological sort in an effort
            # to find the longest path through the link and use that
            # name in order.
            cableNames = map(lambda(cable): cable.name,link.cables)
            cableNames.sort()
            link.name = "-".join(cableNames)

      linksDict[link.name] = link

   return linksDict

def parseCabling(infile):

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

   cableTypeRE = "(%s)" % ("|".join(CABLE_TYPES.keys()))
   circuitTypeRE = "(%s)" % ("|".join(set(CABLE_TYPES.values())))

   # <type> <id> {
   cableStartRE = re.compile(r"%s +([^ ]+) *{" % cableTypeRE)

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

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

   # circuit <num>
   circuitRE = re.compile(r"(?:circuit|vlan) +([^ ]+)")

   # tagged circuits <nums>
   taggedCircuitsRE = re.compile(r"(?:circuit|tagged +vlan)s +([^ ]+)")

   # 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> <circuit> <ip> [shared|stub]
   ip4circuitRE = 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)?)")

   # mac <port> <circuit> <mac> [shared]
   macCircuitRE = re.compile(r"mac +([^ ]+) +([^ ]+) +([^ ]+) *((shared)?)")

   # mac <port> <mac> [shared]
   macRE = re.compile(r"mac +([^ ]+) +([^ ]+) *((shared)?)")

   # circuit <name> {
   circuitStartRE = re.compile(r"(?:circuit|vlan) +([^ /]+) *{")

   # type <...circuit type...>
   circuitTypeRE = re.compile(r"type +%s" % circuitTypeRE)

   # 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 +\"([^\"]+)\"")

   # location <code> {
   locationStartRE = re.compile(r"location +([^ ]+) *{")

   # location <code>
   locationRE = re.compile(r"location +([^ ]+)")

   # address <type> "<address>"
   addressRE = re.compile(r"address +([^ ]+) \"([^\"]+)\"")

   # }
   endRE = re.compile(r"}")

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

   # <type> trunk <name> {
   trunkGroupStartRE = re.compile(r"%s trunk +([^ /]+) *{" % cableTypeRE)

   # group <panel>/<port>-<port> <panel>/<port>-<port>
   trunkGroupRE = re.compile(r"group +([^ /]+)/([^ /-]+)-([^ /-]+) +([^ /]+)/([^ /-]+)-([^ /-]+)")

   # trunk <panel>/<port> <panel>/<port>
   trunkRE = re.compile(r"trunk +([^ /]+)/([^ /-]+) +([^ /]+)/([^ /-]+)")

   # trunk <label> <panel>/<port> <panel>/<port>
   trunkLabelRE = re.compile(r"trunk +([^ /]+) +([^ /]+)/([^ /-]+) +([^ /]+)/([^ /-]+)")

   cables = {}
   cable = None

   circuits = {}
   circuit = None

   devices = {}
   device = None

   ip4subnets = {}
   ip4subnet = None

   organisations = {}
   organisation = None

   locations = {}
   location = None

   panels = {}
   panel = None

   trunkGroups = {}
   trunkGroup = 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, circuit, line)

      if line == "":
         continue

      # Global scope
      if cable == None and circuit == None and device == None and organisation == None and location == None and panel == None and trunkGroup == 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

         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

         m = circuitStartRE.match(line)
         if m:
            circuit = Circuit()
            circuit.name = m.group(1)

            if circuits.has_key(circuit.name):
               print >> sys.stderr, "line %d: The circuit %s is declared twice" % (lineNumber,circuit.name)
               sys.exit(1)
            continue

         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

         m = locationStartRE.match(line)
         if m:
            location = Location(m.group(1))

            if locations.has_key(location.code):
               print >> sys.stderr, "line %d: The location %s is declared twice" % (lineNumber, location.code)
            continue

         m = panelStartRE.match(line)
         if m:
            panel = Panel(m.group(1))

            if panels.has_key(panel.name):
               print >> sys.stderr, "line %d: The panel %s is declared twice" % (lineNumber, panel.name)
            continue

         m = trunkGroupStartRE.match(line)
         if m:
            trunkGroup = TrunkGroup(m.group(1), m.group(2))
            trunkGroupLastLabel = "0"
            trunkGroupLabels = {}

            if trunkGroups.has_key(trunkGroup.name):
               print >> sys.stderr, "line %d: The trunk group %s is declared twice" % (lineNumber, trunkGroup.name)
            continue

         print >> sys.stderr, "line %d: Syntax error in global scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Panel scope
      if panel != None:
         m = endRE.match(line)
         if m:
            panels[panel.name] = panel
            panel = None
            continue

         m = noteRE.match(line)
         if m:
            panel.notes.append(m.group(1))
            continue

         m = titleRE.match(line)
         if m:
            panel.title = m.group(1)
            continue

         m = locationRE.match(line)
         if m:
            panel.location = m.group(1)
            continue

         print >> sys.stderr, "line %d: Syntax error in panel scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Trunk Group scope
      if trunkGroup != None:
         m = endRE.match(line)
         if m:
            trunkGroups[trunkGroup.name] = trunkGroup
            trunkGroup = None
            continue

         m = noteRE.match(line)
         if m:
            trunkGroup.notes.append(m.group(1))
            continue

         m = titleRE.match(line)
         if m:
            trunkGroup.title = m.group(1)
            continue

         m = trunkGroupRE.match(line)
         if m:
            panel0 = m.group(1)
            port01 = int(m.group(2))
            port02 = int(m.group(3))

            panel1 = m.group(4)
            port11 = int(m.group(5))
            port12 = int(m.group(6))

            if port02-port01 != port12-port11:
               print >> sys.stderr, "Trunk group %s attempts to trunk %d ports %d-%d on panel %s to %d ports %d-%d on panel %s - that doesn't match!" % (trunkGroup.name, port02-port01+1, port01, port02, panel0, port12-port11+1, port11, port12, panel1)
               print >> sys.stderr, line
               sys.exit(1)

            for port0 in range(port01,port02+1):
               ct = Cable()
               ct.cableType = trunkGroup.cableType

               if str(int(trunkGroupLastLabel)) != trunkGroupLastLabel:
                  print >> sys.stderr, "line %d: Automatic numbering may only be used if the previous trunk has a numeric label, which '%s' is not" % (lineNumber, trunkGroupLastLabel)
                  print >> sys.stderr, line
                  sys.exit(1)
               trunkGroupLastLabel = str(int(trunkGroupLastLabel)+1)
               ct.name = "%s/%s" % (trunkGroup.name, trunkGroupLastLabel)
               ct.panels.append((panel0, str(port0)))
               ct.panels.append((panel1, str(port0-port01 + port11)))
               ct.isTrunk = True
               ct.trunkGroup = trunkGroup
               ct.trunkGroupLabel = trunkGroupLastLabel
               trunkGroup.trunks.append(ct)
               if trunkGroupLabels.has_key(ct.name):
                  print >> sys.stderr, "Line %d: There is already a trunk with the label '%s'" % ct.name
                  print >> sys.stderr, line
                  sys.exit(1)
               trunkGroupLabels[ct.name] = ct
            continue

         m = trunkRE.match(line)
         if m:
            panel0 = m.group(1)
            port0 = m.group(2)
            panel1 = m.group(3)
            port1 = m.group(4)

            ct = Cable()
            ct.cableType = trunkGroup.cableType
            if str(int(trunkGroupLastLabel)) != trunkGroupLastLabel:
               print >> sys.stderr, "line %d: Automatic numbering may only be used if the previous trunk has a numeric label, which '%s' is not" % (lineNumber, trunkGroupLastLabel)
               print >> sys.stderr, line
               sys.exit(1)
            trunkGroupLastLabel = str(int(trunkGroupLastLabel)+1)
            ct.name = "%s/%s" % (trunkGroup.name, trunkGroupLastLabel)
            ct.panels.append((panel0, port0))
            ct.panels.append((panel1, port1))
            ct.isTrunk = True
            ct.trunkGroup = trunkGroup
            ct.trunkGroupLabel = trunkGroupLastLabel
            trunkGroup.trunks.append(ct)
            if trunkGroupLabels.has_key(ct.name):
               print >> sys.stderr, "Line %d: There is already a trunk with that label"
               print >> sys.stderr, line
               sys.exit(1)
            trunkGroupLabels[ct.name] = ct
            continue

         m = trunkLabelRE.match(line)
         if m:
            label = m.group(1)
            panel0 = m.group(2)
            port0 = m.group(3)
            panel1 = m.group(4)
            port1 = m.group(5)

            ct = Cable()
            ct.isTrunk = True
            ct.cableType = trunkGroup.cableType
            trunkGroupLastLabel = label
            ct.name = "%s/%s" % (trunkGroup.name, label)
            ct.panels.append((panel0, port0))
            ct.panels.append((panel1, port1))
            ct.isTrunk = True
            ct.trunkGroup = trunkGroup
            ct.trunkGroupLabel = label
            trunkGroup.trunks.append(ct)
            if trunkGroupLabels.has_key(ct.name):
               print >> sys.stderr, "Line %d: There is already a trunk with that label"
               print >> sys.stderr, line
               sys.exit(1)
            trunkGroupLabels[ct.name] = ct
            continue

         print >> sys.stderr, "line %d: Syntax error in trunk group scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Location scope
      if location != None:
         m = endRE.match(line)
         if m:
            locations[location.code] = location
            location = None
            continue

         m = noteRE.match(line)
         if m:
            location.notes.append(m.group(1))
            continue

         m = titleRE.match(line)
         if m:
            location.name = m.group(1)
            continue

         m = locationRE.match(line)
         if m:
            location.location = m.group(1)
            continue

         m = addressRE.match(line)
         if m:
            location.addresses[m.group(1)] = m.group(2)
            continue

         print >> sys.stderr, "line %d: Syntax error in location scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Organisation scope
      if organisation != None:
         m = noteRE.match(line)
         if m:
            organisation.notes.append(m.group(1))
            continue

         m = titleRE.match(line)
         if m:
            organisation.name = m.group(1)
            continue

         m = orgEmergContactRE.match(line)
         if m:
            organisation.emergencyContacts.append (m.group(1))
            continue

         m = orgAuthContactRE.match(line)
         if m:
            organisation.authorisedContacts.append (m.group(1))
            continue

         m = endRE.match(line)
         if m:
            organisations[organisation.code] = organisation
            organisation = None
            continue


         print >> sys.stderr, "line %d: Syntax error in organisation scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Device scope
      if device != None:
         m = noteRE.match(line)
         if m:
            device.notes.append(m.group(1))
            continue

         m = endRE.match(line)
         if m:
            devices[device.name] = device
            device = None
            continue

         m = ip4circuitRE.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))
            continue

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

         m = deviceTypeRE.match(line)
         if m:
            device.deviceType = m.group(1)
            continue

         m = deviceHostsRE.match(line)
         if m:
            device.hostedDevices.append(m.group(1))
            continue

         m = macCircuitRE.match(line)
         if m:
            if not device.macs.has_key(m.group(1)):
               device.macs[m.group(1)] = []

            shared = m.group(4) == "shared"
            device.macs[m.group(1)].append(MacPort(m.group(2),device.name,m.group(1),parse_mac(m.group(3)),shared))
            continue


         m = macRE.match(line)
         if m:
            if not device.macs.has_key(m.group(1)):
               device.macs[m.group(1)] = []

            shared = m.group(3) == "shared"
            device.macs[m.group(1)].append(MacPort(None,device.name,m.group(1),parse_mac(m.group(2)),shared))
            continue

         m = locationRE.match(line)
         if m:
            device.location = m.group(1)
            continue

         print >> sys.stderr, "line %d: Syntax error in device scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Circuit scope
      if circuit != None:
         m = noteRE.match(line)
         if m:
            circuit.notes.append(m.group(1))
            continue

         m = endRE.match(line)
         if m:
            circuits[circuit.name] = circuit
            circuit = None
            continue

         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"
            circuit.ip4subnets.append((trimmed,m.group(2),multiple))
            continue

         # 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 overlaps
            circuit.ip4reservations.append((fromIP,toIP,descr))
            continue


         m = titleRE.match(line)
         if m:
            circuit.title = m.group(1)
            continue

         m = circuitTypeRE.match(line)
         if m:
            circuit.circuitType = m.group(1)
            continue

         print >> sys.stderr, "line %d: Syntax error in circuit scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

      # Cable scope
      if cable != None:
         m = endRE.match(line)
         if m:
            cables[cable.name] = cable
            cable = None
            continue

         m = deviceRE.match(line)
         if m:
            cable.devices.append ((m.group(1),m.group(2)))
            continue

         m = panelRE.match(line)
         if m:
            cable.panels.append ((m.group(1),m.group(2)))
            continue

         m = circuitRE.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.circuit = m.group(1)
            continue

         m = taggedCircuitsRE.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 _circuit in m.group(1).split(","):
               _circuit = _circuit.strip()
               if _circuit != "":
                  cable.circuits.append (_circuit)

            continue



         m = noteRE.match(line)
         if m:
            cable.notes.append(m.group(1))
            continue

         print >> sys.stderr, "line %d: Syntax error in cable scope:" % lineNumber
         print >> sys.stderr, line
         sys.exit(1)

   crossRefPanels(cables, panels, trunkGroups, organisations)

   links = findLinks(cables, panels, trunkGroups)

   return CablingScheme(cables, links, circuits, devices, {}, ip4subnets, organisations, locations, panels, trunkGroups)

def findVirtualLocation(cabling, device):
   # Guess the location of a virtual device
   if device.location <> None:
      return device.location
   if device.deviceType <> "virtual":
      return device.location

   for parentName in device.hostedBy:
      parent = cabling.devices[parentName]
      loc = findVirtualLocation(cabling, parent)
      if loc <> None:
         device.location = loc # Save future work by storing our result
         return loc

def crossRefLocations(cabling):
   for locationName in cabling.locations:
      location = cabling.locations[locationName]

      # Resolve ownership
      nameparts = location.name.split(":")
      if len(nameparts) == 1:
         orgname = "unknown"

      else:
         orgname = nameparts[0]

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

      location.owner.locations.append(location)

      # Resolve hierarchy
      if location.location <> None:
         if not cabling.locations.has_key(location.location):
            print >> sys.stderr, "Location %s claims to be within location %s, but that does not exist" % (location.code, location.location)
            sys.exit(1)

         # A tongue twister:
         cabling.locations[location.location].locations.append(location)

   # What devices are in what location?
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]

      # For virtual devices, try and deduce a physical location
      if device.location == None and device.deviceType == "virtual":
         device.location = findVirtualLocation(cabling, device)

      # Add the device to it's containing location

      if device.location <> None:
         if not cabling.locations.has_key(device.location):
            print >> sys.stderr, "Device %s claims to be within location %s, but that does not exist" % (device.name, device.location)
            sys.exit(1)

         cabling.locations[device.location].devices.append(device)

   # What panels are in what location?
   for panelName in cabling.panels:
      panel = cabling.panels[panelName]

      # Add the panel to it's containing location

      if panel.location <> None:
         if not cabling.locations.has_key(panel.location):
            print >> sys.stderr, "Panel %s claims to be within location %s, but that does not exist" % (panel.name, panel.location)
            sys.exit(1)

         cabling.locations[panel.location].panels.append(panel)

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 linkName in cabling.links:
      link = cabling.links[linkName]
      for device in link.devices:
         (dev,port,cable) = device

         # Create devices that were not declared explicitly in the
         # file, but implied by having a link 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:
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
            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/macs 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

            for portName in cabling.devices[dev].macs:
               if portName == port:
                  macs = cabling.devices[dev].macs[portName]
                  for mac in macs:
                     if mac.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
                        mac.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 crossRefMacs(cabling):
   # Examine the MACs declared on vlans
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
      for port in device.macs:
         macs = device.macs[port]

         for mac in macs:
            # Add to global list
            if not cabling.macs.has_key(mac.mac):
               cabling.macs[mac.mac] = []

            cabling.macs[mac.mac].append(mac)

            if mac.vlan != None:
               # Add to VLAN's MAC list

               # Create VLAN if it does not already exist
               if not cabling.vlans.has_key(mac.vlan):
                  cabling.vlans[mac.vlan] = VLAN()
               cabling.vlans[mac.vlan].name = mac.vlan

               if cabling.vlans[mac.vlan].macs.has_key(mac.mac) and not mac.shared:
                  print >> sys.stderr, "Warning: mac %s appears on VLAN %s in more than one place" % (mac.mac, vlan.name)
               else:
                  cabling.vlans[mac.vlan].macs[mac.mac] = []

               cabling.vlans[mac.vlan].macs[mac.mac].append(mac)

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)







|
|

|
|




|
|
|
|





|
|
|
|

|
|
|
>

|
|
|
>
>
>
|
>
|
|
|
<
<
>
>

|
|
|
|
|
>
>
>
|
<
<
|
<
<
>
>

>
|
|
<
|
>
>


|












|
|

|
|
|
|

|
|

|

|


|
|
|



|






|





|

|



|



|






|



|
|
|



|













|




|
|








|
|


|







1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387


1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399


1400


1401
1402
1403
1404
1405
1406

1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
            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], link)
         cabling.devices[dev].ports.append ((port,link))

         if link.tagged == False:
            # Fix up any ip4s/macs without Circuit specified
            for portName in cabling.devices[dev].ip4s:
               if portName == port:
                  ip4s = cabling.devices[dev].ip4s[portName]
                  for ip4 in ip4s:
                     if ip4.circuit == None:
                        # print >>sys.stderr, "Assigning circuit %s from link %s to ip %s of %s/%s" % (link.circuit, link, ip4, portName, dev)
                        # print >>sys.stderr, "We shared this link with %s" % link.devices
                        ip4.circuit = link.circuit

            for portName in cabling.devices[dev].macs:
               if portName == port:
                  macs = cabling.devices[dev].macs[portName]
                  for mac in macs:
                     if mac.circuit == None:
                        # print >>sys.stderr, "Assigning circuit %s from link %s to ip %s of %s/%s" % (link.circuit, link, ip4, portName, dev)
                        # print >>sys.stderr, "We shared this link with %s" % link.devices
                        mac.circuit = link.circuit

def crossRefCircuits(cabling):
   for linkName in cabling.links:
      link = cabling.links[linkName]
      circuitType = getCircuitType(link.cableType)

      if link.tagged == None:
         circuits = []
      elif link.tagged:
         circuits = link.circuits
      else:
         circuits = [link.circuit]

      for circuit in circuits:
         # Create any circuits that were not explicitly declared
         # in the configuration, but implied by being present on a link
         if not cabling.circuits.has_key(circuit):


            cabling.circuits[circuit] = Circuit()
            cabling.circuits[circuit].name = circuit

         # Build list of ports on each circuit
         for device in link.devices:
            (dev,port,cable) = device
            cabling.circuits[circuit].ports.append((dev,port,link))
            # Check circuit types match
            if cabling.circuits[circuit].circuitType == None:
               # No type declared, let's guess
               cabling.circuits[circuit].circuitType = circuitType
            else:


               if cabling.circuits[circuit].circuitType != circuitType:


                  # Is this warning good? UTP can carry serial and telephone signals, too, which this model doesn't cover.
                  print >> sys.stderr, "The circuit %s has circuit type %s, but link %s carries it and has link type %s (which is circuit typer %s)" % (cabling.circuits[circuit].name, cabling.circuits[circuit].circuitType, link.name, link.cableType, circuitType)

   # Sanity check: Warn if IP4 subnets are assigned to non-Ethernet
   # circuits
   for circuitName in cabling.circuits:

      circuit = cabling.circuits[circuitName]
      if circuit.circuitType <> "ethernet" and len(circuit.ip4subnets) <> 0:
         print >> sys.stderr, "The circuit %s has IP4 subnets, but isn't an ethernet circuit (its type is %s)" % (circuit, circuit.circuitType)

def crossRefMacs(cabling):
   # Examine the MACs declared on circuits
   for deviceName in cabling.devices:
      device = cabling.devices[deviceName]
      for port in device.macs:
         macs = device.macs[port]

         for mac in macs:
            # Add to global list
            if not cabling.macs.has_key(mac.mac):
               cabling.macs[mac.mac] = []

            cabling.macs[mac.mac].append(mac)

            if mac.circuit != None:
               # Add to Circuit's MAC list

               # Create Circuit if it does not already exist
               if not cabling.circuits.has_key(mac.circuit):
                  cabling.circuits[mac.circuit] = Circuit()
               cabling.circuits[mac.circuit].name = mac.circuit

               if cabling.circuits[mac.circuit].macs.has_key(mac.mac) and not mac.shared:
                  print >> sys.stderr, "Warning: mac %s appears on Circuit %s in more than one place" % (mac.mac, circuit.name)
               else:
                  cabling.circuits[mac.circuit].macs[mac.mac] = []

               cabling.circuits[mac.circuit].macs[mac.mac].append(mac)

def crossRefIP4Subnets(cabling):
   # Examine ip4 subnets delcared on circuits
   for circuitName in cabling.circuits:
      circuit = cabling.circuits[circuitName]

      processedSubnets = []

      for subnetDetails in circuit.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 CircuitS 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 circuit %s) also exists on circuit %s" % (unparse_ip(subnet), circuit,  existingSubnet.circuit)
               else:
                  print >>sys.stderr, "The subnet %s (from circuit %s) overlaps the existing subnet %s" % (unparse_ip(subnet), circuit, existingSubnet)
               break

         newSubnet = IP4Subnet(subnet,title,multiple)
         newSubnet.circuit = circuitName
         cabling.ip4subnets[repr(newSubnet)] = newSubnet
         processedSubnets.append (newSubnet)

      circuit.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.circuit)

   # Examine ip reservations

   for circuitName in cabling.circuits:
      circuit = cabling.circuits[circuitName]
      for resv in circuit.ip4reservations:
         (fromIP,toIP,descr) = resv
         for subnetName in cabling.ip4subnets:
            subnet = cabling.ip4subnets[subnetName]
            if circuitName == subnet.circuit 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 link graces that port" % (deviceName, ip4portName)
         ip4ports = device.ip4s[ip4portName]
         for ip4port in ip4ports:
            ip4 = ip4port.ip

            if ip4port.circuit == None and not ip4port.stub:
               print >>sys.stderr, "Port %s/%s declares IP %s, but the circuit 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, "circuit is %s vs. %s" % (ip4port.circuit, subnet.circuit)
               if (ip4port.circuit == subnet.circuit) and compare_nets(ip4, subnet.net) == -1:
                  # We have found our subnet
                  matchedSubnets.append(subnet)
                  #print >>sys.stderr, "ip address %s from %s/%s (circuit %s)" % (unparse_ip(ip4), deviceName, ip4portName, ip4port.circuit)
                  #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)
851
852
853
854
855
856
857
858
859
860

861
862
               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)
   crossRefMacs (cabling)
   crossRefIP4Subnets (cabling)


   return cabling







|


>


1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
               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)
   crossRefCircuits (cabling)
   crossRefMacs (cabling)
   crossRefIP4Subnets (cabling)
   crossRefLocations (cabling)

   return cabling