File: bypass4netnsd.go

package info (click to toggle)
golang-github-rootless-containers-bypass4netns 0.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 596 kB
  • sloc: sh: 1,936; python: 542; makefile: 33
file content (264 lines) | stat: -rw-r--r-- 6,644 bytes parent folder | download | duplicates (2)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package bypass4netnsd

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"sync"
	"syscall"
	"time"

	"github.com/rootless-containers/bypass4netns/pkg/api"
	"github.com/rootless-containers/bypass4netns/pkg/api/com"
	"github.com/rootless-containers/bypass4netns/pkg/util"
	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

type Driver struct {
	BypassExecutablePath string
	ComSocketPath        string
	bypass               map[string]api.BypassStatus
	lock                 sync.RWMutex
	containerInterfaces  map[string]com.ContainerInterfaces
	interfacesLock       sync.RWMutex
	HandleC2CEnable      bool
	TracerEnable         bool
	MultinodeEnable      bool
	MultinodeEtcdAddress string
	MultinodeHostAddress string
}

func NewDriver(execPath string, comSocketPath string) *Driver {
	return &Driver{
		BypassExecutablePath: execPath,
		ComSocketPath:        comSocketPath,
		bypass:               map[string]api.BypassStatus{},
		lock:                 sync.RWMutex{},
		containerInterfaces:  map[string]com.ContainerInterfaces{},
		interfacesLock:       sync.RWMutex{},
		TracerEnable:         false,
		MultinodeEnable:      false,
	}
}

func (d *Driver) ListBypass() []api.BypassStatus {
	d.lock.RLock()
	defer d.lock.RUnlock()

	res := []api.BypassStatus{}
	for _, v := range d.bypass {
		res = append(res, v)
	}

	return res
}

func (d *Driver) StartBypass(spec *api.BypassSpec) (*api.BypassStatus, error) {
	logger := logrus.WithFields(logrus.Fields{"ID": util.ShrinkID(spec.ID)})
	logger.Info("Starting bypass")
	b4nnArgs := []string{}

	if logger.Logger.GetLevel() == logrus.DebugLevel {
		b4nnArgs = append(b4nnArgs, "--debug")
	}

	if spec.SocketPath != "" {
		socketOption := fmt.Sprintf("--socket=%s", spec.SocketPath)
		b4nnArgs = append(b4nnArgs, socketOption)
	}

	if spec.PidFilePath != "" {
		pidFileOption := fmt.Sprintf("--pid-file=%s", spec.PidFilePath)
		b4nnArgs = append(b4nnArgs, pidFileOption)
	}

	if spec.LogFilePath != "" {
		logFileOption := fmt.Sprintf("--log-file=%s", spec.LogFilePath)
		b4nnArgs = append(b4nnArgs, logFileOption)
	}

	for _, port := range spec.PortMapping {
		b4nnArgs = append(b4nnArgs, fmt.Sprintf("-p=%d:%d", port.ParentPort, port.ChildPort))
	}

	for _, subnet := range spec.IgnoreSubnets {
		b4nnArgs = append(b4nnArgs, fmt.Sprintf("--ignore=%s", subnet))
	}

	if spec.IgnoreBind {
		b4nnArgs = append(b4nnArgs, "--ignore-bind")
	}

	b4nnArgs = append(b4nnArgs, fmt.Sprintf("--com-socket=%s", d.ComSocketPath))
	if d.HandleC2CEnable {
		b4nnArgs = append(b4nnArgs, "--handle-c2c-connections")
	}
	if d.TracerEnable {
		b4nnArgs = append(b4nnArgs, "--tracer=true")
	}

	if d.MultinodeEnable {
		b4nnArgs = append(b4nnArgs, "--multinode=true")
		b4nnArgs = append(b4nnArgs, fmt.Sprintf("--multinode-etcd-address=%s", d.MultinodeEtcdAddress))
		b4nnArgs = append(b4nnArgs, fmt.Sprintf("--multinode-host-address=%s", d.MultinodeHostAddress))
	}

	// prepare pipe for ready notification
	readyR, readyW, err := os.Pipe()
	if err != nil {
		return nil, err
	}
	defer readyR.Close()
	defer readyW.Close()

	// fd in b4nnCmd.ExtraFiles is assigned in child process from fd=3
	readyFdOption := "--ready-fd=3"
	b4nnArgs = append(b4nnArgs, readyFdOption)

	logger.Infof("bypass4netns args:%v", b4nnArgs)
	b4nnCmd := exec.Command(d.BypassExecutablePath, b4nnArgs...)
	b4nnCmd.ExtraFiles = append(b4nnCmd.ExtraFiles, readyW)
	err = b4nnCmd.Start()
	if err != nil {
		return nil, err
	}

	err = waitForReadyFD(b4nnCmd.Process.Pid, readyR)
	if err != nil {
		return nil, err
	}
	logger.Info("bypass4netns successfully started")

	d.lock.Lock()
	defer d.lock.Unlock()
	status := api.BypassStatus{
		ID:   spec.ID,
		Pid:  b4nnCmd.Process.Pid,
		Spec: *spec,
	}

	d.bypass[status.ID] = status
	logger.Info("Started bypass")

	return &status, nil
}

