2

Is there any way to find how many active namespaces of each type are present in Linux? Such as:

  • mount ns: 20
  • net ns: 40
  • etc.
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250

2 Answers2

4

This will iterate over the links under /proc/*/ns to count the number of active namespaces of each type, i.e. namespaces containing at least one process:

sudo find /proc/*/ns -type l -printf "%l\n" |
gawk -F'[:\\[\\]]+' '{ nss[$1][$2] = 1 } END { for (ns in nss) { print ns ": " length(nss[ns]) } }'

It works by counting the number of distinct identifiers, grouped by namespace type.

Namespaces can be kept alive without processes by bind mounting them elsewhere; the above doesn’t take this into account.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • Since the docs say so, and I have container setups which rely on that, I know that namespaces can be maintained using bind mounts even if no process is tied to them (the namespaces, not the mounts). – Stephen Kitt Dec 10 '19 at 16:46
  • 1
    How would you rephrase “[Bind mounting (see mount(2)) one of the files in this directory to somewhere else in the filesystem keeps the corresponding namespace of the process specified by pid alive even if all processes currently in the namespace terminate.](http://man7.org/linux/man-pages/man7/namespaces.7.html)”? – Stephen Kitt Dec 10 '19 at 18:14
  • The bind-mounted namespaces are seen in /proc/mounts (as a nsfs filesystem). eg: `ip netns add test; grep nsfs /proc/mounts`. Then they can be accounted with their inode (eg: `stat -c %i /run/netns/test`) which is the identifier. – A.B Dec 10 '19 at 18:31
  • But I admit some might not be so easily accessible when mounted within other mount namespaces... – A.B Dec 10 '19 at 18:37
  • There are also fds keeping a namespace alive. If you're interested, in order to solve (only) the network namespace case, I wrote an answer trying to find all 3 categories: https://unix.stackexchange.com/questions/505112/how-do-i-find-all-interfaces-that-have-been-configured-in-linux-including-those/505978#505978 (example for this 3rd category is Firefox) – A.B Dec 10 '19 at 18:42
3

You can use the lsns(1) command from the util-linux package for that [1]:

lsns -n | awk '{n[$2]++}END{for(k in n) print k"\t"n[k]}'
net     2
cgroup  1
...

But lsns is broken: it won't show either the per-thread namespaces or those only kept alive by an open handle or a bind mount. To get all that, try the lsnsx.pl script from my other answer:

# perl ./lsnsx.pl | grep -v '^ '
cgroup   1
ipc      1
mnt      3
net      5
...

[1] If you're on a machine without lsns (eg. busybox), you can extract that info directly from /proc/*/ns/*:

for f in /proc/[0-9]*/ns/*; do readlink "$f"; done | awk -F: '!t[$2]++{c[$1]++}END{for(k in c)print k"\t"c[k]}'

You can change /proc/[0-9]*/ns to /proc/[0-9]*/task/[0-9]*/ns to also get the per-thread namespaces, but on any moderately-used machine it will get horribly slow.