/ components / internal / safego / safe.go
safe.go
 1  // Copyright 2025 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 safego
16  
17  import (
18  	"context"
19  	"net/http"
20  	"runtime"
21  
22  	"github.com/alibaba/opensandbox/internal/logger"
23  	runtimeutil "k8s.io/apimachinery/pkg/util/runtime"
24  )
25  
26  func InitPanicLogger(_ context.Context, log logger.Logger) {
27  	runtimeutil.PanicHandlers = []func(context.Context, any){
28  		func(_ context.Context, r any) {
29  			if r == http.ErrAbortHandler { // nolint:errorlint
30  				return
31  			}
32  
33  			const size = 64 << 10
34  			stacktrace := make([]byte, size)
35  			stacktrace = stacktrace[:runtime.Stack(stacktrace, false)]
36  			if _, ok := r.(string); ok {
37  				log.Errorf("Observed a panic: %s\n%s", r, stacktrace)
38  			} else {
39  				log.Errorf("Observed a panic: %#v (%v)\n%s", r, r, stacktrace)
40  			}
41  		},
42  	}
43  }
44  
45  func init() {
46  	runtimeutil.ReallyCrash = false
47  }
48  
49  func Go(f func()) {
50  	go func() {
51  		defer runtimeutil.HandleCrash()
52  
53  		f()
54  	}()
55  }