summaryrefslogtreecommitdiff
path: root/internal/namespace/pinning.go
blob: cd81a38e7421e85cabe8c7e77a96e19036468fd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package namespace

import (
	"fmt"
	"os"

	"git.theodohertyfamily.com/tools/wg-wrap/internal/paths"
)

// UnpinNamespace removes the pinned namespace file from the filesystem.
// This allows the namespace to be destroyed once the last process exits.
func UnpinNamespace(pm *paths.PathManager, profile string) error {
	nsPath := GetProfileNamespacePath(pm, profile)

	// We only want to unpin if there are no more active processes.
	// The caller (cli.ExecuteCommand) is responsible for calling this
	// when IsLastProcess returns true.

	if _, err := os.Stat(nsPath); os.IsNotExist(err) {
		return nil
	}

	// We also want to remove the pids directory if it's empty.
	pidsDir := GetPidsDirPath(pm, profile)

	// Unlink the namespace file
	if err := os.Remove(nsPath); err != nil {
		return fmt.Errorf("failed to unpin namespace %s: %w", nsPath, err)
	}

	// Try to remove pids directory
	_ = os.Remove(pidsDir)

	return nil
}