/ components / egress / shutdown.go
shutdown.go
 1  // Copyright 2026 Alibaba Group Holding Ltd.
 2  //
 3  // Licensed under the Apache License, Version 2.0 (the "License");
 4  // you may not use this file except in compliance with the License.
 5  // You may obtain a copy of the License at
 6  //
 7  //     http://www.apache.org/licenses/LICENSE-2.0
 8  //
 9  // Unless required by applicable law or agreed to in writing, software
10  // distributed under the License is distributed on an "AS IS" BASIS,
11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  // See the License for the specific language governing permissions and
13  // limitations under the License.
14  
15  package main
16  
17  import (
18  	"context"
19  	"errors"
20  	"net/http"
21  	"net/netip"
22  	"os"
23  	"time"
24  
25  	"github.com/alibaba/opensandbox/egress/pkg/dnsproxy"
26  	"github.com/alibaba/opensandbox/egress/pkg/iptables"
27  	"github.com/alibaba/opensandbox/egress/pkg/log"
28  	"github.com/alibaba/opensandbox/egress/pkg/mitmproxy"
29  )
30  
31  const (
32  	defaultPolicyShutdownTimeout = 5 * time.Second
33  	defaultNftTeardownTimeout    = 5 * time.Second
34  	defaultMitmShutdownTimeout   = 5 * time.Second
35  )
36  
37  func waitForShutdown(ctx context.Context, proxy *dnsproxy.Proxy, policySrv *http.Server, exemptDst []netip.Addr, applier nftApplier, mitm *mitmTransparent) {
38  	<-ctx.Done()
39  	log.Infof("received shutdown signal; beginning graceful shutdown")
40  
41  	policyShutdownCtx, policyCancel := context.WithTimeout(context.Background(), defaultPolicyShutdownTimeout)
42  	defer policyCancel()
43  
44  	if policySrv != nil {
45  		if err := policySrv.Shutdown(policyShutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
46  			log.Errorf("policy server shutdown error: %v", err)
47  		}
48  	}
49  	if err := proxy.Shutdown(); err != nil {
50  		log.Errorf("dns proxy shutdown error: %v", err)
51  	}
52  
53  	if mitm != nil {
54  		iptables.RemoveTransparentHTTP(mitm.port, mitm.uid)
55  		mitmproxy.GracefulShutdown(mitm.running, defaultMitmShutdownTimeout)
56  	}
57  
58  	proxy.SetOnResolved(nil)
59  	iptables.RemoveRedirect(15353, exemptDst)
60  
61  	if applier != nil {
62  		nftCtx, nftCancel := context.WithTimeout(context.Background(), defaultNftTeardownTimeout)
63  		defer nftCancel()
64  		if err := applier.RemoveEnforcement(nftCtx); err != nil {
65  			log.Errorf("nftables teardown error: %v", err)
66  		}
67  	}
68  
69  	log.Infof("egress shutdown complete")
70  	_ = os.Stderr.Sync()
71  }