lxkns

package module
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 13, 2020 License: Apache-2.0 Imports: 15 Imported by: 0

README

Linux kernel Namespaces

GoDoc Architecture GitHub build and test Go Report Card

lxkns is a Golang package for discovering Linux kernel namespaces. In every nook and cranny of your Linux hosts.

In addition, lxkns comes with a set of unique CLI namespace discovery tools and also helps Go programs with switching namespaces.

And all that tested with Go 1.13 and 1.14. And even with support for the new time namespaces.

Comprehensive Namespace Discovery

When compared to most well-known and openly available CLI tools, such as lsns, the lxkns package detects namespaces even in places of a running Linux system other tools typically do not consider. In particular:

  1. from the procfs filesystem in /proc/[PID]/ns/* -- as lsns and other tools do.
  2. bind-mounted namespaces, via /proc/[PID]/mountinfo. Our discovery method even finds bind-mounted namespaces in other mount namespaces than the current one in which the discovery starts.
  3. file descriptor-referenced namespaces, via /proc/[PID]/fd/*.
  4. intermediate hierarchical user and PID namespaces, via NS_GET_PARENT (man 2 ioctl_ns).
  5. user namespaces owning non-user namespaces, via NS_GET_USERNS (man 2 ioctl_ns).
tool /proc/[PID]/ns/* bind mounts ② /proc/[PID]/fd/* hierarchy ④ owning user namespaces ⑤
lsns
lxkns

Applications can control the extent to which a lxkns discovery tries to ferret out namespaces from the nooks and crannies of Linux hosts.

Some discovery methods are more expensive than others, especially the discovery of bind-mounted namespaces in other mount namespaces. The reason lies in the design of the Go runtime which runs multiple threads and Linux not allowing multi-threaded processes to switch mount namespaces. In order to work around this constraint, lxkns must fork and immediately re-execute the process it is used in. Applications that want to use such advanced discovery methods thus must call reexec.CheckAction() as early as possible in their main() function. For this, you need to import "github.com/thediveo/gons/reexec".

gons CLI tools

But lxkns is more than "just" a Golang package. It also features CLI tools build on top of lxkns (we do eat our own dog food). To install these tools into your $GOPATH/bin directory, simply run go install ./....

These are the CLI tools:

  • lsuns GoDoc: shows all user namespaces in your Linux host, in a neat hierarchy. Moreover, it can also show the non-user namespaces "owned" by user namespaces. This ownership information is important with respect to capabilities and processes switching namespaces using setns() (man 2 setns).

  • lspidns GoDoc: shows all PID namespaces in your Linux host, in a neat hierarchy. Optionally, the owning user namespaces can be shown interleaved with the PID namespace hierarchy.

  • pidtree GoDoc: shows either the process hierarchy within the PID namespace hierarchy or a single branch only.

lsuns

In its simplest form, lsuns shows the hierarchy of user namespaces.

$ sudo lsuns
user:[4026531837] process "kthreadd" (2) created by UID 0 ("root")
└─ user:[4026532277] process "unshare" (15736) created by UID 0 ("root")

It gets more interesting with the -d (details) flag: lsuns then additionally displays all non-user namespaces owned by the user namespaces. In Linux-kernel namespace parlance, "owning" refers to the relationship between a newly created namespace and the user namespace that was active at the time the new namespace was created. For convenience, lsuns sorts the owned namespaces first alphabetically by type, and second numerically by namespace IDs.

$ sudo lsuns -d
user:[4026531837] process "kthreadd" (2) created by UID 0 ("root")
│  ⋄─ cgroup:[4026531835] process "systemd" (1)
│  ⋄─ ipc:[4026531839] process "kthreadd" (2)
│  ⋄─ mnt:[4026531840] process "systemd" (1)
│  ⋄─ mnt:[4026531860] process "kdevtmpfs" (29)
│  ⋄─ mnt:[4026532156] process "systemd-udevd" (161)
│  ⋄─ mnt:[4026532256] process "systemd-timesyn" (298)
│  ⋄─ mnt:[4026532271] process "bluetoothd" (472)
│  ⋄─ mnt:[4026532273] process "unshare" (11697)
│  ⋄─ mnt:[4026532275] process "unshare" (11818)
│  ⋄─ net:[4026531905] process "kthreadd" (2)
│  ⋄─ pid:[4026531836] process "kthreadd" (2)
│  ⋄─ pid:[4026532274] process "bash" (11698)
│  ⋄─ pid:[4026532276] process "bash" (11819)
│  ⋄─ uts:[4026531838] process "systemd" (1)
└─ user:[4026532277] process "unshare" (15736) created by UID 0 ("root")
      ⋄─ mnt:[4026532278] process "unshare" (15736)
      ⋄─ mnt:[4026532280] process "unshare" (15747)
      ⋄─ pid:[4026532279] process "bash" (15737)
      ⋄─ pid:[4026532281] process "bash" (15748)
lspidns

On its surface, lspidns might appear to be lsuns twin, but for PID namespaces.

pid:[4026531836] process "kthreadd" (2)
└─ pid:[4026532274] process "bash" (11698)
   └─ pid:[4026532276] process "bash" (11819)
      └─ pid:[4026532279] process "bash" (15737)
         └─ pid:[4026532281] process "bash" (15748)

But hidden beneath the surface lies the -u flag; "u" as in user namespace. Now what have user namespaces to do with PID namespaces? Like other non-user namespaces, also PID namespaces are owned by user namespaces. -u now tells lspidns to show a "synthesized" hierarchy where owning user namespaces and owned PID namespaces are laid out in a single tree.

user:[4026531837] process "kthreadd" (2) created by UID 0 ("root")
└─ pid:[4026531836] process "kthreadd" (2)
   └─ pid:[4026532274] process "bash" (11698)
      └─ pid:[4026532276] process "bash" (11819)
         └─ user:[4026532277] process "unshare" (15736) created by UID 0 ("root")
            └─ pid:[4026532279] process "bash" (15737)
               └─ pid:[4026532281] process "bash" (15748)

Please note that this representation is only possible because the capabilities rules for user and PID namespaces forbid user namespaces criss-crossing PID namespaces and vice versa.

pidtree

pidtree shows either the process hierarchy within the PID namespace hierarchy or a single branch only. It additionally shows translated PIDs, which are valid only inside the PID namespace processes are joined to. Such as in "containerd" (24446=78), where the PID namespace-local PID is 78, but inside the initial (root) PID namespace the PID is 24446 instead.

$ sudo pidtree
pid:[4026531836], owned by UID 0 ("root")
├─ "systemd" (1974)
│  ├─ "dbus-daemon" (2030)
│  ├─ "kglobalaccel5" (2128)
...
│  ├─ "containerd" (1480)
│  │  ├─ "containerd-shim" (21411)
│  │  │  └─ "foobar" (21434)
│  │  ├─ "containerd-shim" (24173)
│  │  │  └─ pid:[4026533005], owned by UID 0 ("root")
│  │  │     └─ "systemd" (24191/1)
│  │  │        ├─ "systemd-journal" (24366/70)
│  │  │        ├─ "containerd" (24446/78)

Alternatively, it can show just a single branch down to a PID inside a specific PID namespace.

$ sudo pidtree -n pid:[4026532512] -p 3
pid:[4026531836], owned by UID 0 ("root")
└─ "systemd" (1)
    └─ "kdeinit5" (2098)
      └─ "code" (20384)
          └─ pid:[4026532512], owned by UID 1000 ("harald")
            └─ "code" (20387/1)
                └─ "code" (20389/3)

Please see also the pidtree command documentation.

Package Usage

The following example code runs a full namespace discovery using Discover(FullDiscovery) and then prints all namespaces found, sorted by their type, then by their ID.

package main

import (
    "fmt"
    "github.com/thediveo/gons/reexec"
    "github.com/thediveo/lxkns"
)

func main() {
    reexec.CheckAction() // must be called before a full discovery
    result := lxkns.Discover(lxkns.FullDiscovery)
    for nsidx := lxkns.MountNS; nsidx < lxkns.NamespaceTypesCount; nsidx++ {
        for _, ns := range result.SortedNamespaces(nsidx) {
            fmt.Println(ns.String())
        }
    }
}

lxkns is Copyright 2020 Harald Albrecht, and licensed under the Apache License, Version 2.0.

Documentation

Overview

Package lxkns discovers Linux kernel namespaces (of types cgroup, ipc, mount, net, pid, 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.

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.

And finally, lxkns relates namespaces to the "leading" (or "root") processes joined to them; this relationship is basically derived from on the process tree hierarchy.

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().

Information Model, Base Level

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 executing the discovery process with 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

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

View Source
const SemVersion = "0.12.0"

SemVersion is the semantic version string of the lxkns module.

Variables

View Source
var FullDiscovery = DiscoverOpts{}

FullDiscovery sets the discovery options to a full and thus extensive discovery process.

View Source
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.

TypeIndexLexicalOrder contains Namespace type indices in lexical order.

TypesByIndex maps Allnamespaces array indices to their corresponding Linux' kernel namespace clone() syscall constants.

Functions

func ReexecIntoAction added in v0.9.0

func ReexecIntoAction(actionname string, namespaces []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 []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.

Types

type AllNamespaces added in v0.9.0

type AllNamespaces [NamespaceTypesCount]NamespaceMap

AllNamespaces contains separate NamespaceMaps for all types of Linux kernel namespaces. This type allows package functions to work on multiple namespace types simultaneously in order to optimize traversal of the /proc filesystem, bind-mounts, et cetera. AllNamespaces thus stores "all" namespaces that could be discovered in the system, subject to discovery filtering.

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"`
}

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

	// Where to scan (or not scan) for signs of namespaces?
	SkipProcs      bool // Don't scan processes.
	SkipTasks      bool // Don't scan threads, a.k.a. tasks.
	SkipFds        bool // Don't scan process file descriptors for references to namespaces.
	SkipBindmounts bool // Don't scan for bind-mounted namespaces.
	SkipHierarchy  bool // Don't discover the hierarchy of PID and user namespaces.
	SkipOwnership  bool // 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        AllNamespaces // all discovered namespaces, subject to filtering according to Options.
	InitialNamespaces NamespacesSet // the 7 initial namespaces.
	UserNSRoots       []Namespace   // the topmost user namespace(s) in the hierarchy
	PIDNSRoots        []Namespace   // the topmost PID namespace(s) in the hierarchy
	Processes         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 NamespaceTypeIndex) []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 Hierarchy added in v0.9.0

type Hierarchy interface {
	// Parent returns the parent user or PID namespace of this user or PID
	// namespace. If there is no parent namespace or the parent namespace in
	// inaccessible, then Parent returns nil.
	Parent() Hierarchy
	// Children returns a list of child PID or user namespaces for this PID or
	// user namespace.
	Children() []Hierarchy
}

Hierarchy informs about the parent-child relationships of PID and user namespaces.

func SortChildNamespaces added in v0.9.0

func SortChildNamespaces(nslist []Hierarchy) []Hierarchy

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).

type HierarchyConfigurer added in v0.9.0

type HierarchyConfigurer interface {
	AddChild(child Hierarchy)
	SetParent(parent Hierarchy)
}

HierarchyConfigurer allows discovery mechanisms to configure the information hold by hierarchical namespaces.

type Namespace added in v0.9.0

type Namespace interface {
	// ID returns the unique identifier of this Linux-kernel namespace. This
	// identifier is basically a tuple consisting of an inode number from the
	// special "nsfs" namespace filesystem inside the Linux kernel, together
	// with the device ID of that nsfs filesystem. IDs cannot be set as only the
	// Linux allocates and manages them.
	ID() species.NamespaceID
	// Type returns the type of namespace in form of one of the NamespaceType, such
	// as species.CLONE_NEWNS, species.CLONE_NEWCGROUP, et cetera.
	Type() species.NamespaceType
	// Owner returns the user namespace "owning" this namespace. For user
	// namespaces, Owner always returns nil; use Hierarchy.Parent() instead, as
	// the owner of a user namespace is its parent user namespace.
	Owner() Ownership
	// Ref returns a filesystem path suitable for referencing this namespace. A zero
	// ref indicates that there is no reference path available: this is the case for
	// "hidden" PID and user namespaces sandwiched in between PID or user namespaces
	// where reference paths are available, because these other namespaces have
	// processes joined to them, or are either bind-mounted or fd-referenced. Hidden
	// PID namespaces can appear only when there is no process in any of their child
	// namespaces and the child PID namespace(s) is bind-mounted or fd-references
	// (the parent PID namespace is then kept alive because the child PID namespaces
	// are kept alive).
	Ref() string
	// Leaders returns an unsorted list of Process-es which are joined to this
	// namespace and which are the topmost processes in the process tree still
	// joined to this namespace.
	Leaders() []*Process
	// LeaderPIDs returns the list of leader PIDs. This is a convenience method for
	// those use cases where just a list of leader process PIDs is needed, but not
	// the leader Process objects themselves.
	LeaderPIDs() []PIDType // "leader" process PIDs only.
	// Ealdorman returns the most senior leader process. The "most senior"
	// process is the one which was created at the earliest, based on the start
	// times from /proc/[PID]/stat. Me thinks, me has read too many Bernard
	// Cornwell books. Wyrd bið ful aræd.
	Ealdorman() *Process
	// String describes this namespace with type, id, joined leader processes,
	// and optionally information about owner, children, parent.
	String() string
}

Namespace represents a Linux kernel namespace in terms of its unique identifier, type, owning user namespace, joined (leader) processes, and some more.

func NewNamespace added in v0.9.0

func NewNamespace(nstype species.NamespaceType, nsid species.NamespaceID, ref string) Namespace

NewNamespace returns a new zero'ed namespace object suitable for the specified type of namespace. Now this is a real-world case where the "nongonformist" rule of "accept interfaces, return structs" doesn't make sense, because struct types don't support polymorphism. On the other hand, thousands of blog posts and SO answers cannot be wrong, more so, the more upvotes they accumulated ;)

func SortNamespaces added in v0.9.0

func SortNamespaces(nslist []Namespace) []Namespace

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 NamespaceMap) []Namespace

SortedNamespaces returns the namespaces from a map sorted.

type NamespaceConfigurer added in v0.9.0

type NamespaceConfigurer interface {
	AddLeader(proc *Process)               // adds yet another self-styled leader.
	SetRef(string)                         // sets a filesystem path for referencing this namespace.
	DetectOwner(nsf *ops.NamespaceFile)    // detects owning user namespace id.
	SetOwner(usernsid species.NamespaceID) // sets the owning user namespace id directly.
	ResolveOwner(usernsmap NamespaceMap)   // resolves owner ns id into object reference.
}

NamespaceConfigurer allows discovery mechanisms to set up the information for a namespace. This is a lxkns-internal interface needed by other lxkns subpackages.

type NamespaceMap added in v0.9.0

type NamespaceMap map[species.NamespaceID]Namespace

NamespaceMap indexes a bunch of Namespaces by their identifiers. Usually, namespace indices will contain only namespaces of the same type.

type NamespaceStringer added in v0.9.0

type NamespaceStringer interface {
	fmt.Stringer
	// TypeIDString describes this instance of a Linux kernel namespace just by
	// its type and identifier, and nothing else.
	TypeIDString() string
}

NamespaceStringer describes a namespace either in its descriptive form when using the well-known String() method, or in a terse format when going for TypeIDString(), which only describes the type and identifier of a namespace.

type NamespaceTypeIndex added in v0.9.0

type NamespaceTypeIndex int

NamespaceTypeIndex is an array index type for Linux kernel namespace types. It is used with the AllNamespaces type, which is an array of namespace maps, one map "id->namespace object" for each type of Linux kernel namespace. NamespaceTypeIndex must not be confused with the Linux' kernel namespace clone() syscall constants as typed as NamespaceType instead.

const (
	MountNS  NamespaceTypeIndex = iota // array index for mount namespaces map
	CgroupNS                           // array index for cgroup namespaces map
	UTSNS                              // array index for UTS namespaces map
	IPCNS                              // array index for IPC namespaces map
	UserNS                             // array index for user namespaces map
	PIDNS                              // array index for PID namespaces map
	NetNS                              // array index for net namespaces map
	TimeNS                             // array index for time namespaces map

	NamespaceTypesCount // number of namespace types
)

Set of indices into AllNamespaces arrays, one for each type of Linux kernel namespace.

func TypeIndex added in v0.9.0

func TypeIndex(nstype species.NamespaceType) NamespaceTypeIndex

TypeIndex returns the AllNamespaces array index corresponding with the specified Linux' kernel clone() syscall namespace constant. For instance, for CLONE_NEWNET the index NetNS is then returned.

type NamespacedPID added in v0.9.0

type NamespacedPID struct {
	PIDNS Namespace // PID namespace ID for PID.
	PID   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() []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 NamespacesSet added in v0.9.0

type NamespacesSet [NamespaceTypesCount]Namespace

NamespacesSet contains a Namespace reference of each type exactly once. For instance, it represents the set of 7 namespaces a process will always be joined ("attached", ...) to. Processes cannot be not attached to each type of Linux kernel namespace.

type Ownership added in v0.9.0

type Ownership interface {
	// UID returns the user ID of the process that created this user namespace.
	UID() int
	// Ownings returns all namespaces owned by this user namespace, with the
	// exception of user namespaces. "Owned" user namespaces are actually child
	// user namespaces, so they are returned through Hierarchy.Children()
	// instead.
	Ownings() AllNamespaces
}

Ownership informs about the owning user ID, as well as the namespaces owned by a specific user namespace. Only user namespaces can execute Ownership.

type PIDMap added in v0.9.0

type PIDMap struct {
	// contains filtered or unexported fields
}

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(res *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

func (pm *PIDMap) NamespacedPIDs(pid PIDType, from Namespace) NamespacedPIDs

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 (pm *PIDMap) Translate(pid PIDType, from Namespace, to Namespace) 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".

type PIDType added in v0.9.0

type PIDType int32

PIDType expresses things more clearly. And no, that's not a "PidType" since "PID" is an acronym (https://en.wikipedia.org/wiki/Acronym), but neither an abbreviation, nor an ordinary word (yet/still) in itself.

func NSpid added in v0.9.0

func NSpid(proc *Process) (pids []PIDType)

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 own PID namespaces to calculate the correct namespacing.

type Process added in v0.9.0

type Process struct {
	PID        PIDType       // this process' identifier.
	PPID       PIDType       // parent's process identifier.
	Parent     *Process      // our parent's process description.
	Children   []*Process    // child processes.
	Name       string        // synthesized name of process.
	Cmdline    []string      // command line of process.
	Namespaces NamespacesSet // the 7 namespaces joined by this process.
	Starttime  uint64        // Time of process start, since the Kernel boot epoch.
}

Process represents our very limited view and even more limited interest in a specific Linux process. Well, the limitation comes from what we need for namespace discovery to be useful.

func NewProcess added in v0.9.0

func NewProcess(PID PIDType) (proc *Process)

NewProcess returns a Process object describing certain properties of the Linux process with the specified PID. In particular, the parent PID and the name of the process, as well as the command line.

func (*Process) Basename added in v0.9.0

func (p *Process) Basename() (basename string)

Basename returns the process executable name with the directory stripped off, similar to what basename(1) does when applied to the "$0" argument. In case the basename would be empty, then the process name is returned instead as fallback.

func (*Process) String added in v0.9.0

func (p *Process) String() string

String praises a Process object with a text hymn.

func (*Process) Valid added in v0.9.0

func (p *Process) Valid() bool

Valid checks for the same process to still be present in the OS process table and then returns true, otherwise false. The validity check bases on the start time of the process, so stale PIDs can be detected even if they get reused after some time.

type ProcessListByPID added in v0.9.0

type ProcessListByPID []*Process

ProcessListByPID is a type alias for sorting slices of *Process by their PIDs in numerically ascending order.

func (ProcessListByPID) Len added in v0.9.0

func (l ProcessListByPID) Len() int

func (ProcessListByPID) Less added in v0.9.0

func (l ProcessListByPID) Less(i, j int) bool

func (ProcessListByPID) Swap added in v0.9.0

func (l ProcessListByPID) Swap(i, j int)

type ProcessTable added in v0.9.0

type ProcessTable map[PIDType]*Process

ProcessTable maps PIDs to their Process descriptions, allowing for quick lookups.

func NewProcessTable added in v0.9.0

func NewProcessTable() (pt ProcessTable)

NewProcessTable takes returns the currently available processes (as usual, without tasks=threads). The process table is in fact a map, indexed by PIDs.

Directories

Path Synopsis
cmd
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.
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
Package nstest provides testing support in the context of Linux kernel namespaces.
Package nstest provides testing support in the context of Linux kernel namespaces.
Package ops provides a Golang-idiomatic API to query and switching operations on Linux-kernel namespaces.
Package ops provides a Golang-idiomatic API to query and switching operations on Linux-kernel namespaces.
Package species defines the type constants and type names of the 7 Linux kernel namespace types ("species").
Package species defines the type constants and type names of the 7 Linux kernel namespace types ("species").

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL