Sunday, November 27, 2011

GPS dongle, gpsd, and Ubuntu 11.10

This post is an update to my original experiment #1 and experiment #2 with a USB GPS dongle two years ago.

Install the hardware: Plug it in, of course.
  • Check the kernel message log to discover the GPS dongle location in the filesystem:
    $ dmesg | grep tty
    [1769190.919411] usb 2-1: pl2303 converter now attached to ttyUSB0
  • Test for signal with the following command:
    $ cat /dev/ttyUSB0 
    5�y�220,N,08754.5061,W,000.0,316.5,271111,,,A*71
    $GPVTG,316.5,T,,M,000.0,N,000.0,K,A*0C
    $GPGGA,173905.000,4259.7220,N,08754.5060,W,1,08,1.0,190.0,M,-33.8,M,,0000*63
    $GPGSA,A,3,12,04,10,23,02,05,17,25,,,,,1.7,1.0,1.4*31
    $GPRMC,173905.000,A,4259.7220,N,08754.5060,W,000.0,316.5,271111,,,A*71
    
    Use CTRL+C to end the signal check.
    If you get a bunch of zero-data, then try moving closer to a window, since GPS signals are line-of-sight. Or try a USB hub or extension cable, to reduce interference from your computer.

Install the gps daemon so you can use gps data.
  • sudo apt-get install gpsd gpsd-clients
  • Normally, udev will start gpsd automatically when a USB GPS device is inserted. If it fails to start after 5-10 seconds, you can start it manually:
    gpsd /dev/ttyUSB0  #You must tell gpsd where to look for the dongle
  • Test the GPS and gpsd output using the gpsmon and cgps terminal programs, or the xgps program (all included in the gpsd-clients package)
  • Capture data for recycling (optional - handy for development). gpsfake will simulate gpsd output
    $cat /dev/ttyUSB0 > path/to/datalog  # Create data file. Use CTRL+C to end the capture.
    $gpsfake path/to/datalog             # Run gpsd simulator (not a daemon - it will occupy the terminal)

Command-line tools to get GPS data
  • Use the gpspipe command to get gpsd data:
    $ gpspipe -w -n 5
    netlib_connectsock() returns socket on fd 3
    {"class":"VERSION","release":"2.95","rev":"2011-07-27T11:20:24","proto_major":3,"proto_minor":3}
    {"class":"DEVICES","devices":[{"class":"DEVICE","path":"/dev/ttyUSB0"}]}
    {"class":"WATCH","enable":true,"json":true,"nmea":false,"raw":0,"scaled":false,"timing":false}
    {"class":"TPV","tag":"RMC","device":"/dev/ttyUSB0","time":1322418390.001,"ept":0.005,"lat":42.995410000,"lon":-87.908430000,"alt":195.400,"epx":11.739,"epy":17.294,"epv":36.800,"track":342.2000,"speed":0.000,"climb":0.000,"eps":34.59,"mode":3}
    {"class":"SKY","tag":"GSV","device":"/dev/ttyUSB0","xdop":0.66,"ydop":1.15,"vdop":1.46,"tdop":1.01,"hdop":1.32,"gdop":2.22,"pdop":1.97,"satellites":[{"PRN":2,"el":77,"az":360,"ss":26,"used":true},{"PRN":10,"el":58,"az":72,"ss":32,"used":true},{"PRN":12,"el":51,"az":247,"ss":34,"used":true},{"PRN":5,"el":45,"az":192,"ss":21,"used":true},{"PRN":4,"el":40,"az":65,"ss":20,"used":true},{"PRN":25,"el":39,"az":292,"ss":21,"used":true},{"PRN":13,"el":15,"az":60,"ss":18,"used":true},{"PRN":24,"el":14,"az":258,"ss":0,"used":false},{"PRN":29,"el":12,"az":304,"ss":23,"used":false},{"PRN":17,"el":8,"az":121,"ss":17,"used":true},{"PRN":23,"el":7,"az":35,"ss":10,"used":false},{"PRN":31,"el":0,"az":334,"ss":0,"used":false}]}
  • Let's refine the command a bit, limit to the first "TPV" (time, position, velocity) sentence:
    $ gpspipe -w -n 5 | grep -m 1 TPV
    netlib_connectsock() returns socket on fd 3
    {"class":"TPV","tag":"RMC","device":"/dev/ttyUSB0","time":1322418481.001,"ept":0.005,"lat":42.995406667,"lon":-87.908428333,"alt":195.300,"epx":10.003,"epy":17.383,"epv":36.800,"track":342.2000,"speed":0.000,"climb":0.000,"eps":34.77,"mode":3}
  • We can use basic shell commands to extract single variables from this sentence:
    tpv=$(gpspipe -w -n 5 | grep -m 1 TPV | cut -d, -f4,6-8,13)
    seconds=$(echo $tpv | cut -d, -f1 | cut -d: -f2)
    latitude=$(echo $tpv | cut -d, -f2 | cut -d: -f2)
    longitude=$(echo $tpv | cut -d, -f3 | cut -d: -f2)
    altitude=$(echo $tpv | cut -d, -f4 | cut -d: -f2)
    speed=$(echo $tpv | cut -d, -f5 | cut -d: -f2)
  • For fun, let's compare GPS time with system time using shell commands:
    date -u +%s   # System utc time in seconds
    gpspipe -w -n 5 | grep -m 1 TPV | cut -d, -f4 | cut -d: -f2   # GPS utc time in seconds
    
    # Let's compare them side-by side
    $ echo System: $(date -u +%s) , GPS: $(gpspipe -w -n 5 | grep -m 1 TPV | cut -d, -f4 | cut -d: -f2) 
    netlib_connectsock() returns socket on fd 3
    System: 1322419689 , GPS: 1322419689.000
    # Our sytem time is within one second of GPS time. That's good!
  • For fun, let's use shell script to post the GPS location to Google Maps:
    The format is simple enough: http://maps.google.com/?ll=40.480381,-92.373047&z=16 will return a valid map. So that's three variables: Latitude, longitude, and zoom Level.
    tpv=$(gpspipe -w -n 5 | grep -m 1 TPV | cut -d, -f4,6-8,13)
    latitude=$(echo $tpv | cut -d, -f2 | cut -d: -f2)
    longitude=$(echo $tpv | cut -d, -f3 | cut -d: -f2)
    zoom=20
    map_url="http://maps.google.com/?ll=${latitude},${longitude}&z=${zoom}"
    firefox $map_url

Python tools to get GPS data
  • Python bindings to gpsd are provided by the python-gps package.
    sudo apt-get install python-gps
  • The python tools have changed a *lot* in two years. The old methods don't work anymore. No Python 3 version is available yet. There's a decent example here, but I couldn't get it to work.

Conversion between Lat/Lon and MGRS/UTM and other systems: gpsd doesn't do this, though apparently the geographiclib-tools package does. And so does this website.

Saturday, November 26, 2011

Ubuntu Brainstorm - inside the sausage factory

Brainstorm gets about 2,000 submissions each year.
What do we do with all those ideas?
How can they help you, without bogging you down?

Well, we close about 85% of them immediately. That's good - it keeps the system from being spammed by all those bugs, complaints, and other not-really-ideas.

About 2% get reviewed by the Ubuntu Technical Board. We try to get the most out of that 2%!

Most new Brainstormers are new to the Ubuntu community - they find Brainstorm in their first excursion looking for a way to contribute. A Brainstorm idea is their first attempt to speak up, so we try to handle them carefully.

(If you were, er, untactfully treated by any moderator in the past, then please accept my most humble apologies. If you find a recent idea we handled tactlessly, *please* let me know!)


The Idea Sandbox

Of course, most of those first-ideas aren't very good. My first idea was awful, too.
- Make it more like my old OS
- Fix this bug
- This doesn't work very well
- Hey, do this. It's self-evident
- Substitute application X for application Y in the default install
- Create a whole new distro for a very small audience
- Develop a whole new application
- I don't like this
- Someone should be in charge of this
- Make this incredibly minor change to one application
- If only my perfect idea would reach SABDFL, *he* would appreciate it, though none of you other fools do.

In the Sandbox, we gently address every idea. Is it a bug in the wrong venue? Is it a dispute or complaint in the wrong venue? Does it clearly describe a real problem that has multiple possible solutions? Has the problem already been solved some other way? Is this a duplicate? Was it discussed by the community before (and the result)? Is the submitter still interested in the idea, or was it a fire-and-forget notion? Is the issue handled within an existing project or team, or does it cross boundaries?

Most submitters, of course, abandon their idea when they realize that nobody will implement it for them...or that they need to do some research or file a bug report or otherwise become a contributing community member.

We do a lot of basic instruction on how the Ubuntu software ecosystem works, and try to change many of them from a customer-mindset to a community-member mindset. That's a hard transition, and we're still trying to find better ways to do it.

