Daniel Pocock: $75,000 to explore free software during maternity leave?
| Publisher: | William Morrow |
| Copyright: | 2008 |
| ISBN: | 0-06-147409-6 |
| Format: | Hardcover |
| Pages: | 935 |
| Series: | Sirantha Jax #2 |
| Publisher: | Ace |
| Copyright: | September 2008 |
| ISBN: | 0-441-01627-8 |
| Format: | Mass market |
| Pages: | 312 |
This is an essay form of a talk I have given today at the Cambridge
Mini-debconf. The talk was videoed, so will presumably show up in the
Debconf video archive eventually.
Abstract
Debian has a long and illustrious history. However, some of the things
we do perhaps no longer make as much sense as they used to do. It's a
new millennium, and we might find better ways of doing things. Things
that used to be difficult might now be easy, if we dare look at things
from a fresh perspective. I have been doing that at work, for the
Baserock project, and this talk is a compilation of observations based
on what I've learnt, concentrating on things that affect the
development workflow of package maintainers.
Introduction and background
I have been a Debian developer since August, 1996 (modulo a couple of
retirements), and have used it a little bit longer. I have done a
variety of things for Debian, from maintaining PGP 2 packages to
writing piuparts to blathering excessively on the mailing lists.
My day job is to develop the Baserock system at Codethink. Baserock is
a set of tools and workflows for developing embedded and appliance
Linux systems. If you squint, it looks a bit like a source-based Linux
distribution. I have worked on Baserock since September, 2011.
Some of Baserock's design has been influenced by my experience with
Debian. With Baserock I have the chance to fix all the things that are
wrong in Debian, and this talk is me giving back to Debian by pointing
out some the things I feel should be fixed. I don't have solutions for
these problems: this is a bug report, not a patch. It's also perhaps a
bit of a rant.
I am specifically concentrating here on technical and tooling issues
that affect the development process of Debian. I excluding social
issues.
I am also not trying to get Debian to switch to Baserock. Baserock is
targeting embedded and appliance systems, and makes simplifying
assumptions based on those targets, which Debian does not get to do. I
am pointing out problems, and I am outlining solutions as implemented
in Baserock, when I think the concept carries over well to Debian.
Build tools should be intelligent, packaging should be dumb
In Debian, the fundamental tool for compiling the upstream code and
assembling a binary package is dpkg-buildpackage. It uses
debian/rules, which is a Makefile with targets with specific names
and semantics. By executing the right targets in the right order,
dpkg-buildpackage tells the source package to build the binary
package.
On the one hand, this is a nice design, because it abstracts away the
large variety of upstream build systems into one API for
dpkg-buildpackage to use. On the other hand, it puts all the
intelligence for how packages are built into the packages.
Making packaging intelligent, rather than the build tool, means
packagers need to do more work, and there's more work to do when, say,
the Debian policy changes, or when there are other changes that affect
a large number of packages. If packaging is intelligent, then every
package needs changes. If the build tool is intelligent, then you
change the build tool and re-build everything.
In Baserock we put as much intelligence as we can into the Morph tool,
which drives the build process. It turns out that today, unlike in
1995, most upstream projects use one of a handful well-known build
systems: autotools, cpan, cmake, Python distutils, etc. With just a
little extra logic in Morph we avoid having any delta against upstream
in Baserock. This doesn't work for quite all upstream projects, of
course, but we've spent the 2% (two, not twenty) of effort that solves
80% of the problem.
In recent years, the dh approach to packaging has made a lot of
packages be able to have only a minimal, 3-line debian/rules file.
This is excellent. Wouldn't it be nice if even that wasn't needed?
It'd save thousands of files in source packages across the archive, at
least. It would be easy to: if the file is missing, have
dpkg-buildpackage assume the 3-line version by default.
Getting rid of a single file is, of course, not a particularly big
win. The big win is the change in mindset: rather than dealing with
all new issues in development by adding yet more fields to
debian/control and more optional, competing tooling outside the core
toolset, if you improve the tools everyone uses, then everyone's
packages gets better.
The goal should, in my opinion, be that for the large number of
packages where upstream uses a well-known, well-behaved build system,
and uses it in a reasonably sensible way, the Debian source package
should not require anything added to make the package build. There
will still be a need to add some stuff, such as the debian/copyright
file, to make a good Debian package, but just getting the package to
build should require nothing extra. (Side note: wouldn't it be nice if
there was a well-known, widely used way to mark up copyright
information so that debian/copyright could be constructed and
updated automatically?)
Configuration file handling on upgrades: add ucf to dpkg already
In the 1990s, dpkg had excellent handling of configuration files and
merging local changes with changes from the new package version, but
it was excellent only because it tried to do that at all, and mostly
nothing else did. It hasn't changed much, since, and it's not
excellent on any absolute scale.
We have the ucf tool, which can do a better job, but requires to be
added to each package wanting to use it. Why don't we make dpkg
smarter, instead? If ucf is not not good enough to be merged
wholesale into dpkg, let's write something better.
Making every package maintainer use ucf manually is just wasteful.
This is not the kind of thing that should be done for each package
separately: the package manager should be smart so that packaging can
be stupid.
The goal should be that dpkg is smart enough in its configuration
file handling that having the package do it is a very rare special
case.
Clean building shouldn't be hard
The basic tool for building a package is dpkg-buildpackage. It is
ever so slightly cumbersome to use, so there are some wrappers, most
importantly debuild. However, if you're making a build intended to
be uploaded to the Debian archive, you should be doing a clean build.
This means having to learn, configure, and use yet more tools.
A clean build is important: security updates, development, debugging,
quality control, porting, and user support become more difficult if we
don't know how a package was built, and can't reproduce the build. It
gets harder to keep build dependencies correct, making it harder for
everyone to build things.
Luckily, Debian has solved the clean build problem. Unluckily, it has
solved it multiple times, creating the problem of having to choose the
clean building approach you want to use. The default way of building
is not clean, so then you have to remember to use the non-standard
way. You also get to spend time maintaining the clean build
environments yourself, since that doesn't seem to be fully automated.
None of this is hard, as such, but it's extra friction in the
development workflow.
The primary approaches for clean building in Debian seem to be
pbuilder, cowbuilder, and sbuild. I happen to use pbuilder
myself, because it's what's been around the longest, but I make no
claim of having made an informed choice.
That is part of the problem here: why should I have to spend the
effort to become informed to make a choice well? Why is the default
way of building not clean? Don't say performance: Morph sets up a
clean staging area in seconds, and does not offer you a choice of not
doing so. It's a chroot, with everything but the build tree hardlinked
from cached, unpacked build dependencies, and protected using
read-only bind mounts.
What's more, this approach avoids having to maintain the pbuilder
base tarballs or sbuild chroots manually. It's all automatic, and up
to date, for every build. Furthermore, the staging area contains only
the specified build dependencies, and not anything else, meaning a
build fails if a build dependency is missing, rather than succeeding
because it happens to be in the default set of packages the build tool
installs.
Mass building shouldn't be hard
Suppose you want to try out a large-scale change in Debian. It might
be trying out a new version of GCC, or using llvm's clang as the
default C compiler, or updating glibc, or doing a large library
transition such as a new version of GTK+, or trying a new dpkg
version, or even something more exploratory such as changing the
default optimisation flags for all packages to see what breaks.
All of these will require you to at least rebuild all affected
packages. Ideally you'd test the built packages as well, but let's
concentrate on the building for now.
Here's what you do. You make the changes you want to try out, and
build those packages. You create a dedicated APT repository, and
upload your packages there. You configure your build environment to
favour that APT repository. You make a list of all reverse build
dependencies of the packages you changed. You write a script to build
all of those, preferably so that if you change A, and rebuild B, then
you also rebuild C which build depends on B. Each rebuilt package you
also upload to your APT repository. You keep track of the build log,
and success or failure, of each build.
The people in Debian who do this kind of stuff regularly presumably
have tools for doing it. It shouldn't be a rare, special thing,
though. If my package has reverse build dependencies, I should at
least consider testing building when I'm making changes. Otherwise, it
might take years until the reverse build dependencies are rebuilt, and
the problem is only found then, making it harder to fix.
To be fair, building a lot of packages takes a lot of resources. It's
not feasible to rebuild everything in Debian every time there's any
change to, say, eglibc. However, it's feasible to do it, for large
subsets of the archive, without huge hardware investments.
One VCS to rule them all
In 1995 there was really only one relevant version control system:
CVS. It was not a great tool. In 2000, another contender existed:
Subversion. It fixed some problems in CVS, but still wasn't a great
tool. In 2005, there was a great upheaval and distributed version
control systems started to become mainstream. There were a large
handful of them. In 2010, it was becoming pretty clear that git had
won. It's ugly, but it's powerful.
I'm not going to debate the relative merits of different version
control systems. Until recently, I was a Bazaar boy, and all of my
personal projects were kept in Bazaar. (I have recently switched
everything to git.)
There are, however, strong benefits from everyone using the same
system. Developers don't need to learn a dozen version control
systems. Tools that operate on many repositories are easier to write
and maintain. Workflows become simpler if one system can be assumed.
Debian has a strong historical tendency to choose every option. This
is sometimes a good thing, and sometimes a bad thing. For keeping
source packages in version control I believe it is to be a bad thing.
The status quo is that a Debian source package may not be in version
control at all, or it might be in any version control system.
This is acceptable when everyone only ever needs to maintain their own
packages. However, in a distribution the size of Debian, that is not
the case. NMUs, security support, archive wide transitions, and other
situations arise when I might need to change yours, or you might need
to change mine.
We try to work around this by having a complicated source package
format, using quilt to maintain patches to upstream semi-manually in
a debian/patches directory. This is an awkward workflow. It's a
workflow that trips up those that are not used to it. (I know quilt
is a patch management system, not a version control system. I think
git does it much better anyway.)
It would be oh so much easier if everyone kept their source packages
in the same, real version control system. I don't even care what it
is, as long as it is powerful enough to handle the use cases we have.
Imagine a world where every Debian source package is kept, for
argument's sake, git, and everyone also uses the same layout and
roughly the same workflow to maintain it. What would this mean?
It would mean that if you want to inspect the history of your package,
you know how to do that. If you want to merge in some bugfix from
upstream code, you know how to do that, without having to figure out
which of the several source package formats are in use.
It would make feasible the development of more powerful, more higher
level tooling. For example, it would allow Debian to have what we call
system branches in Baserock. In Debian we have stable, testing,
unstable, and experimental. We may get something like Ubuntu's PPAs,
or perhaps an improved version of those. These are very poor versions
of system branches, just like quilt is a poor way to manage patches
and deltas against upstream. For example, you can upload an
experimental version of gccto experimental, but then nobody else
can upload another experimental version. You can set up your own PPA
for this, but you'll still be affected by all the uploads to
unstable while you're working.
A Baserock system branch is a branch of the entire system, or the
entire distribution in the case of Debian. It is isolated from other
system branches. In branch in an individual repository is a well-known
concept. A system branch is conceptually like branching every
repository in the distribution at once. The actual implementation is
more efficient, of course.
This would be possible to implement without standardising on one
version control system, but it would be much harder to implement, and
would have to live with the lowest common denominator for features.
CVS and Subversion, for example, don't really to merges, where Bazaar,
Mercurial, and git do. Possible does not mean feasible.
Any work you do in a system branch is isolated. Your work doesn't
affect others, and theirs doesn't affect yours, until a merge happens.
This is a simple, but very powerful tool.
Cheap system branches, and powerful merging, makes it possible to do
experiments safely, with little fuss. Combine that with being able to
build everything cleanly and quickly, and get into a situation where
there's no need to have make technical decisions based on arguments on
mailing lists, and instead they can be done by choosing by looking at
working code.
I don't know how this could be implemented in Debian, but think about
it. If Debian could have this, it might many archive-scale changes
easier.
debian/rules clean: really?
One of the silliest things we require of packages is that they have a
debian/rules clean rule that cleans up after a build perfectly so
that we can do repeated builds in the same source tree.
Let's just use git clean -fdx instead.
This is a problem that is superbly well suited for automation. There
is no point whatsover making packagers do any manual work for this.
Large scale semi-mechanical changes require too much effort
About a decade ago, we decided to follow a new version of the
Filesystem Hierarchy Standard and transition from /usr/doc to
/usr/share/doc. This was an almost entirely mechanical change: in
many cases, a mere rebuild would fix it, and in almost every other
case it was just a minor tweak to the packaging. A one-line change.
It took us seven years to do this.
Seven years. Think about it.
In a recent discussion about building R binary data files from source
at package build time it was suggested that we take 2-3 release cycles
to get this done. That's four to six years. Think about it.
These are not isolated cases. Every time we need to make a change that
affects more than a small handful of packages, it becomes a major
undertaking. Most of the time all the people involved in this are
agreeable to the change, and welcome it. The change takes long because
it requires co-ordinating a large number of people. Sometimes people
are just busy. Sometimes they've left the project, but haven't
properly orphaned their packages. Waiting for a timeout for answers
about packages drags the process longer.
Mechanical changes, or semi-mechanical ones, which are very easy and
very quick to do should not take years. They should take an evening,
no more.
There's no end of changes we might want to do like this. In 2005 and
2006 I filed a few hundred bugs from failed piuparts runs. They're
still being fixed, even when the fix is simple, such as adding a
postrm script to remove, when the package is purged, a configuration
file created by postinst, or starting the service with invoke-rc.d
rather than running an init.d script directly. Mostly one-line
changes.
There's more mechanical changes that might happen. For example,
changing the value of the VCS-Browser field when the Debian version
control server changes domain names.
It's not just about simple, mechanical changes, either. Transitions of
important library packages, for example, which require changes to
reverse dependencies due to a changed API are another source of pain.
What should be a few evenings of build fixes can drag out to months of
co-ordination.
This is caused partly by technical issues, and partly due to social
issues. The main social issue is that we have quite a strong ownership
of packages, and NMUs are to be done carefully, and only in some
cases. This is both good and bad, and I won't discuss that aspect now.
The technical issues are that our tools are primarily intended for
maintaining individual packages, rather than all of them together,
making it harder to make even simple changes in large number of
packages.
In addition to easy mass building and system branches, as outlined
above, large-scale changes would require testing tools so that you
don't build the new package versions, but also test things
automatically. Essentially, CI at the distribution level.
Conclusion
I've listed above a small variety of problems I see in the Debian
development processes and tools. They're not the important part of
this talk. The important part is that it we, the Debian developers,
should look at our tools, and workflows, critically, and improve them
when we can. Even small improvements are very useful, when they affect
each of our twenty thousand source packages. The important change I
argue for here is one in mindset, rather than any specific problem in
any tool. We need a mindset of constant, incremental improvement for
our tools.
| Series: | Poseidon's Children #1 |
| Publisher: | Ace |
| Copyright: | January 2012 |
| Printing: | June 2012 |
| ISBN: | 0-441-02071-2 |
| Format: | Hardcover |
| Pages: | 505 |
For those with fond memories of the very successful DebConf13...
This photo is actually from a few years ago, but the white stuff has started to appear in some parts of the country. Maybe someone local will even be able to sneak down there and draw the Debian swirl in the snow.
We ve been trying to build Mono on MIPS in Debian for a long time. Just under a decade, in fact. Mono 0.29.99.20040114-3 was the first attempt, back when the Mono source was 10 meg, not today s ~80.
It never worked though. Not once. At the end of 2004, 10 upstream versions later, we gave up, and turned off mipsel as a target architecture in the package.
When I became a Debian Developer in 2009, one of the first things I did was try again with Mono on various previously unsupported architectures, by running a build on the Debian porterboxes. Supposedly MIPS support was there, as evidenced by all the MIPS-related files in the source tree. But I d try it, and it d fail, and upstream would say works for me . I repeat the process every major release or so, to see what s changed.
The breakthrough
Spurred by the removal of two bitrotted architectures (IA64 and SPARC), I decided to try again, this time investigating more deeply into the reason for the failures, with the help of upstream developer Alex R nne Petersen. A couple of hours of IRC-driven gdb and test program disassembly later, a seemingly innocent comment flagged something in my brain:
09-07-2013 15:10:11 < alexrp!~zor@baldr.rfw.name: TIL that mul and mult are not the same thing on mips
Why is this notable? Well, MIPS processors lack a whole bunch of instructions which are commonly used in assembler. MUL is one of them it s valid MIPS assembler, which is expanded to MULT/MFLO when compiling. Call it a macro, or a mnemonic, or shorthand the preferred term is pseudoinstructions . So what s the issue?
09-07-2013 15:18:27 > directhex: mono isn't trying to use a mul instruction, right? i mean, that instruction doesn't exist as far as the cpu is concerned, it's a macro the compiler does things with
See where this is headed?
09-07-2013 15:23:59 > directhex: mini/mini-mips.c:#define USE_MUL 1 /* use mul instead of mult/mflo for multiply */
Argh.
See, the thing about MIPS pseudoinstructions is they may be real instructions on a given CPU implementation. Strictly speaking MUL isn t a standard instruction, but a given CPU might have it anyway, to make multiplication a little faster (by using only one instruction, not two, for multiplication). In this case, the Debian MIPS infrastructure is based around ICT Loongson-2E processors which don t have that extension but the upstream Mono developers were building and testing on an extended CPU, never seeing the issue themselves.
Flipping that define to 0 (and amending the instruction length setting in another file) fixed the build. Mono was running on MIPS for me for the first time ever.
Digging through the history in git showed just how annoying this implementation quirk was. USE_MUL was added in late 2008 replacing a previously used #if 1 . The mult/mflo version of the code existed in the Mono source since the first time the full MIPS port was committed in 2006, but we never saw it.
The breakage
So, with that patched to work, I added mipsel to the Experimental build of Mono which still failed. The runtime would build fine, but the class library build would fail at random times, with random meaningless stack traces. Unrepeatable. Some kind of race condition. The build would eventually succeed if I hammered make a few times, but that s no good for the Debian build daemons. Back to square one
except I had an epiphany yesterday. I have heard more than once that Loongson processors are missing a few instructions. What if one of those was being hit, intermittently? I started doing a search in places that might need to work around that kind of issue, and found this. A patch to binutils in 2009, replacing one no-op instruction with another, when /usr/bin/as is fed the -mfix-loongson2f-nop flag.
Turns out NOP is another pseudoinstruction on MIPS. Well, more of an alias. The opcode 0 000000 is Shift Left Logical with 0 registers and 0 data, which is a no-op. But on all but the latest generation of Loongson-2F chips, that opcode can, under heavy load, fail causing inconsistent state in the CPU registers. The flag to as replaces sll 0,0,0 with or $at,$at,0 , which is also a no-op instruction, but doesn t trigger the failure on Loongson-2F chips (and 2E chips, although that s not stated in the documentation).
As long as ALL your programs get fed through as , you don t have a problem, since it uses the replacement opcode but what if you use a JITter to generate your own opcodes? Oh fuck, it couldn t be
diff --git a/mono/arch/mips/mips-codegen.h b/mono/arch/mips/mips-codegen.h
index dc4df7d..1dbd1c6 100644
--- a/mono/arch/mips/mips-codegen.h
+++ b/mono/arch/mips/mips-codegen.h
@@ -334,7 +334,7 @@ enum
/* misc and coprocessor ops */
#define mips_move(c,dest,src) mips_addu(c,dest,src,mips_zero)
#define mips_dmove(c,dest,src) mips_daddu(c,dest,src,mips_zero)
-#define mips_nop(c) mips_sll(c,0,0,0)
+#define mips_nop(c) mips_or(c,mips_at,mips_at,0)
#define mips_break(c,code) mips_emit32(c, ((code)<<6) 13)
#define mips_mfhi(c,dest) mips_format_r(c,0,0,0,dest,0,16)
#define mips_mflo(c,dest) mips_format_r(c,0,0,0,dest,0,18)
Oh yes it could! Mono was using sll 0,0,0 (the recommended no-op instruction from the MIPS instruction reference manual), causing failures in my tests, because Debian s build and test infrastructure just happens to use defective silicon. And, again, upstream were unable to reproduce a problem because they use better silicon than we do.
So what now?
Well, last night I uploaded mono_3.2.3+dfsg-3, which includes the above patch to force the replacement no-op instruction. It test built fine on the porterbox, and it should (when the damn experimental buildd gets around to it), just work.
Finally.
After just under a decade, Mono packages will be available on MIPS in Debian.
And after all this time, all we had to change was 4 lines to work around 7 year old Chinese knock-off processors.
The edit
So, things are finally built.
It turns out that despite everything, the replacement NOP opcode is not enough.
If you re-read the post to the binutils list, pay close attention to:
In theory this is still not enough to fully eliminate possible hangs, but the possiblity is extremely low now and hard to be hit in real code.
It s a filthy lie. It s easy to hit the issue in real code: just do a from-source build of the whole Mono class library. With the replacement instruction it builds .NET 2.0, 3.0, 3.5, 4.0, and most of 4.5, before dying in the same way as before an improvement on failing early in the 2.0 build, but not enough.
Thankfully, 2 out of the 5 Debian mipsel build servers are not Loongson 2 they re 11 year old Broadcom SWARM developer boards. Not fast but also not broken. Luck smiled on me, and caused my build to go to one of these Broadcom machines. As a result
(experimental_mipsel-dchroot)directhex@eder:~$ mono --version head -1
Mono JIT compiler version 3.2.3 (Debian 3.2.3+dfsg-3)
It s been a long time coming.
After running a QNAP TS-459 Pro+ for the last 3 or 4 years at home, my monitoring was alerting me about memory warnings cause I upgraded my SqueezeBox Server to the latest nightly version. So I looked into how to upgrade the shipped Adata SU3S1333B1G9-B.
It seems that the KVR1333D3S8S9/2G should work, so I ordered one. After plugin it in, it revealed that the module wasn't working while it worked for others. After digging around, it seems essentially that the modul has a 8-chip design. Indeed, my modul just has only 8 memory chips, but the design is a 16 chip. So I thought it would be a nice try to order the one from amazon that worked for others.
And like expected it's not the same module but has the same Kingston Part Number.
As you can see, the 16 chip design module has printed '9905428-189.A00lf' on and the 8 chip design '9931712-009.A00G'. It's something like in the Wireless LAN USB dongle business where they sell totally different hardware with the same Part Number but different Revisions.
I also ordered a Samsung M471B5773DH0-CH9 cause that's also a 8 chip design.
To make it short, both 8 chips design modules worked like a charm, the M471B5773DH0-CH9 and the KVR1333D3S8S9/2G (9931712-009.A00G). - Please avoid the Adolf one from Kingston! ;)
Last week was the
OpenStack Design Summit Icehouse
in Hong-Kong where we, OpenStack developers, discussed and designed the new
OpenStack release (Icehouse) that is coming up.
The week has been wonderful. It was my second OpenStack design summit, and I
loved it. Bumping into various people I've never met so far and worked with
online was a real pleasure. As it was to meet again with fellow OpenStack
developers! The event organisation was great, as were the parties. :-)
On the last day, I had the chance to present a talk with Eoghan Glynn and
Nick Barcet how we built the auto-scaling feature in Heat, implementing the
"alarming" feature needed in Ceilometer.
In Haskell, lists are ubiquitous. In real-world Haskell, monads are ubiquitous. So it should be an easy task to fill a list with values obtained in a monad, i.e. a list of n random numbers (in the Rand monad), or getting some input from the user, and storing it in a list, until the user chooses to finish the input.
The task
For now, assume a function getInput :: IO Int; we want to run it 10000 and then have the list of the values returned. Sounds simple and straight forward, but it is actually really hard to get the run-time behaviour that we naively and optimistically expect.
The expectation
In an imperative setting, we would have a simple counting loop. In the loop, we run getInput, allocate a new cell for the linked list, and append it to the list. Clearly, this
accumAppend :: Int -> IO [Int]
accumAppend n = go n []
where
go 0 l = return l
go n l = do x <- getInput; go (n-1) (l++[x])
To check the space usage of this, I pass -Kn to the GHC runtime and see what limit is just enough to let this program calculate accumAppend 10000 and fully evaluate the resulting list. It turns out that we need 328336 bytes of stack space.
So what about the second requirement; that the list is fully evaluated? Experienced Haskellers see it immediatelly: The accumulator is not used in the loop, so each iteration adds a thunk around the previous value, that would add the next entry to the end. Only when the list is actually used, these are run, each traversing the whole list, causing quadratic cost. We can verify this using ghc-vis:
accumAppendSeq :: Int -> IO [Int]
accumAppendSeq n = go n []
where
go 0 l = return l
go n l = do x <- getInput ; go (n-1) $!! (l++[x])
As the accumulator gets fully evaluated before being passed to the next invocation of go, the result will not contain thunks. But note that this has also fixed the stack consumption: The code now runs the smallest setting for -K, 8 bytes. This works as both go and deepseq are tail-recursive.
But this is still not the solution we are looking for, as the quadradic cost caused by using ++ is still there.
Attempt 3: The accumulator (reversed)
Since we know that l++[x] is expensive, but x:l is cheap, we can simply use this to update the accumulator. This has the slightly annoying consequence that the entries of the list are in the reverse order, but we can fix that in the base case:
accumReverse :: Int -> IO [Int]
accumReverse n = go n []
where
go 0 l = return (reverse l)
go n l = do x <- getInput ; go (n-1) (x:l)
And indeed, we get noticably faster code that still runs in 8 bytes of stack. Unfortunately, we still don t construct the final list directly.
Attempt 4: Naive recursion
Maybe we can do without an accumulator. The most naive such code would be
listRecurse :: Int -> IO [Int]
listRecurse n = go n
where
go 0 = return []
go n = do x <- getInput; r <- go (n-1); return (x:r)
and I d expect that most experienced Haskellers would write that code (if they are asked not to use a library function). And indeed, this code does create the final list directly. But it requires a large stack or 164616 bytes. The reason is that this is no longer tail recursive: After calling go again we need to take the result and prepend x
Attempt 5: library functions
Maybe we should simply not worry about the implementation, and use library functions? Clearly, the authors of such libraries have found the best solution. So how does
listReplicateM :: Int -> IO [Int] listReplicateM n = Control.Monad.replicateM n getInputfare? Unfortunately, not better than the naive recursion. In fact, the stack space requirement is the same 164616 bytes. The same holds when using special libraries for generating and consuming list, e.g. the Streams module from the vector package:
listStreams :: Int -> IO [Int] listStreams n = MStream.toList $ MStream.replicateM n getInputAttempt 6: Difference lists It is time to dig deeper into our box of tricks. What if we have lists with constant time Snoc (a.k.a. appending a new element)? Then Attempt 3 would not require reversing the list. Such lists are provided by difference lists; there are libraries for that, but we can simply implement them using lambdas:
accumDList :: Int -> IO [Int]
accumDList n = go n id
where
go 0 l = return (l [])
go n l = do x <- getInput; go (n-1) (l . (x:))
Indeed, no stack is required (8 bytes are enough). But we are cheating here: We are still not constructing the final list, but rather we combine functions that append elements to lists. So when accumDList returns, what we have in memory, is a thunk and sequence of partial function applications in the wrong order, and evaluating the thunk does basically the same thing as reverse in Attempt 3. It might be a bit faster, is still not satisfying enough:
listUnsafeInterleave :: Int -> IO [Int]
listUnsafeInterleave n = do l <- go n; return $!! l
where
go 0 = return []
go n = do x <- getInput
r <- unsafeInterleaveIO (go (n-1))
return (x:r)
The stack consumption is 8 bytes. It is worth noting that the all to deepseq (in $!!) will actually drive the evaluation of go. Also, it guarantees that the unsafe effects of unsafeInterleaveIO are confined to the execution of listUnsafeInterleave, i.e. are actually safe.
Run time statistics
I ran criterion over the functions (generating lists of length 1000), and found these results:

While quite old fashioned, SNMP is still an ubiquitous protocol
supported by most network equipments. It comes handy to expose
various metrics, like network interface counters, to be gathered
for the purpose of monitoring. It can also be used to retrieve and
modify equipments configuration.
Variables exposed by SNMP agents (servers) are organized inside a
Management Information Base (MIB) which is a hierarchical
database1. Each entry is identified by an OID. Querying a
specific OID allows a manager (client) to get the value of an
associated variable.
For example, one common MIB-module is IF-MIB defined in RFC 2863. It
contains objects used to manage network interfaces. One of them is
ifTable whose rows are representing agent s logical network
interfaces. Each row will expose the interface name, characteristics
and various associated counters.
| ifIndex | ifDescr | ifPhysAddress | ifOperStatus | ifOutOctets |
|---|---|---|---|---|
| 1 | lo | up | 545721741 | |
| 2 | eth0 | 0:18:f3:3:4e:4 | up | 78875421 |
| 3 | eth1 | 0:18:f3:3:4e:5 | down | 0 |
ifTable is indexed by its first column ifIndex. If you want to get
the operational status of the second interface, you need to query
IF-MIB::ifOperStatus.2 which is translated to OID
.1.3.6.1.2.1.2.2.1.8.2 using information provided by the MIB definition.
snmpget
and snmpwalk:
$ snmpwalk -v 2c -c public localhost IF-MIB::ifDescr IF-MIB::ifDescr.1 = STRING: lo IF-MIB::ifDescr.2 = STRING: eth0 IF-MIB::ifDescr.3 = STRING: eth1
#!/bin/sh set -e host="$ 1:-localhost " community="$ 2:-public " args="-v2c -c $community $host" for idx in $(snmpwalk -Ov -OQ $args IF-MIB::ifIndex); do descr=$(snmpget -Ov -OQ $args IF-MIB::ifDescr.$idx) oper=$(snmpget -Ov -OQ $args IF-MIB::ifOperStatus.$idx) in=$(snmpget -Ov -OQ $args IF-MIB::ifInOctets.$idx) out=$(snmpget -Ov -OQ $args IF-MIB::ifOutOctets.$idx) [ x"$descr" != x"lo" ] continue [ x"$oper" = x"up" ] continue echo $descr $in $out done
import argparse import netsnmp parser = argparse.ArgumentParser() parser.add_argument("host", default="localhost", nargs="?", help="Agent to retrieve variables from") parser.add_argument("community", default="public", nargs="?", help="Community to query the agent") options = parser.parse_args() args = "Version": 2, "DestHost": options.host, "Community": options.community for idx in netsnmp.snmpwalk(netsnmp.Varbind("IF-MIB::ifIndex"), **args): descr, oper, cin, cout = netsnmp.snmpget( netsnmp.Varbind("IF-MIB::ifDescr", idx), netsnmp.Varbind("IF-MIB::ifOperStatus", idx), netsnmp.Varbind("IF-MIB::ifInOctets", idx), netsnmp.Varbind("IF-MIB::ifOutOctets", idx), **args) assert(descr is not None and cin is not None and cout is not None) # if descr == "lo": continue if oper != "1": # continue print(" ".format(descr, cin, cout))
snmp_build: unknown failure on the
standard error. No exception. If a variable does not exist,
you ll get None instead. See .None, your script may cause havoc!
#!/usr/bin/env snimpy import argparse parser = argparse.ArgumentParser() parser.add_argument("host", default="localhost", nargs="?", help="Agent to retrieve variables from") parser.add_argument("community", default="public", nargs="?", help="Community to query the agent") options = parser.parse_args() m = M(options.host, options.community, 2) load("IF-MIB") for idx in m.ifDescr: if m.ifDescr[idx] == "lo": continue if m.ifOperStatus[idx] != "up": continue print(" ".format(m.ifDescr[idx], m.ifInOctets[idx], m.ifOutOctets[idx]))
load("IF-MIB") print("\n".join([ " ".format(m.ifDescr[idx], m.ifInOctets[idx], m.ifOutOctets[idx]) for idx in m.ifDescr if m.ifDescr[idx] != "lo" and m.ifOperStatus[idx] == "up" ]))
load("IP-FORWARD-MIB") m=M("localhost", "public", 2) routes = m.ipCidrRouteNextHop for x in routes: net, netmask, tos, src = x print(" :>15s / :<15s via :<15s src :<15s ".format( net, netmask, routes[x], src))
IP-FORWARD-MIB::ipCidrRouteNextHop is a more complex table with a
compound index. Despite this, querying the table still seems natural.
Have a look at Snimpy s documentation for more information. Behind
the hood, SNMP requests are handled by PySNMP and MIB parsing is
done with libsmi2. Snimpy supports both Python 2, Python
3 and Pypy.
smidump which comes with libsmi. Snimpy uses a
custom CFFI wrapper around libsmi.
In high school, I had a science teacher who would mark your answers wrong if
you forgot to include units. What does that mean? , he would write, 17.2
elephants? The point he was trying to get across was that a bare number,
without the relevant units, wasn t precise enough to be useful. Also,
carrying the units with you helped to cross-check your work if you got
a numeric answer, but the units were garbage (seconds per kilogram, for
instance, when you were trying to find an acceleration), then you could be
pretty sure you d made a mistake somewhere.
Fast forward to today, and I m currently working with a database containing
a pile of timestamps. Without timezones. Where the timestamps being
inserted are in local time. Thankfully, so far, this particular system has
always been run in one timezone, so I ve only got one timezone to deal with,
but the potential ramifications of systems with different timezones
inserting data into this database terrify me.
The naive answer is to just store everything in UTC and be done with it.
I m not particularly averse to that solution, as long as it s very clear to
everyone what s going on. The correct answer, though, I think, is to
always keep timezone information with your timestamps otherwise, you ll
never know whether it s 0830 in elephants
I'm very happy: I was finally able to present a talk at a Free Software conference in Paran , Argentina Regina's hometown. Not only in Paran , but at the Vieja Usina culture center, half a block away from her parents' house. So, I must doubly thank Laura: First, for letting us know there would be a Free Software conference there, and second, for taking some pictures :-
config interface 'loopback'
option ifname 'lo'
option proto 'static'
option ipaddr '127.0.0.1'
option netmask '255.0.0.0'
config globals 'globals'
option ula_prefix 'fdbf:4c12:3fed::/48'
config interface 'lan'
option ifname 'eth0'
option type 'bridge'
option proto 'dhcp'
option ipaddr '192.168.1.1'
option netmask '255.255.255.0'
option hostname 'tl-mr3040'
option ip6assign '60'
config interface 'mesh'
option ifname 'adhoc0'
option mtu '1528'
option proto 'batadv'
option mesh 'bat0'
/etc/config/wireless
config wifi-device 'radio0'
option type 'mac80211'
option channel '11'
option hwmode '11ng'
option path 'platform/ar933x_wmac'
option htmode 'HT20'
list ht_capab 'SHORT-GI-20'
list ht_capab 'SHORT-GI-40'
list ht_capab 'RX-STBC1'
list ht_capab 'DSSS_CCK-40'
option disabled '0'
config wifi-iface 'wmesh'
option device 'radio0'
option ifname 'adhoc0'
option network 'mesh'
option encryption 'none'
option mode 'adhoc'
option bssid '02:BA:00:00:00:01'
option ssid 'meshfx@hackeriet'
/etc/config/batman-adv
config 'mesh' 'bat0'
option interfaces 'adhoc0'
option 'aggregated_ogms'
option 'ap_isolation'
option 'bonding'
option 'fragmentation'
option 'gw_bandwidth'
option 'gw_mode'
option 'gw_sel_class'
option 'log_level'
option 'orig_interval'
option 'vis_mode'
option 'bridge_loop_avoidance'
option 'distributed_arp_table'
option 'network_coding'
option 'hop_penalty'
# yet another batX instance
# config 'mesh' 'bat5'
# option 'interfaces' 'second_mesh'
The mesh node is now operational. I have yet to test its range,
but I hope it is good. I have not yet tested the TP-Link 3600 box
still wrapped up in plastic.
Next.