Documentation ΒΆ
Overview ΒΆ
Package lxkns discovers Linux kernel namespaces of types cgroup, ipc, mount, net, pid, time, user, and uts. This package discovers namespaces not only when processes have joined them, but also when namespaces have been bind-mounted or are only referenced anymore by process file descriptors or within a hierarchy (PID and user only).
In case of PID and user namespaces, lxkns additionally discovers their hierarchies, except when running on a really ancient kernel before 4.9. Furthermore, for user namespaces the owning user ID and the owned namespaces will be discovered too. Time namespaces require a kernel 5.6 or later.
And finally, lxkns relates namespaces to the "leading" (or "root") processes joined to them; this relationship is basically derived for convenience from the process tree hierarchy. The kernel itself doesn't define any special relationship between namespaces and processes except for the "attachment" of processes joining namespaces.
The namespace discovery process can be controlled in several aspects, according to the range of discovery of namespace types and places to search namespaces for, according to the needs of API users of the lxkns package.
Discovery ΒΆ
A namespace discovery is just a single call to function lxkns.Discover(). Additionally, there's a one-time support function call to reexec.CheckAction() required as early as possible in main().
import ( "github.com/thediveo/gons/reexec" "github.com/thediveo/lxkns" ) func main() { reexec.CheckAction() ... allns := lxkns.Discover(lxkns.FullDiscovery) ... }
Technical note: in order to discover namespaces in some locations, such as bind-mounted namespaces, lxkns needs to fork the process it used from in, in order to switch the forked copy into other mount namespaces for further discovery. In order to implement this mechanism as painless as possible, process using lxkns need to call reexec.CheckAction() as early as possible from their main().
Basics of the lxkns Information Model ΒΆ
Not totally unexpectedly, the lxkns discovery information model at its most basic level comprises ... namespaces. In the previous code snippet, the information model returned is stored in the "allns" variable for further processing. The result organizes the namespaces found by type. For instance, the following code snippet prints all namespaces, sorted first by type and then by namespace identifier:
// Iterate over all 7 types of Linux-kernel namespaces, then over all // namespaces of a given type... for nsidx := range allns.Namespaces { for _, ns := range allns.SortedNamespaces(lxkns.NamespaceTypeIndex(nsidx)) { println(ns.Type().Name(), ns.ID().Ino) } }
Because namespaces have no order defined, the discovery results "list" the namespaces in per-type maps, indexed by namespace identifiers. For convenience, SortedNamespaces() returns the namespaces of a specific type in a slice instead of a map, sorted numerically by the namespace identifiers (that is, sorting by inode numbers, ignoring dev IDs at this time).
Technically, these namespace identifiers are tuples consisting of 64bit unsigned inode numbers and (~64bit) device ID numbers, and come from the special "nsfs" namespace filesystem integrated with the Linux kernel. And before someone tries: nope, the nsfs cannot be mounted; and it even does not appear in the kernel's list of namespaces.
Unprivileged Discovery and How To Not Panic ΒΆ
While it is possible to discover namespaces without root privileges, this won't return the full set of namespaces in a Linux host. The reason is that while an unprivileged discovery is allowed to see some basic information about all processes in the system, it is not allowed to query the namespaces such privileged processes are joined too. In addition, an unprivileged discovery may turn up namespaces (for instance, when bind-mounted) for which the identifier is discovered, but further information, such as the parent or child namespaces for PID and user namespaces, is undiscoverable.
Users of the lxkns information model thus must be prepared to handle incomplete information yielded by unprivileged lxkns.Discover() calls. In particular, applications must be prepared to handle:
- more than a single "initial" namespace per type of namespace,
- PID and user namespaces without a parent namespace,
- namespaces without owning user namespaces,
- processes not related to any namespace.
In consequence, always check interface values and pointers for nil values like a pro. You can find many examples in the sources for the "lsuns", "lspidns", and "pidtree" CLI tools (inside the cmd sub-package).
In-Capabilities ΒΆ
It is possible to run full discoveries without being root, when given the discovery process the following effective capabilities:
- CAP_SYS_PTRACE -- no joking here, that's what needed for reading namespace references from /proc/[PID]/ns/*
- CAP_SYS_CHROOT -- for mount namespace switching
- CAP_SYS_ADMIN -- for mount namespace switching
- CAP_DAC_READ_SEARCH -- for reading details of bind-mounted namespaces
Considering that especially CAP_SYS_PTRACE being essential there's probably not much difference to "just be root" in the end, unless you want show off your "capabilities capabilities".
Namespace Hierarchies ΒΆ
PID and user namespaces form separate and independent namespaces hierarchies. This parent-child hierarchy is exposed through the lxkns.Hierarchy interface of the discovered namespaces.
Please note that lxkns represents namespaces often using the lxkns.Namespace interface when the specific type of namespace doesn't matter. In case of PID and user-type namespaces an lxkns.Namespace can be "converted" into an interface value of type lxkns.Hierarchy using a type assertion, in order to access the particular namespace hierarchy.
// If it's a PID or user namespace, then we can turn a "Namespace" // into an "Hierarchy" in order to access hierarchy information. if hns, ok := ns.(lxkns.Hierarchy); ok { if hns.Parent() != nil { ... } for _, childns := range hns.Children() { ... } }
Ownership ΒΆ
User namespaces play the central role in controlling the access of processes to other namespaces as well as the capabilities process gain when allowed to join user namespaces. A comprehensive discussion of the rules and their ramifications is beyond this package documentation. For starters, please refer to the man page for user_namespaces(7), http://man7.org/linux/man-pages/man7/user_namespaces.7.html.
The controlling role of user namespaces show up in the discovery information model as owner-owneds relationships: user namespaces own non-user namespaces. And non-user namespaces are owned by user namespaces, the "ownings". In case you are now scratching your head "why the Gopher" the owned namespaces are referred to as "ownings": welcome to the wonderful Gopher world of "er"-ers, where interface method naming conventions create wonderful identifier art.
If a namespace interface value represents a user-type namespace, then it can be "converted" into an lxkns.Ownership interface value using a type assertion. This interface discloses which namespaces are owned by a particular user namespace. Please note that this does not include child user namespaces, use Hierarchy.Children() instead.
// Get the user namespace -owned-> namespaces relationships. if owns, ok := ns.(lxkns.Ownership); ok { for _, ownedns := range owns.Ownings() { ... } }
In the opposite direction, the owner of a namespace can be directly queried via the lxkns.Namespace interface (again, only for non-user namespaces):
// Get the namespace -owned by-> user namespace relationship. ownerns := ns.Owner()
When asking a user namespace for its owner, the parent user namespace is returned in accordance with the Linux ioctl()s for discovering the ownership of namespaces.
Namespaces and Processes ΒΆ
The lxkns discovery information model also relates processes to namespaces, and vice versa. After all, processes are probably the main source for discovering namespaces.
For this reason, the discovery results (in "allns" in case of the above discovery code example) not only list the namespaces found, but also a snapshot of the process tree at discovery time (please relax now, as this is a snapshot of the "tree", not of all the processes themselves).
// Get the init(1) process representation. initprocess := allns.Processes[lxkns.PIDType(1)] for _, childprocess := range initprocess.Children() { ... }
Please note that the process tree information is for convenience; it's not a replacement for the famous gopsutil package in many use cases. However, the process tree information show which namespaces are used by (or "joined by") which particular processes.
// Show all namespaces joined by a specific process, such as init(1). for nsidx := lxkns.MountNS; nsidx < lxkns.NamespaceTypesCount; nsidx++ { println(initprocess.Namespaces[nsidx].String()) }
It's also possible, given a specific namespace, to find the processes joined to this namespace. However, the lxkns information model optimizes this relationship information on the assumption that in many situations not the list of all processes joined to a namespace is needed, but actually only the so-called "leader" process or processes.
A leader process of namespace X is the process topmost in the process tree hierarchy of processes joined to namespace X. It is perfectly valid for a namespace to have more than one leader process joined to it. An example is a container with its own processes joined to the container namespaces, and an additional "visiting" process also joined to one or several namespaces of this container. The lxkns information then is able to correctly handle and represent such system states.
// Show the leader processes joined to the initial user namespace. for _, leaders := range initprocess.Namespaces[lxkns.UserNS].Leaders() { ... }
Architecture ΒΆ
Please find more details about the lxkns information model in the architectural documents: https://github.com/TheDiveO/lxkns/blob/master/docs/architecture.md.
Index ΒΆ
- Constants
- Variables
- func NSpid(proc *model.Process) (pids []model.PIDType)
- func ReexecIntoAction(actionname string, namespaces []model.Namespace, result interface{}) (err error)
- func ReexecIntoActionEnv(actionname string, namespaces []model.Namespace, envvars []string, ...) (err error)
- func SortChildNamespaces(nslist []model.Hierarchy) []model.Hierarchy
- func SortNamespaces(nslist []model.Namespace) []model.Namespace
- func SortedNamespaces(nsmap model.NamespaceMap) []model.Namespace
- type BindmountedNamespaceInfo
- type DiscoverOpts
- type DiscoveryResult
- type NamespacedPID
- type NamespacedPIDs
- type PIDMap
Constants ΒΆ
const SemVersion = "0.15.5"
SemVersion is the semantic version string of the lxkns module.
Variables ΒΆ
var FullDiscovery = DiscoverOpts{}
FullDiscovery sets the discovery options to a full and thus extensive discovery process. This is the preferred option setup for most use cases, unless you know exactly what you're doing and want to fine-tune the discovery process by selectively switching off certain discovery elements.
var NoDiscovery = DiscoverOpts{ SkipProcs: true, SkipTasks: true, SkipFds: true, SkipBindmounts: true, SkipHierarchy: true, SkipOwnership: true, }
NoDiscovery set the discovery options to not discover anything. This option set can be used to start from when only a few chosen discovery methods are to be enabled.
Functions ΒΆ
func NSpid ΒΆ added in v0.9.0
NSpid returns the list of namespaced PIDs for the process proc, based on information from the /proc filesystem (the "NSpid:" field in particular). NSpid only returns the list of PIDs, but not the corresponding PID namespaces; this is because the Linux kernel doesn't give us the namespace information as part of the process status. Instead, a caller (such as NewPIDMap) needs to combine a namespaced PIDs list with the hierarchy of PID namespaces to calculate the correct namespacing.
func ReexecIntoAction ΒΆ added in v0.9.0
func ReexecIntoAction(actionname string, namespaces []model.Namespace, result interface{}) (err error)
ReexecIntoAction forks and then re-executes this process in order to run a specific action (indicated by actionname) in a set of (different) Linux kernel namespaces. The stdout result of running the action is then deserialized as JSON into the specified result element.
func ReexecIntoActionEnv ΒΆ added in v0.9.0
func ReexecIntoActionEnv(actionname string, namespaces []model.Namespace, envvars []string, result interface{}) (err error)
ReexecIntoActionEnv forks and then re-executes this process in order to run a specific action (indicated by actionname) in a set of (different) Linux kernel namespaces. It also passes the additional environment variables specified in envvars. The stdout result of running the action is then deserialized as JSON into the specified result element.
func SortChildNamespaces ΒΆ added in v0.9.0
SortChildNamespaces returns a sorted copy of a list of hierarchical namespaces. The namespaces are sorted by their namespace ids in ascending order. Please note that the list itself is flat, but this function can only be used on hierarchical namespaces (PID, user).
func SortNamespaces ΒΆ added in v0.9.0
SortNamespaces returns a sorted copy of a list of namespaces. The namespaces are sorted by their namespace ids in ascending order.
func SortedNamespaces ΒΆ added in v0.9.0
func SortedNamespaces(nsmap model.NamespaceMap) []model.Namespace
SortedNamespaces returns the namespaces from a map sorted.
Types ΒΆ
type BindmountedNamespaceInfo ΒΆ added in v0.11.0
type BindmountedNamespaceInfo struct { ID species.NamespaceID `json:"id"` Type species.NamespaceType `json:"type"` Path string `json:"path"` OwnernsID species.NamespaceID `json:"ownernsid"` Log []string `json:"log"` // not strictly necessary, yet very helpful. }
BindmountedNamespaceInfo describes a bind-mounted namespace in some (other) mount namespace, including the owning user namespace ID, so we can later correctly set up the ownership relations in the discovery results.
type DiscoverOpts ΒΆ added in v0.9.0
type DiscoverOpts struct { // The types of namespaces to discover: this is an OR'ed combination of // Linux kernel namespace constants, such as CLONE_NEWNS, CLONE_NEWNET, et // cetera. If zero, defaults to discovering all namespaces. NamespaceTypes species.NamespaceType `json:"-"` // Where to scan (or not scan) for signs of namespaces? SkipProcs bool `json:"skipped-procs"` // Don't scan processes. SkipTasks bool `json:"skipped-tasks"` // Don't scan threads, a.k.a. tasks. SkipFds bool `json:"skipped-fds"` // Don't scan process file descriptors for references to namespaces. SkipBindmounts bool `json:"skipped-bindmounts"` // Don't scan for bind-mounted namespaces. SkipHierarchy bool `json:"skipped-hierarchy"` // Don't discover the hierarchy of PID and user namespaces. SkipOwnership bool `json:"skipped-ownership"` // Don't discover the ownership of non-user namespaces. }
DiscoverOpts gives control over the extend and thus time and resources spent on discovering Linux kernel namespaces, their relationships between them, and with processes.
type DiscoveryResult ΒΆ added in v0.9.0
type DiscoveryResult struct { Options DiscoverOpts // options used during discovery. Namespaces model.AllNamespaces // all discovered namespaces, subject to filtering according to Options. InitialNamespaces model.NamespacesSet // the 7 initial namespaces. UserNSRoots []model.Namespace // the topmost user namespace(s) in the hierarchy PIDNSRoots []model.Namespace // the topmost PID namespace(s) in the hierarchy Processes model.ProcessTable // processes checked for namespaces. }
DiscoveryResult stores the results of a tour through Linux processes and kernel namespaces.
func Discover ΒΆ added in v0.9.0
func Discover(opts DiscoverOpts) *DiscoveryResult
Discover returns the Linux kernel namespaces found, based on discovery options specified in the call. The discovery results also specify the initial namespaces, as well the process table/tree on which the discovery bases at least in part.
func (*DiscoveryResult) SortedNamespaces ΒΆ added in v0.9.0
func (dr *DiscoveryResult) SortedNamespaces(nsidx model.NamespaceTypeIndex) []model.Namespace
SortedNamespaces returns a sorted list of discovered namespaces of the specified type. The namespaces are sorted by their identifier, which is an inode number (on the special "nsfs" filesystem), ignoring a namespace's device ID.
type NamespacedPID ΒΆ added in v0.9.0
type NamespacedPID struct { PIDNS model.Namespace // PID namespace ID for PID. PID model.PIDType // PID within PID namespace (of ID). }
NamespacedPID is PID in the context of a specific PID namespace.
type NamespacedPIDs ΒΆ added in v0.9.0
type NamespacedPIDs []NamespacedPID
NamespacedPIDs is a list of PIDs for the same process, but in different PID namespaces. The order of the list is undefined.
func (NamespacedPIDs) PIDs ΒΆ added in v0.9.0
func (ns NamespacedPIDs) PIDs() []model.PIDType
PIDs just returns the different PIDs assigned to a single process in different PID namespaces, without the namespaces. This is a convenience function for those lazy cases where just the PID list is wanted, but no PID namespace details.
type PIDMap ΒΆ added in v0.9.0
type PIDMap map[NamespacedPID]NamespacedPIDs
PIDMap maps a single namespaced PID to the list of PIDs for this process in different PID namespaces. Further PIDMap methods then allow simple translation of PIDs between different PID namespaces.
func NewPIDMap ΒΆ added in v0.9.0
func NewPIDMap(result *DiscoveryResult) PIDMap
NewPIDMap returns a new PID map based on the specified discovery results and further information gathered from the /proc filesystem.
func (PIDMap) NamespacedPIDs ΒΆ added in v0.9.0
NamespacedPIDs returns for a specific namespaced PID the list of all PIDs the corresponding process has been given in different PID namespaces. Returns nil if the PID doesn't exist in the specified PID namespace. The list is ordered from the topmost PID namespace down to the leaf PID namespace to which a process actually is joined to.
func (PIDMap) Translate ΒΆ added in v0.9.0
func (pidmap PIDMap) Translate(pid model.PIDType, from model.Namespace, to model.Namespace) model.PIDType
Translate translates a PID "pid" in PID namespace "from" to the corresponding PID in PID namespace "to". Returns 0, if PID "pid" either does not exist in namespace "from", or PID namespace "to" isn't either a parent or child of PID namespace "from".
Source Files ΒΆ
Directories ΒΆ
Path | Synopsis |
---|---|
api
|
|
types
Package types defines the common types for (un)marshalling elements of the lxkns information model from/to JSON.
|
Package types defines the common types for (un)marshalling elements of the lxkns information model from/to JSON. |
cmd
|
|
dumpns
dumpns runs a namespace (and process) discovery and then dumps the results as JSON.
|
dumpns runs a namespace (and process) discovery and then dumps the results as JSON. |
internal/pkg/cli
Package cli handles registering CLI flags via a plug-in mechanism.
|
Package cli handles registering CLI flags via a plug-in mechanism. |
internal/pkg/filter
Package filter provides CLI-controlled filtering of namespaces by type.
|
Package filter provides CLI-controlled filtering of namespaces by type. |
internal/pkg/style
Package style styles text output of the CLI commands with foreground and background colors, as well as different text styles (bold, italics, ...).
|
Package style styles text output of the CLI commands with foreground and background colors, as well as different text styles (bold, italics, ...). |
internal/test/getstdout
Package getstdout captures os.Stdout and os.Stderr while executing a specified function, returning the captured output afterwards.
|
Package getstdout captures os.Stdout and os.Stderr while executing a specified function, returning the captured output afterwards. |
lspidns
lspidns lists the tree of PID namespaces, optionally with their owning user namespaces.
|
lspidns lists the tree of PID namespaces, optionally with their owning user namespaces. |
lsuns
lsuns lists the tree of user namespaces, optionally with the other namespaces they own.
|
lsuns lists the tree of user namespaces, optionally with the other namespaces they own. |
nscaps
nscaps determines a process' capabilities in some namespace.
|
nscaps determines a process' capabilities in some namespace. |
pidtree
pidtree displays a tree (or only a single branch) of processes together with their PID namespaces, and additionally also shows the local PIDs of processes (where applicable).
|
pidtree displays a tree (or only a single branch) of processes together with their PID namespaces, and additionally also shows the local PIDs of processes (where applicable). |
examples
|
|
internal
|
|
Package log allows consumers of the lxkns module to forward logging originating in the lxkns module to whatever logger module they prefer.
|
Package log allows consumers of the lxkns module to forward logging originating in the lxkns module to whatever logger module they prefer. |
logrus
Package logrus enables logging within the lxkns module and directs all logging output to the sirupsen/logrus logging module.
|
Package logrus enables logging within the lxkns module and directs all logging output to the sirupsen/logrus logging module. |
Package model defines the core of lxkns information model: Linux kernel namespaces and processes, and how they relate to each other.
|
Package model defines the core of lxkns information model: Linux kernel namespaces and processes, and how they relate to each other. |
Package nstest provides testing support in the context of Linux kernel namespaces.
|
Package nstest provides testing support in the context of Linux kernel namespaces. |
gmodel
Package gmodel provides Gomega matches for lxkns model elements.
|
Package gmodel provides Gomega matches for lxkns model elements. |
Package ops provides a Golang-idiomatic API to the query and switching operations on Linux-kernel namespaces, hiding ioctl()s and syscalls.
|
Package ops provides a Golang-idiomatic API to the query and switching operations on Linux-kernel namespaces, hiding ioctl()s and syscalls. |
internal/opener
Package opener provides access to the file descriptors of namespace references.
|
Package opener provides access to the file descriptors of namespace references. |
portable
Package portable provides so-called "portable" namespace references with validation and "locking" (keeping the referenced namespace open and thus alive).
|
Package portable provides so-called "portable" namespace references with validation and "locking" (keeping the referenced namespace open and thus alive). |
relations
Package relations gives access to properties of and relationships between Linux-kernel namespaces, such as type and ID of a namespace, its owning user namespace, parent namespace in case of hierarchical namespaces, et cetera.
|
Package relations gives access to properties of and relationships between Linux-kernel namespaces, such as type and ID of a namespace, its owning user namespace, parent namespace in case of hierarchical namespaces, et cetera. |
Package species defines the type constants and type names of the 8 Linux kernel namespace types ("species").
|
Package species defines the type constants and type names of the 8 Linux kernel namespace types ("species"). |