This is an opportunity to recruit new members for YOUR project/team, and turn a lot of potential complainers into contributors and advocates. We're trying, and good ideas on improving our methods are welcome. So are more drop-ins from other teams - come in, answer a few project-specific questions, and leave with the contacts for a half-dozen new people interested in your subject.


30-day voting

15% of that 2000 pass the Sandbox - the problem statement is real and clear, and it won't waste the community's time. Some of that 15% is marginal - the problem is real enough, but needs community input to refine.

We leave those marginal ones open for only 30 days, to give the submitter the public feedback they want. These have the clear understanding that we're leaving it open for feedback to help refine the issue - it won't be seen by the Ubuntu Technical Board.

30-day wonders are also helpful to developers who want to use Brainstorm for project-related polling or questions. Just ping a moderator in #ubuntu-brainstorm so we can skip it past the Sandbox for you.


6-month voting

Around 10% of the original 2000 are left open for the full 6-month voting period (and, indeed, left open long after that. We have still-open ideas from 2008).

If you find a question that's relevant to your project or team, and have an answer, please ping a moderator in #ubuntu-brainstorm, so we can put your answer in the "Developer Comments" section of the idea, and close it for you.

Similarly, if the issue has been raised and answered somewhere else (Launchpad, AskUbuntu, Blog Post), just post the link to the answer, and flag the idea so we know to close it.


The Ubuntu Technical Board

Every three months, the UTB selects 10 of the highest-voted ideas to review. 40 a year out of 2000 initial submissions, or around 2%. The 'review' isn't a promise to implement - indeed most result in a "hey, we agree this is a great idea, somebody in the community should implement this..." Some get added to UDS discussions, some turn into milestones for future releases. Some simply become bug reports.

Every idea that the UTB reviews that simply becomes a "hey, great" or a bug report is a wasted opportunity. You didn't need to wait three months for that kind of feedback - by being involved with the right project or team, or filing the bug report yourself, you could have done all that yourself!

We incorporate past UTB feedback into our moderation - for example we now routinely close ideas to create a whole new project unless they include a realistic resource plan. We encourage idea submitters to engage the appropriate bug tracker / upstream project / Ubuntu Team directly whenever possible. We want the best 40 new ideas before the UTB, real head-scratchers that will require research and create discussion and show up at UDS...and then as taskings.


We have resources for your project

Brainstorm doesn't need to be a filter for only the UTB - we can be a structured-community-feedback filter for *lots* of projects and teams. We have a lot of very smart and knowledgeable community members that help refine the ideas and solutions. If your project/team reviews Brainstorm input on a regular basis, please let us know. If you're looking for certain types of ideas, or want us to moderate your relevant ideas in a different way, just pop in to #ubuntu-brainstorm and let us know.


Are you ready for the challenge?

If you're an AskUbuntu or Forums or IRC guru looking for the next challenge to your technical and diplomatic skills, looking to help shape the next generation of contributors...well, come on by.

NTP on a Debian 6 server

This post is an update to my original in March 2011.


NTP is useful to set the time of LAN devices. The correct time is essential for several services. I installed ntp on an almost-always-connected server, which will in turn broadcast the correct time to other devices on my LAN.

internet ntp servers  <--->  my net ntp client / LAN ntp server  <--->  my LAN ntp clients


The ntp program is both client and server (those used to be separate packages). The same ntp gets installed on all devices. You change the settings in the /etc/ntp.conf file. The version of ntp on those devices isn't important - different versions of ntp interact well together (unlike, say, different versions of the deluge torrent client/server)


These instructions are for debian 6, running as root. For Ubuntu, you need to prepend most commands with 'sudo'


  1. Install NTP with the following command:
    apt-get install ntp
  2. Edit the server's /etc/ntp.conf file (if needed). If you want your device to get time from the default internet time servers (in most cases, this is exactly what you want), then skip this step and make no changes.

    In my case, however, my server is both a client of those upstream internet time servers AND a time server to my LAN. Your LAN probably does not need a timeserver - I'm doing this for fun.
    ## Around Line 48
    # If you want to provide time to your local subnet, change the next line.
    # (Again, the address is an example only.)
    #broadcast 192.168.123.255
    
    # Since my LAN is 192.168.1.0, the corresponding broadcast address is at 192.168.1.255
    broadcast 192.168.1.255
  3. No changes to /etc/hosts.allow and /etc/hosts.deny are needed to limit access to ntpd. Access controls are set by the /etc/ntp.conf file, they default to nobody has any access, and we didn't change those rules.
  4. xinted and dnsmasq do not interact with ntpd, and no special configuration is required.
  5. Firewall rules to open udp port 123 for ntp sync messages. Normally, this won't be necessary. Since the ntp client sends the first packet to the upstream internet server, and outbound packets usually are not blocked, the firewall should automatically let the server's response through.

    If an ntp client has a really locked-down firewall (blocking outgoing traffic), then open the client's UDP port 23 to outgoing traffic.
    iptables -A OUTPUT -p udp --sport 123 -j ACCEPT

    If you run a LAN-facing NTP server, then of course you must ensure that LAN-interface UDP port 23 is open to that same inbound traffic from your clients. (your -i interface name will be different)
    iptables -A INPUT -i lan0 -p udp --dport 123 -j ACCEPT 

    If you run an exposed internet-facing NTP server, then you should really be working with ntp.org for security, and to help support the ntp infrastructure!

    In my case, no firewall changes were needed at all. My firewall blocks inbound packets from the internet, not LAN-only packets, and not outbound-packets (or responses).
  6. Restart/update the firewall (how you do that is up to you), and then restart ntp to reload the changed config file. Let's test ntp to see if it's working:
    $ ntpq -p
         remote           refid      st t when poll reach   delay   offset  jitter
    ==============================================================================
    -w1-wdc.ipv4.got 10.0.77.54       4 u  396 1024  377   30.567    1.853   2.901
    *ntp3.junkemailf 209.81.9.7       2 u  465 1024  377   64.788   -0.072   1.269
    +vimo.dorui.net  208.90.144.52    3 u  633 1024  377   32.876   -1.081  30.206
    +aeolus.seobeo.c 193.67.79.202    2 u  184 1024  377  110.840    0.577   1.790
     192.168.1.255   .BCST.          16 u    -   64    0    0.000    0.000   0.000
    
    Looks correct. The first character of each row (*/+/-) is the status of each upstream server. See the explanation. The 'when' column is the number of seconds since the last check of that server. The'poll' column is the number of seconds between checks. The first four rows are upstream internet servers. The last row is the LAN broadcast, which is why it doesn't have an upstream status.
  7. The other ntp clients on the LAN need to be modified to listen for the new ntp server. Left alone, they will pull time from the upstream internet time servers (good). But, of course, I now have a server broadcasting time, so let's set each device on my LAN to listen for it. Plus, I still want them to get time from upstream in case my ntp server goes down or starts sending bad time.

    Log in to each device, and look at their /etc/ntp.conf (though it may be in a different location or names differently).

    Here's an example /etc/ntp.conf change from an Ubuntu system on the LAN, starting at around Line #15. We added the LAN ntp server, and marked it as the preferred source. We added minpoll to the internet servers to increase the time between pollings.
    # Specify one or more NTP servers.
    server kiwkak.dyndns.org prefer
    
    # Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
    # on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
    # more information.
    server 0.ubuntu.pool.ntp.org minpoll 12
    server 1.ubuntu.pool.ntp.org minpoll 12
    server 2.ubuntu.pool.ntp.org minpoll 12
    server 3.ubuntu.pool.ntp.org minpoll 12
    Restart ntp (in debian 'service ntp restart'. For ubuntu 'sudo service ntp restart') to reload the new configuration file.

    Let's also take a loot at their ntp status:
    $ ntpq -p
         remote           refid      st t when poll reach   delay   offset  jitter
    ==============================================================================
    *adsl-76-229-175 184.105.182.7    3 u   28   64  377    0.274    0.805   0.209
     ntp1.Rescomp.Be 169.229.128.214  3 u  838 1024    3   63.979    3.262   0.424
     cheezum.mattnor 129.7.1.66       2 u  818 1024    3   34.490    0.145  25.810
     host2.kingrst.c 204.9.54.119     2 u  789 1024    3   22.359    0.721  17.671
     vf1.bbnx.net    128.4.1.1        2 u  824 1024    3   68.227   -0.820   1.466
    

    This looks good. See how the local server is preferred, and gets checked more often than the backup upstream servers. And the backup upstreams are reachable, but not currently used.
  8. The server itself may not always be the network router/firewall. I automagically switching between server between router and non-router roles using my kingbaron script. I use a script and two config files to change how ntp runs based on if the system is a router (Network King, runlevel 3) or just a LAN client (Faithful Baron, runlevel 4). The decision logic operates in runlevel 2.

    Create two .conf files, one for each runlevel. Let's call them /etc/ntp-king.conf and /etc/ntp-baron.conf. Look at all the .conf stuff above for the contents of those files.

    Use the following command once to automatically prevent ntp from starting in runlevel 2 (the decision logic level), and to stop ntp if you manually switch to runlevel 2 due to a loss of connectivity or for maintenance:
    update-rc.d ntp stop 2

    Add the following patch to /etc/init.d/ntp to restart ntp with the appropriate config files upon runlevel changes.
    test -x $DAEMON || exit 5    # Insert after this line
    
    current_runlevel=echo $(runlevel | cut -d' ' -f2)
    if [ current_runlevel -eq "3" ]; then
         NTPD_OPTS="$NTPD_OPTS -c /etc/ntp-king.conf"
    elif [ current_runlevel -eq "4" ]; then
         NTPD_OPTS="$NTPD_OPTS -c /etc/ntp-baron.conf"
    
    This covers the common use cases (booting, manual force of decision logic), but doesn't cover everything - if I manually switch to runlevels 3/4/5, ntp won't automatically check the config.

