Rewrite cleanup with RAII.

Rewrite the goto shutdown hack by using the destructor of a local class
to make the code cleaner.