Sep 182013
 

Indenting lines with leading tabs is an important technique for writing clear and readable code, and are essential in Python where they have syntactic meaning. Many IDEs insert tabs automatically, but if you’re using vi it can be tedious to insert tabs individually. Fortunately, there is an easy shortcut, and it’s a very handy command to remember.

In the vi session, enter command mode by pressing ESC. Then, set the size of the tabs with the following command:

  :set shiftwidth=2

To make this the default, put “set shiftwidth=2” in your ~/.exrc file.

Then, to tab shift the next 13 lines, you’d type a command like this:

13>>


Matt Parsons is a freelance Linux specialist who has designed, built and supported Unix and Linux systems in the finance, telecommunications and media industries.

He lives and works in London.

Sep 052013
 

While operating a MongoDB cluster, it can often be useful in maintenance scripts to check whether a host is the primary or secondary (master or slave). This is easy to do, and can be done without having to authenticate against the database. Scripts can be made simpler as there is no need to shield the login credentials, as there aren’t any.

When one connects a Mongo database process without credentials, using the “mongo” client command, the implicit “test” database is used. This is a default, and a kind of empty chroot database. Even though it’s an empty database, it still has read-only access to replica information. This can be very handy when automating deployment and monitoring scripts.

There are two commands in particular that are useful for determining the status of a replica set member. These are demonstrated in the following console example, which is fairly self-explanatory.

$ mongo localhost:27017
connecting to: localhost:27017/test
> db.isMaster().secondary
false
> db.isMaster().ismaster
true

This could also be executed non-interactively like this:

mongo localhost:27017 --quiet --eval 'db.isMaster().secondary'

Shell Script Snippet: wait for replica synchronization to finish

When resynchronizing a replica set slave, it will report its status as RECOVERING until it completes, at which point it becomes SECONDARY. The simple example below demonstrates a block of bash to test for this.

while [ "$RESULT" != "true" ]; do
   RESULT=$(mongo localhost --quiet --eval 'db.isMaster().secondary');
   sleep 5;
done

This is over-simplified to demonstrate the logic. In a real-world script you’d have an exit clause to prevent an endless loop in the case when the replica node never recovers.

Other useful commands can be discovered while browsing the mongo console. Find these using commands of the format:

  db.help()


Matt Parsons is a freelance Linux specialist who has designed, built and supported Unix and Linux systems in the finance, telecommunications and media industries.

He lives and works in London.