Saturday, November 19, 2011

The Unexpected Success of Ubuntu Brainstorm

Once upon a time, there was a busy, vibrant community...with some communication issues. Yes, I'm talking about the Ubuntu community. Back in 2007.

So Ubuntu created a website to foster community discussion about ideas to improve Ubuntu. http://brainstorm.ubuntu.com

Conventional Wisdom from the old-timers who remember those heady days is that it didn't work out. The site was quickly overwhelmed with bugs (not ideas), complaints (not ideas), and unrealistic expectations. It didn't work.

And Conventional Wisdom had those facts right...but reached entirely the wrong conclusion! Brainstorm has been successful in ways that were unexpected at the time.


1) Brainstorm is indeed lousy at directly turning submissions into code.

Well, we knew this already, didn't we? There is no roomful of monkeys poised over their keyboards eagerly awaiting the next idea to begin cranking out Shakesperian code. There never was. There never will be. Implementation was never really expected to be a metric of success...community action was supposed to be the metric.


2) Brainstorm is a great early-warning system for controversy.

What? You can avoid getting blindsided? Brainstorm is awesome at reflecting the community's (lack of) consensus on a wide range of issues. For example, when 'close window' window button changed sides, the ideas on the topic were plentiful. Similarly, today most ideas are about Unity. Brainstorm is also a pretty good barometer of whether an issue is temporary or chronic, and our moderators are excellent at separating valid issues from mere whining (so you don't have to).


3) Brainstorm is a great place to recruit enthusiastic new members.

The website is a portal-of-entry for users who are just starting to get involved, but don't understand the community's structure yet, or how the various teams and projects interact.


4) Brainstorm keeps project community input manageable.

If you are involved with a project, you know how challenging it is to manage certain types of community feedback. Brainstorm has reviewers and moderators who do nothing but handle those tough cases. Better yet, it's set up to let the community itself moderate feedback for you. And it's set up so that you only answer an issue once...ever.


5) Brainstorm finds your blind spots.

Maybe it's documentation, maybe it's a workflow, maybe it's a use case, maybe it's a legacy, maybe it's something else. The trend of feedback across years helps you improve user experience.


So, in the spirit of Ubuntu Community Appreciation day,

- Thanks to nand for writing and maintaining Ideatorrent.

- Thanks to the best moderators and reviewers in the world: Vahan Harutyunyan, DarwinSurvivor, Komputes, DrG, alourie, andruk, and Thonixx

Your valiant efforts to raise the quality of discussions and ideas, and to uphold the Ubuntu Code of Conduct, challenge me to strive. I'm very proud to work with people of such high caliber.

Tuesday, November 1, 2011

Move IPTables log events to a separate logfile

Today some botnet tried to connect to my server over 26,000 times in five hours. They might still be trying.

I have strong firewall protection, and I log all those dropped packets from the firewall. but the records of more than 26,000 dropped packets is filling my syslog and making it unusable.

I used the instructions here to shift that reporting to a separate iptables log, plus enabled logrotate so it gets changed out daily.

Sunday, October 30, 2011

deluged on a server

I want to move my (quite limited) torrenting from my laptop onto the server. Here's how to run headless deluge on a server, and connect to it from the deluge client. (Instructions).