func (d *Driver) StopBypass(id string) error {
	logger := logrus.WithFields(logrus.Fields{"ID": util.ShrinkID(id)})
	logger.Infof("Stopping bypass")
	d.lock.Lock()
	defer d.lock.Unlock()

	bStatus, ok := d.bypass[id]
	if !ok {
		return fmt.Errorf("child %s not found", id)
	}

	proc, err := os.FindProcess(bStatus.Pid)
	if err != nil {
		return err
	}
	logger.Debugf("bypass4netns found pid=%d", proc.Pid)

	logger.Infof("Terminating bypass4netns pid=%d", proc.Pid)
	err = proc.Signal(unix.SIGTERM)
	if err != nil {
		return err
	}

	// wait for the process exit
	// TODO: Timeout
	if _, err := proc.Wait(); err != nil {
		logrus.Warnf("Failed to terminate bypass4netns pid=%d with SIGTERM, killing...", proc.Pid)
		err = proc.Kill()
		if err != nil {
			return err
		}
		_, _ = proc.Wait()
	}
	logger.Infof("Terminated bypass4netns pid=%d", proc.Pid)

	delete(d.bypass, id)
	logger.Info("Stopped bypass")

	// remove the container's interfaces
	d.DeleteInterface(id)

	return nil
}

func (d *Driver) ListInterfaces() map[string]com.ContainerInterfaces {
	d.interfacesLock.RLock()
	defer d.interfacesLock.RUnlock()

	ifs := map[string]com.ContainerInterfaces{}
	// copy map
	for k := range d.containerInterfaces {
		ifs[k] = d.containerInterfaces[k]
	}

	return ifs
}

func (d *Driver) GetInterface(id string) *com.ContainerInterfaces {
	d.interfacesLock.RLock()
	defer d.interfacesLock.RUnlock()

	ifs, ok := d.containerInterfaces[id]
	if !ok {
		return nil
	}

	return &ifs
}

func (d *Driver) PostInterface(id string, containerIfs *com.ContainerInterfaces) {
	d.interfacesLock.Lock()
	defer d.interfacesLock.Unlock()

	d.containerInterfaces[id] = *containerIfs
}

func (d *Driver) DeleteInterface(id string) {
	d.interfacesLock.Lock()
	defer d.interfacesLock.Unlock()

	delete(d.containerInterfaces, id)
}

// waitForReady is from libpod
// https://github.com/containers/libpod/blob/e6b843312b93ddaf99d0ef94a7e60ff66bc0eac8/libpod/networking_linux.go#L272-L308
func waitForReadyFD(cmdPid int, r *os.File) error {
	b := make([]byte, 16)
	for {
		if err := r.SetDeadline(time.Now().Add(1 * time.Second)); err != nil {
			return fmt.Errorf("error setting bypass4netns pipe timeout: %w", err)
		}
		if _, err := r.Read(b); err == nil {
			break
		} else {
			if os.IsTimeout(err) {
				// Check if the process is still running.
				var status syscall.WaitStatus
				pid, err := syscall.Wait4(cmdPid, &status, syscall.WNOHANG, nil)
				if err != nil {
					return fmt.Errorf("failed to read bypass4netns process status: %w", err)
				}
				if pid != cmdPid {
					continue
				}
				if status.Exited() {
					return errors.New("bypass4netns failed")
				}
				if status.Signaled() {
					return errors.New("bypass4netns killed by signal")
				}
				continue
			}
			return fmt.Errorf("failed to read from bypass4netns sync pipe: %w", err)
		}
	}
	return nil
}