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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
|
package device
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
liblxc "gopkg.in/lxc/go-lxc.v2"
"github.com/lxc/incus/v6/internal/linux"
"github.com/lxc/incus/v6/internal/server/apparmor"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/db/cluster"
"github.com/lxc/incus/v6/internal/server/db/warningtype"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/device/nictype"
firewallDrivers "github.com/lxc/incus/v6/internal/server/firewall/drivers"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/ip"
"github.com/lxc/incus/v6/internal/server/network"
"github.com/lxc/incus/v6/internal/server/project"
"github.com/lxc/incus/v6/internal/server/warnings"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/subprocess"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
type proxy struct {
deviceCommon
}
type proxyProcInfo struct {
listenPid string
listenPidFd string
connectPid string
connectPidFd string
connectAddr string
listenAddr string
listenAddrGID string
listenAddrUID string
listenAddrMode string
securityUID string
securityGID string
proxyProtocol string
inheritFds []*os.File
}
// CanHotPlug returns whether the device can be managed whilst the instance is running.
func (d *proxy) CanHotPlug() bool {
return true
}
// validateConfig checks the supplied config for correctness.
func (d *proxy) validateConfig(instConf instance.ConfigReader) error {
if !instanceSupported(instConf.Type(), instancetype.Container, instancetype.VM) {
return ErrUnsupportedDevType
}
validateAddr := func(input string) error {
_, err := network.ProxyParseAddr(input)
return err
}
// Supported bind types are: "host" or "instance" (or "guest" or "container", legacy options equivalent to "instance").
// If an empty value is supplied the default behavior is to assume "host" bind mode.
validateBind := func(input string) error {
if !slices.Contains([]string{"host", "instance", "guest", "container"}, d.config["bind"]) {
return errors.New("Invalid binding side given. Must be \"host\" or \"instance\"")
}
return nil
}
rules := map[string]func(string) error{
// gendoc:generate(entity=devices, group=proxy, key=listen)
//
// ---
// type: string
// required: yes
// shortdesc: The address and port to bind and listen (`<type>:<addr>:<port>[-<port>][,<port>]`)
"listen": validate.Required(validateAddr),
// gendoc:generate(entity=devices, group=proxy, key=connect)
//
// ---
// type: string
// required: yes
// shortdesc: The address and port to connect to (`<type>:<addr>:<port>[-<port>][,<port>]`)
"connect": validate.Required(validateAddr),
// gendoc:generate(entity=devices, group=proxy, key=bind)
//
// ---
// type: string
// required: no
// default: `host`
// shortdesc: Which side to bind on (`host`/`instance`)
"bind": validate.Optional(validateBind),
// gendoc:generate(entity=devices, group=proxy, key=mode)
//
// ---
// type: int
// required: no
// default: `0644`
// shortdesc: Mode for the listening Unix socket
"mode": validate.Optional(unixValidOctalFileMode),
// gendoc:generate(entity=devices, group=proxy, key=nat)
//
// ---
// type: bool
// required: no
// default: `false`
// shortdesc: Whether to optimize proxying via NAT (requires that the instance NIC has a static IP address)
"nat": validate.Optional(validate.IsBool),
// gendoc:generate(entity=devices, group=proxy, key=gid)
//
// ---
// type: int
// required: no
// default: `0`
// shortdesc: GID of the owner of the listening Unix socket
"gid": validate.Optional(unixValidUserID),
// gendoc:generate(entity=devices, group=proxy, key=uid)
//
// ---
// type: int
// required: no
// default: `0`
// shortdesc: UID of the owner of the listening Unix socket
"uid": validate.Optional(unixValidUserID),
// gendoc:generate(entity=devices, group=proxy, key=security.uid)
//
// ---
// type: int
// required: no
// default: `0`
// shortdesc: What UID to drop privilege to
"security.uid": validate.Optional(unixValidUserID),
// gendoc:generate(entity=devices, group=proxy, key=security.gid)
//
// ---
// type: int
// required: no
// default: `0`
// shortdesc: What GID to drop privilege to
"security.gid": validate.Optional(unixValidUserID),
// gendoc:generate(entity=devices, group=proxy, key=proxy_protocol)
//
// ---
// type: bool
// required: no
// default: `false`
// shortdesc: Whether to use the HAProxy PROXY protocol to transmit sender information
"proxy_protocol": validate.Optional(validate.IsBool),
}
err := d.config.Validate(rules)
if err != nil {
return err
}
if instConf.Type() == instancetype.VM && util.IsFalseOrEmpty(d.config["nat"]) {
return errors.New("Only NAT mode is supported for proxies on VM instances")
}
listenAddr, err := network.ProxyParseAddr(d.config["listen"])
if err != nil {
return err
}
connectAddr, err := network.ProxyParseAddr(d.config["connect"])
if err != nil {
return err
}
err = d.validateListenAddressConflicts(net.ParseIP(listenAddr.Address))
if err != nil {
return err
}
if (listenAddr.ConnType != "unix" && len(connectAddr.Ports) > len(listenAddr.Ports)) || (listenAddr.ConnType == "unix" && len(connectAddr.Ports) > 1) {
// Cannot support single address (or port) -> multiple port.
return errors.New("Mismatch between listen port(s) and connect port(s) count")
}
if util.IsTrue(d.config["proxy_protocol"]) && (!strings.HasPrefix(d.config["connect"], "tcp") || util.IsTrue(d.config["nat"])) {
return errors.New("The PROXY header can only be sent to tcp servers in non-nat mode")
}
if (!strings.HasPrefix(d.config["listen"], "unix:") || strings.HasPrefix(d.config["listen"], "unix:@")) &&
(d.config["uid"] != "" || d.config["gid"] != "" || d.config["mode"] != "") {
return errors.New("Only proxy devices for non-abstract unix sockets can carry uid, gid, or mode properties")
}
if util.IsTrue(d.config["nat"]) {
if d.inst != nil {
// Default project always has networks feature so don't bother loading the project config
// in that case.
instProject := d.inst.Project()
if instProject.Name != api.ProjectDefaultName && util.IsTrue(instProject.Config["features.networks"]) {
// Prevent use of NAT mode on non-default projects with networks feature.
// This is because OVN networks don't allow the host to communicate directly with
// instance NICs and so DNAT rules on the host won't work.
return errors.New("NAT mode cannot be used in projects that have the networks feature")
}
}
if d.config["bind"] != "" && d.config["bind"] != "host" {
return errors.New("Only host-bound proxies can use NAT")
}
// Support TCP <-> TCP and UDP <-> UDP only.
if listenAddr.ConnType == "unix" || connectAddr.ConnType == "unix" || listenAddr.ConnType != connectAddr.ConnType {
return fmt.Errorf("Proxying %s <-> %s is not supported when using NAT", listenAddr.ConnType, connectAddr.ConnType)
}
listenAddress := net.ParseIP(listenAddr.Address)
if listenAddress.Equal(net.IPv4zero) || listenAddress.Equal(net.IPv6zero) {
return fmt.Errorf("Cannot listen on wildcard address %q when in nat mode", listenAddress.String())
}
// Records which listen address IP version, as these cannot be mixed in NAT mode.
listenIPVersion := uint(4)
if listenAddress.To4() == nil {
listenIPVersion = 6
}
// Check connect address against the listen address IP version and check they match.
connectAddress := net.ParseIP(connectAddr.Address)
connectIPVersion := uint(4)
if connectAddress.To4() == nil {
connectIPVersion = 6
}
if listenIPVersion != connectIPVersion {
return errors.New("Cannot mix IP versions between listen and connect in nat mode")
}
}
return nil
}
// validateEnvironment checks the runtime environment for correctness.
func (d *proxy) validateEnvironment() error {
if d.name == "" {
return errors.New("Device name cannot be empty")
}
return nil
}
// validateListenAddressConflicts checks that the proxy device about to be created does not
// overlap on existing network forward (both entities can't have the same listening address with
// the same port number).
func (d *proxy) validateListenAddressConflicts(proxyListenAddr net.IP) error {
return d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var projectNetworksForwardsOnUplink map[string]map[int64][]string
networksByProjects, err := tx.GetNetworksAllProjects(ctx)
if err != nil {
return fmt.Errorf("Failed loading network forward listen addresses: %w", err)
}
for projectName, networks := range networksByProjects {
for _, networkName := range networks {
networkID, err := tx.GetNetworkID(ctx, projectName, networkName)
if err != nil {
return fmt.Errorf("Failed loading network forward listen addresses: %w", err)
}
// Get all network forward listen addresses for all networks (of any type) connected to our uplink.
networkForwards, err := cluster.GetNetworkForwards(ctx, tx.Tx(), cluster.NetworkForwardFilter{
NetworkID: &networkID,
})
if err != nil {
return fmt.Errorf("Failed loading network forward listen addresses: %w", err)
}
projectNetworksForwardsOnUplink = make(map[string]map[int64][]string)
for _, forward := range networkForwards {
// Filter network forwards that belong to this specific cluster member
if forward.NodeID.Valid && (forward.NodeID.Int64 == tx.GetNodeID()) {
if projectNetworksForwardsOnUplink[projectName] == nil {
projectNetworksForwardsOnUplink[projectName] = make(map[int64][]string)
}
projectNetworksForwardsOnUplink[projectName][networkID] = append(projectNetworksForwardsOnUplink[projectName][networkID], forward.ListenAddress)
}
}
}
}
for _, networks := range projectNetworksForwardsOnUplink {
for _, listenAddresses := range networks {
for _, netFwdAddr := range listenAddresses {
if proxyListenAddr.Equal(net.ParseIP(netFwdAddr)) {
return fmt.Errorf("Listen address %q conflicts with existing network forward", netFwdAddr)
}
}
}
}
return nil
})
}
// Start is run when the device is added to the instance.
func (d *proxy) Start() (*deviceConfig.RunConfig, error) {
err := d.validateEnvironment()
if err != nil {
return nil, err
}
// Proxy devices have to be setup once the instance is running.
runConf := deviceConfig.RunConfig{}
runConf.PostHooks = []func() error{
func() error {
if util.IsTrue(d.config["nat"]) {
err = d.setupNAT()
if err != nil {
return fmt.Errorf("Failed to start device %q: %w", d.name, err)
}
return nil // Don't proceed with forkproxy setup.
}
proxyValues, err := d.setupProxyProcInfo()
if err != nil {
return err
}
devFileName := fmt.Sprintf("proxy.%s", d.name)
pidPath := filepath.Join(d.inst.DevicesPath(), devFileName)
logFileName := fmt.Sprintf("proxy.%s.log", d.name)
logPath := filepath.Join(d.inst.LogPath(), logFileName)
// Load the apparmor profile
err = apparmor.ForkproxyLoad(d.state.OS, d.inst, d)
if err != nil {
return fmt.Errorf("Failed to start device %q: %w", d.name, err)
}
// Spawn the daemon using subprocess
command := d.state.OS.ExecPath
forkproxyargs := []string{
"forkproxy",
"--",
proxyValues.listenPid,
proxyValues.listenPidFd,
proxyValues.listenAddr,
proxyValues.connectPid,
proxyValues.connectPidFd,
proxyValues.connectAddr,
proxyValues.listenAddrGID,
proxyValues.listenAddrUID,
proxyValues.listenAddrMode,
proxyValues.securityGID,
proxyValues.securityUID,
proxyValues.proxyProtocol,
}
p, err := subprocess.NewProcess(command, forkproxyargs, logPath, logPath)
if err != nil {
return fmt.Errorf("Failed to start device %q: Failed to creating subprocess: %w", d.name, err)
}
p.SetApparmor(apparmor.ForkproxyProfileName(d.inst, d))
err = p.StartWithFiles(context.Background(), proxyValues.inheritFds)
if err != nil {
return fmt.Errorf("Failed to start device %q: Failed running: %s %s: %w", d.name, command, strings.Join(forkproxyargs, " "), err)
}
for _, file := range proxyValues.inheritFds {
_ = file.Close()
}
// Poll log file a few times until we see "Started" to indicate successful start.
for range 10 {
started, err := d.checkProcStarted(logPath)
if err != nil {
_ = p.Stop()
return fmt.Errorf("Error occurred when starting proxy device: %s", err)
}
if started {
err = p.Save(pidPath)
if err != nil {
// Kill Process if started, but could not save the file
err2 := p.Stop()
if err != nil {
return fmt.Errorf("Could not kill subprocess while handling saving error: %s: %s", err, err2)
}
return fmt.Errorf("Failed to start device %q: Failed saving subprocess details: %w", d.name, err)
}
return nil
}
time.Sleep(time.Second)
}
_ = p.Stop()
return fmt.Errorf("Failed to start device %q: Please look in %s", d.name, logPath)
},
}
return &runConf, nil
}
// checkProcStarted checks for the "Started" line in the log file. Returns true if found, false
// if not, and error if any other error occurs.
func (d *proxy) checkProcStarted(logPath string) (bool, error) {
file, err := os.Open(logPath)
if err != nil {
return false, err
}
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "Status: Started" {
return true, nil
}
if strings.HasPrefix(line, "Error:") {
return false, fmt.Errorf("%s", line)
}
}
err = scanner.Err()
if err != nil {
return false, err
}
return false, nil
}
// Stop is run when the device is removed from the instance.
func (d *proxy) Stop() (*deviceConfig.RunConfig, error) {
// Remove possible iptables entries
err := d.state.Firewall.InstanceClearProxyNAT(d.inst.Project().Name, d.inst.Name(), d.name)
if err != nil {
logger.Errorf("Failed to remove proxy NAT filters: %v", err)
}
devFileName := fmt.Sprintf("proxy.%s", d.name)
devPath := filepath.Join(d.inst.DevicesPath(), devFileName)
if !util.PathExists(devPath) {
// There's no proxy process if NAT is enabled
return nil, nil
}
err = d.killProxyProc(devPath)
if err != nil {
return nil, err
}
// Unload apparmor profile.
err = apparmor.ForkproxyUnload(d.state.OS, d.inst, d)
if err != nil {
return nil, err
}
return nil, nil
}
func (d *proxy) setupNAT() error {
listenAddr, err := network.ProxyParseAddr(d.config["listen"])
if err != nil {
return err
}
connectAddr, err := network.ProxyParseAddr(d.config["connect"])
if err != nil {
return err
}
ipVersion := uint(4)
if strings.Contains(listenAddr.Address, ":") {
ipVersion = 6
}
var connectIP net.IP
var hostName string
for devName, devConfig := range d.inst.ExpandedDevices() {
if devConfig["type"] != "nic" {
continue
}
nicType, err := nictype.NICType(d.state, d.inst.Project().Name, devConfig)
if err != nil {
return err
}
// Check if the instance has a NIC with a static IP that is reachable from the host.
if !slices.Contains([]string{"bridged", "routed"}, nicType) {
continue
}
// Ensure the connect IP matches one of the NIC's static IPs otherwise we could mess with other
// instance's network traffic. If the wildcard address is supplied as the connect host then the
// first bridged NIC which has a static IP address defined is selected as the connect host IP.
if ipVersion == 4 && devConfig["ipv4.address"] != "" {
if connectAddr.Address == devConfig["ipv4.address"] || connectAddr.Address == "0.0.0.0" {
connectIP = net.ParseIP(devConfig["ipv4.address"])
}
} else if ipVersion == 6 && devConfig["ipv6.address"] != "" {
if connectAddr.Address == devConfig["ipv6.address"] || connectAddr.Address == "::" {
connectIP = net.ParseIP(devConfig["ipv6.address"])
}
}
if connectIP != nil {
// Get host_name of device so we can enable hairpin mode on bridge port.
hostName = d.inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.host_name", devName)]
break // Found a match, stop searching.
}
}
if connectIP == nil {
if connectAddr.Address == "0.0.0.0" || connectAddr.Address == "::" {
return fmt.Errorf("Instance has no static IPv%d address assigned to be used as the connect IP", ipVersion)
}
return fmt.Errorf("Connect IP %q must be one of the instance's static IPv%d addresses", connectAddr.Address, ipVersion)
}
// Override the host part of the connectAddr.Addr to the chosen connect IP.
connectAddr.Address = connectIP.String()
err = network.BridgeNetfilterEnabled(ipVersion)
if err != nil {
msg := fmt.Sprintf("IPv%d bridge netfilter not enabled. Instances using the bridge will not be able to connect to the proxy listen IP", ipVersion)
d.logger.Warn(msg, logger.Ctx{"err": err})
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpsertWarningLocalNode(ctx, d.inst.Project().Name, cluster.TypeInstance, d.inst.ID(), warningtype.ProxyBridgeNetfilterNotEnabled, fmt.Sprintf("%s: %v", msg, err))
})
if err != nil {
logger.Warn("Failed to create warning", logger.Ctx{"err": err})
}
} else {
err = warnings.ResolveWarningsByLocalNodeAndProjectAndTypeAndEntity(d.state.DB.Cluster, d.inst.Project().Name, warningtype.ProxyBridgeNetfilterNotEnabled, cluster.TypeInstance, d.inst.ID())
if err != nil {
logger.Warn("Failed to resolve warning", logger.Ctx{"err": err})
}
if hostName == "" {
return errors.New("Proxy cannot find bridge port host_name to enable hairpin mode")
}
// br_netfilter is enabled, so we need to enable hairpin mode on instance's bridge port otherwise
// the instances on the bridge will not be able to connect to the proxy device's listen IP and the
// NAT rule added by the firewall below to allow instance <-> instance traffic will also not work.
link := &ip.Link{Name: hostName}
err = link.BridgeLinkSetHairpin(true)
if err != nil {
return fmt.Errorf("Error enabling hairpin mode on bridge port %q: %w", hostName, err)
}
}
// Convert proxy listen & connect addresses for firewall AddressForward.
addressForward := firewallDrivers.AddressForward{
Protocol: listenAddr.ConnType,
ListenAddress: net.ParseIP(listenAddr.Address),
ListenPorts: listenAddr.Ports,
TargetAddress: net.ParseIP(connectAddr.Address),
TargetPorts: connectAddr.Ports,
}
err = d.state.Firewall.InstanceSetupProxyNAT(d.inst.Project().Name, d.inst.Name(), d.name, &addressForward)
if err != nil {
return err
}
return nil
}
func (d *proxy) setupProxyProcInfo() (*proxyProcInfo, error) {
cname := project.Instance(d.inst.Project().Name, d.inst.Name())
cc, err := liblxc.NewContainer(cname, d.state.OS.LxcPath)
if err != nil {
return nil, err
}
defer func() { _ = cc.Release() }()
containerPid := strconv.Itoa(cc.InitPid())
daemonPid := strconv.Itoa(os.Getpid())
containerPidFd := -1
daemonPidFd := -1
var inheritFd []*os.File
if d.state.OS.PidFds {
cPidFd, err := cc.InitPidFd()
if err == nil {
dPidFd, err := linux.PidFdOpen(os.Getpid(), 0)
if err == nil {
inheritFd = []*os.File{cPidFd, dPidFd}
containerPidFd = 3
daemonPidFd = 4
}
}
}
var listenPid, listenPidFd, connectPid, connectPidFd string
connectAddr := d.config["connect"]
listenAddr := d.config["listen"]
switch d.config["bind"] {
case "host", "":
listenPid = daemonPid
listenPidFd = fmt.Sprintf("%d", daemonPidFd)
connectPid = containerPid
connectPidFd = fmt.Sprintf("%d", containerPidFd)
case "instance", "guest", "container":
listenPid = containerPid
listenPidFd = fmt.Sprintf("%d", containerPidFd)
connectPid = daemonPid
connectPidFd = fmt.Sprintf("%d", daemonPidFd)
default:
return nil, errors.New("Invalid binding side given. Must be \"host\" or \"instance\"")
}
listenAddrMode := "0644"
if d.config["mode"] != "" {
listenAddrMode = d.config["mode"]
}
p := &proxyProcInfo{
listenPid: listenPid,
listenPidFd: listenPidFd,
connectPid: connectPid,
connectPidFd: connectPidFd,
connectAddr: connectAddr,
listenAddr: listenAddr,
listenAddrGID: d.config["gid"],
listenAddrUID: d.config["uid"],
listenAddrMode: listenAddrMode,
securityGID: d.config["security.gid"],
securityUID: d.config["security.uid"],
proxyProtocol: d.config["proxy_protocol"],
inheritFds: inheritFd,
}
return p, nil
}
func (d *proxy) killProxyProc(pidPath string) error {
// If the pid file doesn't exist, there is no process to kill.
if !util.PathExists(pidPath) {
return nil
}
p, err := subprocess.ImportProcess(pidPath)
if err != nil {
return fmt.Errorf("Could not read pid file: %s", err)
}
err = p.Stop()
if err != nil && !errors.Is(err, subprocess.ErrNotRunning) {
return fmt.Errorf("Unable to kill forkproxy: %s", err)
}
_ = os.Remove(pidPath)
return nil
}
func (d *proxy) Remove() error {
err := warnings.DeleteWarningsByLocalNodeAndProjectAndTypeAndEntity(d.state.DB.Cluster, d.inst.Project().Name, warningtype.ProxyBridgeNetfilterNotEnabled, cluster.TypeInstance, d.inst.ID())
if err != nil {
logger.Warn("Failed to delete warning", logger.Ctx{"err": err})
}
// Delete apparmor profile.
err = apparmor.ForkproxyDelete(d.state.OS, d.inst, d)
if err != nil {
return err
}
return nil
}
|