Since my server (Debian 6.0.3) is at version 1.2.3, but my Laptop (Ubuntu 11.10) is at version 1.3.3, using the GTK client won't work. I tired and tried, but ultimately the incompatibility defeated me...

...so instead of the GTK client, we'll use the web client. (There's also a console client)





Setup and start the deluged server

1) Run the following on the server as root:
apt-get install deluged deluge-console deluge-web
# To set this for automatic startup at boot, 
# see http://dev.deluge-torrent.org/wiki/UserGuide/InitScript

2) Run the following on the server as a user (not root)
deluged         # Run as USER to create the .config directory
pkill deluged   # Stop deluged

#Add an entry to the /home/USERNAME/.config/deluged/auth file
echo "USERNAME:my__deluge-only_password:5" >> /home/USERNAME/.config/deluged/auth

# Use deluge-console to change the config setting, allowing remote access.
# (For some reason, if you change .config/deluge/core.conf, the change is not persistent!)
deluge-console
config -s allow_remote True
exit

# Start deluged and deluge-web to launch the server and the web socket
deluged
deluge-web --fork

Connect to the server from the laptop:
Open a web browser to the server, port 8112: http: me.myserver.org:8112
Use the same password as the auth file (the "my_deluge-only_password")

And you should be in!

Try it with a small torrent (like a Debian Businesscard .iso)

Using runlevels to demote a network king to a mere baron

I have put enough services onto my server that it has become a single-point of failure. It's a router, a DSL modem, backup storage, and has network-shared drive, plus a few other cool things.

The key point of failure is the combination of Modem + Router. The PCI DSL card requires a custom driver, and sometimes after a system upgrade it needs to be reinstalled. The details of the wanrouter driver are here.

What I need is a failover mode: If the DSL fails to work, I want to use my old external modem and router. So I still want the system to run, but as a dchp-client server instead of a router.

Let's use some startup logic and runlevels to define two roles for the server: Network King routing over DSL, and faithful Baron merely connecting over wi-fi to the Linksys. And a bit of connective tissue so the machine automagically boots into the correct role, plus can be switched manually.

Internet <------+ Network King +-----> LAN

Internet <------+ Other router +------> LAN <------+ Faithful Baron 

Runlevel 1 - startup (Don't touch this)
Runlevel 2 - network testing
Runlevel 3 - server (Network King)
Runlevel 4 - client (Faithful Baron)
Runlevel 5 - unchanged from stock install
Runslevel6 - reboot (Don't touch this)

Decision logic:
If the server can connect to the internet over the dsl interface, then it is a King
Otherwise, it is a Baron.

Issues:
1) I need to change the LAN IP address of the server so it doesn't conflict with the router anymore!
2) All changes to the server must be tracked and undoable

Changes to the external router
Port-forward from the internet to the Baron (easy, one DMZ setting or separate port-forward settings for each service)

Server setup changes
1) Create a new directory to hold the three small scripts we are going to make, so you can keep track!
mkdir /root/startup-scripts

2) It's possible to create one really ugly /etc/networking/interfaces file, but let's not do that. Instead, we'll create separate interface files for runlevels 3 and 4. For convenience, let's put a link to them next to the original interfaces file.
cp /etc/network/interfaces /root/startup-scripts/runlevel-3-interfaces
cp /etc/network/interfaces /root/startup-scripts/runlevel-4-interfaces
ln /root/startup-scripts/runlevel-3-interfaces /etc/network/interfaces
ln /root/startup-scripts/runlevel-4-interfaces /etc/network/interfaces

3) Edit the runlevel 3 file (/root/startup-scripts/runlevel-3-interfaces)
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# This file is ONLY for runlevel 3 (Network King [router] mode)

# The loopback network interface
auto lo
iface lo inet loopback

# The ethernet jack and wi-fi antenna in bridged server mode
iface eth0 inet manual
iface wlan0 inet manual
     up hostapd -B /etc/hostapd/hostapd.conf
     down ifconfig mon.wlan0 down
     down pkill hostapd
auto br0                       
iface br0 inet static
     # Adding and removing the slave eth0 and wlan0 interfaces
     # is handled by /etc/init.d/kingbaron
     address 192.168.1.1
     broadcast 192.168.1.255
     netmask 255.255.255.0
     network 192.168.1.0
     up hostapd -B /etc/hostapd/hostapd.conf
     up route add -net 239.0.0.0 netmask 255.0.0.0 br0
     down ifconfig mon.wlan0 down
     down pkill hostapd
     down route del -net 239.0.0.0 netmask 255.0.0.0 br0

iface dsl-provider inet ppp
     pre-up /sbin/ifconfig dsl0 up # line maintained by pppoeconf
     provider dsl-provider

auto dsl0
iface dsl0 inet manual

4) Edit the runlevel 4 file (/root/startup-scripts/runlevel-4-interfaces)
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# This file os ONLY for runlevel 4 (Network dhcp client mode)

# The loopback network interface
auto lo
iface lo inet loopback

# The ethernet jack in client mode
auto eth0
allow-hotplug eth0
iface eth0 inet dhcp

# The wi-fi antenna in client mode
auto wlan0
iface wlan0 inet dhcp
     pre-up ifconfig wlan0 down
     pre-up iwconfig wlan0 mode Managed
     pre-up iwconfig wlan0 essid MY_LAN_NAME

5) Let's edit the original /etc/network/interfaces file to reduce startup time by not automatically raising the eth0 and wlan0 interfaces. We don't need those in runlevel 2, since only the DSL line will needs to be brought up.
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The ethernet jack in client mode
# (Disabled during initial boot)
allow-hotplug eth0
iface eth0 inet manual

# The wi-fi antenna in client mode
# (Disabled during initial boot)
auto wlan0
iface wlan0 inet manual
     pre-up iwconfig wlan0 essid Klein-Weisser

# The following lines are auto-generated for the dsl connection

auto dsl-provider
iface dsl-provider inet ppp
     pre-up /sbin/ifconfig dsl0 up # line maintained by pppoeconf
     provider dsl-provider

auto dsl0
iface dsl0 inet manual

6) Create a new file for the startup testing and decision logic: /root/startup-scripts/kingbaron
#!/bin/bash

### BEGIN INIT INFO
# Provides:             runlevel_chooser
# Required-Start:       $network $remote_fs $syslog wanrouter
# Required-Stop:        $network
# Default-Start:        2
# Default-Stop:
# Short-Description:    Choose runlevels based on testing network connection to an interface
### END INIT INFO

# Functions

start_king_mode () {
   # If coming from runlevel N or 4, need to change from dhcp to static/Master
   [ runlevel=="4 2" ] && ifdown -a --interface=/etc/network/runlevel-4-interfaces
   [ runlevel=="N 2" ] && ifdown -a

   # If the br0 interface does not exist (coming from runlevel N), create it.
   [ $(brctl show | grep -c br0) -eq 0 ] && brctl addbr br0

   # Add the slave interfaces to br0
   [ $(brctl show | grep -c eth0) -eq 0 ] && brctl addif br0 eth0
   [ $(brctl show | grep -c wlan0) -eq 0 ] && brctl addif br0 wlan0

   # Bring up the King mode interfaces (except dsl0 and ppp0, which are already up)
   ifup -a -v --interfaces=/etc/network/runlevel-3-interfaces

   # Test that ifup worked
   [ $(ifconfig | grep -c mon.wlan0) -eq 0 ] && logger -i -s -t kingbaron "Failed to bring up wlan0...Sorry"
   [ $(ifconfig | grep -c br0) -eq 0 ] && logger -i -s -t kingbaron "Failed to bring up br0...Sorry"

   logger -i -s -t kingbaron "Network should be up now. If not, try 'ifconfig' for LAN interfaces and 'wanrouter' for the DSL interface"
   telinit 3
   exit 0
}

start_baron_mode () {
   # Shut down the dsl0 and ppp0 interfaces (not used in Runlevel 4).
   # Sometimes the signal needs to be sent twice
   [ $(wanrouter status | grep -c stopped) -gt 0 ] || wanrouter stop
   [ $(wanrouter status | grep -c stopped) -gt 0 ] || wanrouter stop

   # If coming from runlevel 3, need to change from static/Master to dhcp
   # If coming from runlevel N or 4, we can keep the same interfaces
   [ runlevel=="3 2" ] && ifdown -a --interface=/etc/network/runlevel-3-interfaces

   # If br0 is up, bring it down. If it still has slaves from runlevel 3, unslave them
   [ $(ifconfig | grep -c br0) -gt 0 ] && ifconfig br0 down
   [ $(brctl show | grep -c wlan0) -gt 0 ] && brctl delif br0 wlan0 && ifconfig wlan0 down
   [ $(brctl show | grep -c eth0) -gt 0 ] && brctl delif br0 eth0 && ifconfig eth0 down

   # If wlan0 is stuck in Master mode from runlevel 3, unstick it
   [ $(ifconfig | grep -c mon.wlan0) -gt 0 ] && pkill hostapd && ifconfig wlan0 down && iwconfig wlan0 Managed

   # Bring up the Baron Mode interfaces, ignoring anything already up
   ifup -a -v --interfaces=/etc/network/runlevel-4-interfaces

   # Sometimes the network fails to come up, especially if it didn't go down properly
   # Check for the most common errors (like WiFi not going up) and try to autofix
   if [ $(ifconfig | grep -A2 wlan0 | grep -c inet) -eq 0 ]; then
      logger -i -s -t kingbaron "Wireless failed to come up. Resetting and trying again..."
      ifconfig wlan0 down
      iwconfig wlan0 mode Managed
      iwconfig wlan0 essid MY_ESSID
      ifconfig wlan0 up
      dhclient -v wlan0
   fi
   logger -i -s -t kingbaron "Network should be up now. If not, try 'ifconfig' and 'iwconfig'"
   telinit 4
   exit 0
}

logger -i -s -t kingbaron "Testing for DSL connectivity"

# Check for the existence of a the DSL interface. If it exists, try to get a connection
# If the internet is reachable, goto runlevel 3 (King mode). Else goto runlevel 4 (Baron mode)

# If wanrouter is not already running, then start it
flag="wanrouter off"
[ $(wanrouter status | grep -c Connecting) -eq 0 ] && flag="wanrouter on"
[ $(wanrouter status | grep -c Connected) -eq 0 ] && flag="wanrouter on"
[ $flag=="wanrouter off" ] && wanrouter start

# If the test interface does not exist, then start client mode
if [ $(ifconfig | grep -c dsl0) -eq "0" ]; then
   logger -i -s -t kingbaron "The DSL interface (dsl0) does not exist. Entering dhcp client mode"
   start_baron_mode
fi

# If the test interface exists, then wait for wanrouter to start up
# Average start time is about 20 seconds
logger -i -s -t kingbaron "Found the DSL interface. Waiting up to 40 seconds for the DSL link (dsl0) to come up"
i="0"
while [ $i -lt 40 ]; do
   sleep 1
   i=$[$i+1]
   [ $(wanrouter status | grep -c Connecting) -gt 0 ] || i=100
done

# If time expires without the wanrouter starting, print the error and start client mode
if [ $i -lt 100 ]; then
   logger -i -s -t kingbaron "dsl0 interface failed to come up. Entering dhcp client mode"
   start_baron_mode
fi

# If the wanrouter comes up properly, then wait for a ppp connection
logger -i -s -t kingbaron "dsl0 up. Waiting up to 40 seconds for a PPPoE connection (ppp0)"
pon dsl-provider
i="0"
while [ $i -lt 40 ]; do
   sleep 1
   i=$[$i+1]
   [ $(route | grep -c default) -gt 0 ] && i=100
done

# If time expires without the ppp connection starting, print the error and start client mode
if [ $i -lt 100 ]; then
   logger -i -s -t kingbaron "ppp0 failed to come up. Entering dhcp client mode"
   start_baron_mode
fi

# If all has gone well, and the ppp connection comes up
logger -i -s -t kingbaron "ppp0 came up. This system has DSL connectivity. Starting Router services"
start_king_mode

7) Install the script:
chmod +x /etc/startup-scripts/kingbaron            # Make executable
ln /root/startup-scripts/kingbaron /etc/init.d/    # Hardlink to init.d
update-rc.d kingbaron defaults                     # Symlink to runlevel 2

8) Take a look at /etc/rc2.d/. See all those router and server services that shouldn't operate in runlevel 2? Or shouldn't operate in runlevels 2 and 4? Use the command "update-rc.d $Name disable 2" to disable the appropriate services in runlevel 2 (or 4).

...And do a whole lot of tweaking and testing, and voila! An automated detection and failover system. If the DSL line is active, router services start and the interfaces come up in static/master mode. If the DSL line isn't active, router services don't start and the interfaces come up in dhcp mode. Runlevel 2 is the decision mode, runlevel 3 is the King (router) mode, and runlevel 4 is the Baron (dhcp) mode.

All the server services (samba, cups, etc) still operate, regardless. And you can manually reset with the command 'telinit 2' to make the system reset the interfaces and router services.

TIP: Look for related posts using the kingbaron tag.