You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2023/04/22 14:17:33 UTC
[skywalking-go] branch main updated: Support native http-client plugin (#12)
This is an automated email from the ASF dual-hosted git repository.
wusheng pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-go.git
The following commit(s) were added to refs/heads/main by this push:
new 3848f25 Support native http-client plugin (#12)
3848f25 is described below
commit 3848f25c852dbadf5406806e8d4d642067ae0d3d
Author: mrproliu <74...@qq.com>
AuthorDate: Sat Apr 22 22:17:28 2023 +0800
Support native http-client plugin (#12)
---
plugins/ginv2/intercepter.go | 3 +-
plugins/http/go.mod | 11 ++++
plugins/http/go.sum | 9 +++
.../register.go => plugins/http/instrument.go | 44 +++++++++++---
plugins/{ginv2 => http}/intercepter.go | 42 +++++++------
tools/go-agent/go.mod | 2 +
.../go-agent/instrument/plugins/enhance_method.go | 28 +++++----
tools/go-agent/instrument/plugins/instrument.go | 16 +++--
tools/go-agent/instrument/plugins/register.go | 2 +
.../go-agent/instrument/plugins/rewrite/context.go | 12 +---
tools/go-agent/instrument/plugins/rewrite/func.go | 2 +
.../plugins/templates/method_inserts.tmpl | 6 +-
.../plugins/templates/method_intercept_after.tmpl | 2 +-
.../plugins/templates/method_intercept_before.tmpl | 6 +-
tools/go-agent/tools/enhancement.go | 69 +++++++++++++++++++++-
.../plugins/register.go => tools/types.go} | 22 +++----
16 files changed, 197 insertions(+), 79 deletions(-)
diff --git a/plugins/ginv2/intercepter.go b/plugins/ginv2/intercepter.go
index 49c5412..dccced9 100644
--- a/plugins/ginv2/intercepter.go
+++ b/plugins/ginv2/intercepter.go
@@ -37,7 +37,8 @@ func (h *HTTPInterceptor) BeforeInvoke(invocation *operator.Invocation) error {
},
tracing.WithLayer(tracing.SpanLayerHTTP),
tracing.WithTag(tracing.TagHTTPMethod, context.Request.Method),
- tracing.WithTag(tracing.TagURL, context.Request.Host+context.Request.URL.Path))
+ tracing.WithTag(tracing.TagURL, context.Request.Host+context.Request.URL.Path),
+ tracing.WithComponent(5006))
if err != nil {
return err
}
diff --git a/plugins/http/go.mod b/plugins/http/go.mod
new file mode 100644
index 0000000..adb4c8b
--- /dev/null
+++ b/plugins/http/go.mod
@@ -0,0 +1,11 @@
+module github.com/apache/skywalking-go/plugins/http
+
+go 1.18
+
+require github.com/apache/skywalking-go/plugins/core v0.0.0-20230414024435-7b292984eb80
+
+require github.com/dave/dst v0.27.2 // indirect
+
+replace github.com/apache/skywalking-go/plugins/core => ../core
+
+replace github.com/apache/skywalking-go => ../../
diff --git a/plugins/http/go.sum b/plugins/http/go.sum
new file mode 100644
index 0000000..7573d0f
--- /dev/null
+++ b/plugins/http/go.sum
@@ -0,0 +1,9 @@
+github.com/dave/dst v0.27.2 h1:4Y5VFTkhGLC1oddtNwuxxe36pnyLxMFXT51FOzH8Ekc=
+github.com/dave/dst v0.27.2/go.mod h1:jHh6EOibnHgcUW3WjKHisiooEkYwqpHLBSX1iOBhEyc=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
+golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
+golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
+golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/tools/go-agent/instrument/plugins/register.go b/plugins/http/instrument.go
similarity index 56%
copy from tools/go-agent/instrument/plugins/register.go
copy to plugins/http/instrument.go
index 6caf205..af9a822 100644
--- a/tools/go-agent/instrument/plugins/register.go
+++ b/plugins/http/instrument.go
@@ -15,20 +15,48 @@
// specific language governing permissions and limitations
// under the License.
-package plugins
+package http
import (
+ "embed"
+
"github.com/apache/skywalking-go/plugins/core/instrument"
- "github.com/apache/skywalking-go/plugins/ginv2"
)
-var instruments = make([]instrument.Instrument, 0)
+//go:embed *
+var fs embed.FS
+
+//skywalking:nocopy
+type Instrument struct {
+}
+
+func NewInstrument() *Instrument {
+ return &Instrument{}
+}
+
+func (i *Instrument) Name() string {
+ return "http"
+}
+
+func (i *Instrument) BasePackage() string {
+ return "net/http"
+}
+
+func (i *Instrument) VersionChecker(version string) bool {
+ return true
+}
-func init() {
- // register the plugins instrument
- registerFramework(ginv2.NewInstrument())
+func (i *Instrument) Points() []*instrument.Point {
+ return []*instrument.Point{
+ {
+ PackagePath: "",
+ At: instrument.NewMethodEnhance("Transport", "RoundTrip",
+ instrument.WithArgsCount(1), instrument.WithArgType(0, "*Request")),
+ Interceptor: "Interceptor",
+ },
+ }
}
-func registerFramework(ins instrument.Instrument) {
- instruments = append(instruments, ins)
+func (i *Instrument) FS() *embed.FS {
+ return &fs
}
diff --git a/plugins/ginv2/intercepter.go b/plugins/http/intercepter.go
similarity index 55%
copy from plugins/ginv2/intercepter.go
copy to plugins/http/intercepter.go
index 49c5412..8cf09ec 100644
--- a/plugins/ginv2/intercepter.go
+++ b/plugins/http/intercepter.go
@@ -15,29 +15,28 @@
// specific language governing permissions and limitations
// under the License.
-package ginv2
+package http
import (
"fmt"
-
- "github.com/gin-gonic/gin"
+ "net/http"
"github.com/apache/skywalking-go/plugins/core/operator"
"github.com/apache/skywalking-go/plugins/core/tracing"
)
-type HTTPInterceptor struct {
+type Interceptor struct {
}
-func (h *HTTPInterceptor) BeforeInvoke(invocation *operator.Invocation) error {
- context := invocation.Args[0].(*gin.Context)
- s, err := tracing.CreateEntrySpan(
- fmt.Sprintf("%s:%s", context.Request.Method, context.Request.RequestURI), func(headerKey string) (string, error) {
- return context.Request.Header.Get(headerKey), nil
- },
- tracing.WithLayer(tracing.SpanLayerHTTP),
- tracing.WithTag(tracing.TagHTTPMethod, context.Request.Method),
- tracing.WithTag(tracing.TagURL, context.Request.Host+context.Request.URL.Path))
+func (h *Interceptor) BeforeInvoke(invocation *operator.Invocation) error {
+ request := invocation.Args[0].(*http.Request)
+ s, err := tracing.CreateExitSpan(fmt.Sprintf("%s:%s", request.Method, request.URL.Path), request.Host, func(headerKey, headerValue string) error {
+ request.Header.Add(headerKey, headerValue)
+ return nil
+ }, tracing.WithLayer(tracing.SpanLayerHTTP),
+ tracing.WithTag(tracing.TagHTTPMethod, request.Method),
+ tracing.WithTag(tracing.TagURL, request.Host+request.URL.Path),
+ tracing.WithComponent(5005))
if err != nil {
return err
}
@@ -45,15 +44,22 @@ func (h *HTTPInterceptor) BeforeInvoke(invocation *operator.Invocation) error {
return nil
}
-func (h *HTTPInterceptor) AfterInvoke(invocation *operator.Invocation, result ...interface{}) error {
+func (h *Interceptor) AfterInvoke(invocation *operator.Invocation, result ...interface{}) error {
if invocation.Context == nil {
return nil
}
- context := invocation.Args[0].(*gin.Context)
span := invocation.Context.(tracing.Span)
- span.Tag(tracing.TagStatusCode, fmt.Sprintf("%d", context.Writer.Status()))
- if len(context.Errors) > 0 {
- span.Error(context.Errors.String())
+ res0 := result[0]
+ res1 := result[1]
+ if res0 != nil {
+ resp := res0.(*http.Response)
+ span.Tag(tracing.TagStatusCode, fmt.Sprintf("%d", resp.StatusCode))
+ }
+ if res1 != nil {
+ err := result[1].(error)
+ if err != nil {
+ span.Error(err.Error())
+ }
}
span.End()
return nil
diff --git a/tools/go-agent/go.mod b/tools/go-agent/go.mod
index 0ded49d..54b91d5 100644
--- a/tools/go-agent/go.mod
+++ b/tools/go-agent/go.mod
@@ -5,6 +5,7 @@ go 1.18
require (
github.com/apache/skywalking-go/plugins/core v0.0.0-20230414024435-7b292984eb80
github.com/apache/skywalking-go/plugins/ginv2 v0.0.0-20230412041451-ba963278b31e
+ github.com/apache/skywalking-go/plugins/http v0.0.0-20230412041451-ba963278b31e
github.com/dave/dst v0.27.2
github.com/sirupsen/logrus v1.9.0
golang.org/x/text v0.8.0
@@ -50,3 +51,4 @@ replace github.com/apache/skywalking-go => ../../
replace github.com/apache/skywalking-go/plugins/core => ../../plugins/core
replace github.com/apache/skywalking-go/plugins/ginv2 => ../../plugins/ginv2
+replace github.com/apache/skywalking-go/plugins/http => ../../plugins/http
diff --git a/tools/go-agent/instrument/plugins/enhance_method.go b/tools/go-agent/instrument/plugins/enhance_method.go
index ab64320..f8484fe 100644
--- a/tools/go-agent/instrument/plugins/enhance_method.go
+++ b/tools/go-agent/instrument/plugins/enhance_method.go
@@ -50,9 +50,9 @@ type MethodEnhance struct {
InterceptorGeneratedName string
InterceptorVarName string
- Parameters []*tools.ParameterInfo
- Recvs []*tools.ParameterInfo
- Results []*tools.ParameterInfo
+ Parameters []*tools.PackagedParameterInfo
+ Recvs []*tools.PackagedParameterInfo
+ Results []*tools.PackagedParameterInfo
FuncID string
AdapterPreFuncName string
@@ -64,18 +64,19 @@ type MethodEnhance struct {
func NewMethodEnhance(inst instrument.Instrument, matcher *instrument.Point, f *dst.FuncDecl, path string) *MethodEnhance {
fullPackage := filepath.Join(inst.BasePackage(), matcher.PackagePath)
+ pkgName := filepath.Base(fullPackage)
enhance := &MethodEnhance{
funcDecl: f,
path: path,
fullPackage: fullPackage,
- packageName: filepath.Base(fullPackage),
+ packageName: pkgName,
InstrumentName: inst.Name(),
InterceptorDefineName: matcher.Interceptor,
- Parameters: tools.EnhanceParameterNames(f.Type.Params, false),
- Results: tools.EnhanceParameterNames(f.Type.Results, true),
+ Parameters: tools.EnhanceParameterNamesWithPackagePrefix(pkgName, f.Type.Params, false),
+ Results: tools.EnhanceParameterNamesWithPackagePrefix(pkgName, f.Type.Results, true),
}
if f.Recv != nil {
- enhance.Recvs = tools.EnhanceParameterNames(f.Recv, false)
+ enhance.Recvs = tools.EnhanceParameterNamesWithPackagePrefix(pkgName, f.Recv, false)
}
enhance.FuncID = buildFrameworkFuncID(filepath.Join(inst.BasePackage(), matcher.PackagePath), f)
@@ -126,19 +127,19 @@ func (m *MethodEnhance) BuildForAdapter() []dst.Decl {
for i, recv := range m.Recvs {
preFunc.Type.Params.List = append(preFunc.Type.Params.List, &dst.Field{
Names: []*dst.Ident{dst.NewIdent(fmt.Sprintf("recv_%d", i))},
- Type: &dst.StarExpr{X: m.addPackagePrefixForArgsAndClone(m.packageName, recv.Type)},
+ Type: &dst.StarExpr{X: recv.PackagedType()},
})
}
for i, parameter := range m.Parameters {
preFunc.Type.Params.List = append(preFunc.Type.Params.List, &dst.Field{
Names: []*dst.Ident{dst.NewIdent(fmt.Sprintf("param_%d", i))},
- Type: &dst.StarExpr{X: m.addPackagePrefixForArgsAndClone(m.packageName, parameter.Type)},
+ Type: &dst.StarExpr{X: parameter.PackagedType()},
})
}
for i, result := range m.Results {
preFunc.Type.Results.List = append(preFunc.Type.Results.List, &dst.Field{
Names: []*dst.Ident{dst.NewIdent(fmt.Sprintf("ret_%d", i))},
- Type: &dst.StarExpr{X: m.addPackagePrefixForArgsAndClone(m.packageName, result.Type)},
+ Type: result.PackagedType(),
})
}
preFunc.Type.Results.List = append(preFunc.Type.Results.List, &dst.Field{
@@ -189,7 +190,7 @@ func (m *MethodEnhance) BuildForAdapter() []dst.Decl {
func (m *MethodEnhance) addPackagePrefixForArgsAndClone(pkg string, tp dst.Expr) dst.Expr {
switch t := tp.(type) {
case *dst.Ident:
- if rewrite.IsBasicDataType(t.Name) {
+ if tools.IsBasicDataType(t.Name) {
return dst.Clone(tp).(dst.Expr)
}
// otherwise, add the package prefix
@@ -198,8 +199,9 @@ func (m *MethodEnhance) addPackagePrefixForArgsAndClone(pkg string, tp dst.Expr)
Sel: dst.NewIdent(t.Name),
}
case *dst.StarExpr:
- t.X = m.addPackagePrefixForArgsAndClone(pkg, t.X)
- return t
+ expr := dst.Clone(tp).(*dst.StarExpr)
+ expr.X = m.addPackagePrefixForArgsAndClone(pkg, t.X)
+ return expr
default:
return dst.Clone(tp).(dst.Expr)
}
diff --git a/tools/go-agent/instrument/plugins/instrument.go b/tools/go-agent/instrument/plugins/instrument.go
index de1ac90..75925ef 100644
--- a/tools/go-agent/instrument/plugins/instrument.go
+++ b/tools/go-agent/instrument/plugins/instrument.go
@@ -68,7 +68,7 @@ func (i *Instrument) CouldHandle(opts *api.CompileOptions) bool {
continue
}
// check the version of the framework could handler
- version, err := i.tryToFindThePluginVersion(opts, ins.BasePackage())
+ version, err := i.tryToFindThePluginVersion(opts, ins)
if err != nil {
logrus.Warnf("ignore the plugin %s, because: %s", ins.Name(), err)
continue
@@ -362,21 +362,25 @@ func (i *Instrument) validateMethodInsMatch(matcher *instrument.EnhanceMatcher,
return true
}
-func (i *Instrument) tryToFindThePluginVersion(opts *api.CompileOptions, pkg string) (string, error) {
+func (i *Instrument) tryToFindThePluginVersion(opts *api.CompileOptions, ins instrument.Instrument) (string, error) {
for _, arg := range opts.AllArgs {
// find the go file
if !strings.HasSuffix(arg, ".go") {
continue
}
+ basePkg := ins.BasePackage()
- parts := strings.SplitN(arg, pkg, 2)
+ parts := strings.SplitN(arg, basePkg, 2)
// example: github.com/gin-gonic/gin@1.1.1/gin.go
- if len(parts) != 2 || !strings.HasPrefix(parts[1], "@") {
- return "", fmt.Errorf("could not found the go version of the package %s, go file path: %s", pkg, arg)
+ if len(parts) != 2 {
+ return "", fmt.Errorf("could not found the go version of the package %s, go file path: %s", basePkg, arg)
+ }
+ if !strings.HasPrefix(parts[1], "@") {
+ return "", nil
}
firstDir := strings.Index(parts[1], "/")
if firstDir == -1 {
- return "", fmt.Errorf("could not found the first directory index for package: %s, go file path: %s", pkg, arg)
+ return "", fmt.Errorf("could not found the first directory index for package: %s, go file path: %s", basePkg, arg)
}
return parts[1][1:firstDir], nil
}
diff --git a/tools/go-agent/instrument/plugins/register.go b/tools/go-agent/instrument/plugins/register.go
index 6caf205..d7c892d 100644
--- a/tools/go-agent/instrument/plugins/register.go
+++ b/tools/go-agent/instrument/plugins/register.go
@@ -20,6 +20,7 @@ package plugins
import (
"github.com/apache/skywalking-go/plugins/core/instrument"
"github.com/apache/skywalking-go/plugins/ginv2"
+ "github.com/apache/skywalking-go/plugins/http"
)
var instruments = make([]instrument.Instrument, 0)
@@ -27,6 +28,7 @@ var instruments = make([]instrument.Instrument, 0)
func init() {
// register the plugins instrument
registerFramework(ginv2.NewInstrument())
+ registerFramework(http.NewInstrument())
}
func registerFramework(ins instrument.Instrument) {
diff --git a/tools/go-agent/instrument/plugins/rewrite/context.go b/tools/go-agent/instrument/plugins/rewrite/context.go
index 8665c08..075a575 100644
--- a/tools/go-agent/instrument/plugins/rewrite/context.go
+++ b/tools/go-agent/instrument/plugins/rewrite/context.go
@@ -26,6 +26,8 @@ import (
"golang.org/x/text/cases"
"golang.org/x/text/language"
+
+ "github.com/apache/skywalking-go/tools/go-agent/tools"
)
var GenerateMethodPrefix = "_skywalking_enhance_"
@@ -208,7 +210,7 @@ func (c *Context) enhanceTypeNameWhenRewrite(fieldType dst.Expr, parent dst.Node
}
func (c *Context) typeIsBasicTypeValueOrEnhanceName(name string) bool {
- if strings.HasPrefix(name, OperatePrefix) || strings.HasPrefix(name, GenerateMethodPrefix) || IsBasicDataType(name) ||
+ if strings.HasPrefix(name, OperatePrefix) || strings.HasPrefix(name, GenerateMethodPrefix) || tools.IsBasicDataType(name) ||
name == "nil" || name == "true" || name == "false" {
return true
}
@@ -223,14 +225,6 @@ func (c *Context) callIsBasicNamesOrEnhanceName(name string) bool {
name == "make" || name == "recover" || name == "len"
}
-// nolint
-func IsBasicDataType(name string) bool {
- return name == "bool" || name == "int8" || name == "int16" || name == "int32" || name == "int64" || name == "uint8" ||
- name == "uint16" || name == "uint32" || name == "uint64" || name == "int" || name == "uint" || name == "uintptr" ||
- name == "float32" || name == "float64" || name == "complex64" || name == "complex128" || name == "string" || name == "error" ||
- name == "interface{}" || name == "_"
-}
-
func (r *rewriteImportInfo) generateStaticMethod(name string) *dst.Ident {
if r.ctx.typeIsBasicTypeValueOrEnhanceName(name) {
return dst.NewIdent(name)
diff --git a/tools/go-agent/instrument/plugins/rewrite/func.go b/tools/go-agent/instrument/plugins/rewrite/func.go
index 5b48c85..14fedc9 100644
--- a/tools/go-agent/instrument/plugins/rewrite/func.go
+++ b/tools/go-agent/instrument/plugins/rewrite/func.go
@@ -181,6 +181,8 @@ func (c *Context) rewriteVarIfExistingMapping(exp dst.Expr) bool {
for _, arg := range n.Args {
c.rewriteVarIfExistingMapping(arg)
}
+ case *dst.StarExpr:
+ c.enhanceTypeNameWhenRewrite(n.X, n, -1)
}
return false
}
diff --git a/tools/go-agent/instrument/plugins/templates/method_inserts.tmpl b/tools/go-agent/instrument/plugins/templates/method_inserts.tmpl
index 52454d5..770b53c 100644
--- a/tools/go-agent/instrument/plugins/templates/method_inserts.tmpl
+++ b/tools/go-agent/instrument/plugins/templates/method_inserts.tmpl
@@ -4,8 +4,8 @@ if {{ range $index, $value := .Results -}}
{{ if ne $index 0}},{{ end }}&{{$value.Name -}},
{{- end -}}{{ range $index, $value := .Parameters -}}
{{ if ne $index 0}},{{ end }}&{{$value.Name -}}
-{{- end -}}); !_sw_keep { return {{- range $index, $value := .Results -}}
- _sw_inv_res_{{$index -}},
+{{- end -}}); !_sw_keep { return {{ range $index, $value := .Results -}}
+ {{ if ne $index 0}},{{ end }}_sw_inv_res_{{$index -}}
{{- end -}} } else { defer func() { {{.AdapterPostFuncName}}(_sw_invocation{{- range $index, $value := .Results -}}
-,{{- $value.Name -}}
+,&{{- $value.Name -}}
{{- end -}})}() };
\ No newline at end of file
diff --git a/tools/go-agent/instrument/plugins/templates/method_intercept_after.tmpl b/tools/go-agent/instrument/plugins/templates/method_intercept_after.tmpl
index 8b20ffa..0967184 100644
--- a/tools/go-agent/instrument/plugins/templates/method_intercept_after.tmpl
+++ b/tools/go-agent/instrument/plugins/templates/method_intercept_after.tmpl
@@ -9,7 +9,7 @@ defer func() {
// real invoke
if err := {{.InterceptorVarName}}.AfterInvoke(invocation{{ range $index, $value := .Results -}}
- , ret_$index
+ , *ret_{{$index}}
{{- end}}); err != nil {
// using go2sky log error
log.Warnf("execute interceptor after invoke error, instrument name: %s, interceptor name: %s, function ID: %s, error: %v",
diff --git a/tools/go-agent/instrument/plugins/templates/method_intercept_before.tmpl b/tools/go-agent/instrument/plugins/templates/method_intercept_before.tmpl
index 2d67031..8d6e27a 100644
--- a/tools/go-agent/instrument/plugins/templates/method_intercept_before.tmpl
+++ b/tools/go-agent/instrument/plugins/templates/method_intercept_before.tmpl
@@ -20,14 +20,14 @@ if err := {{.InterceptorVarName}}.BeforeInvoke(invocation); err != nil {
log.Warnf("execute interceptor before invoke error, instrument name: %s, interceptor name: %s, function ID: %s, error: %v",
"{{.InstrumentName}}", "{{.InterceptorDefineName}}", "{{.FuncID}}", err)
return {{ range $index, $value := .Results -}}
-$value.DefaultValueAsString,
+{{$value.DefaultValueAsString}},
{{- end}}invocation, true
}
if (invocation.Continue) {
return {{ range $index, $value := .Results -}}
- invocation.Return[$index],
+ (invocation.Return[{{$index}}]).({{$value.PackagedTypeName}}),
{{- end}}invocation, false
}
return {{ range $index, $value := .Results -}}
-{{- if ne .index 0}}, {{end}}$value.DefaultValueAsString
+{{- if ne $index 0}}, {{end}}{{$value.DefaultValueAsString }}
{{- end}}{{if .Results}}, {{- end}}invocation, true
\ No newline at end of file
diff --git a/tools/go-agent/tools/enhancement.go b/tools/go-agent/tools/enhancement.go
index dca0137..e79f879 100644
--- a/tools/go-agent/tools/enhancement.go
+++ b/tools/go-agent/tools/enhancement.go
@@ -25,10 +25,18 @@ import (
"github.com/dave/dst/decorator"
)
+var interfaceName = "interface{}"
+
type ParameterInfo struct {
Name string
Type dst.Expr
DefaultValueAsString string
+ TypeName string
+}
+
+type PackagedParameterInfo struct {
+ ParameterInfo
+ PackageName string
}
// EnhanceParameterNames enhance the parameter names if they are missing
@@ -62,6 +70,15 @@ func EnhanceParameterNames(fields *dst.FieldList, isResult bool) []*ParameterInf
return result
}
+func EnhanceParameterNamesWithPackagePrefix(pkg string, fields *dst.FieldList, isResult bool) []*PackagedParameterInfo {
+ params := EnhanceParameterNames(fields, isResult)
+ result := make([]*PackagedParameterInfo, 0)
+ for _, p := range params {
+ result = append(result, &PackagedParameterInfo{ParameterInfo: *p, PackageName: pkg})
+ }
+ return result
+}
+
func GoStringToStats(goString string) []dst.Stmt {
parsed, err := decorator.Parse(fmt.Sprintf(`
package main
@@ -92,8 +109,9 @@ func InsertStmtsBeforeBody(body *dst.BlockStmt, tmpl string, data interface{}) {
func newParameterInfo(name string, tp dst.Expr) *ParameterInfo {
result := &ParameterInfo{
- Name: name,
- Type: tp,
+ Name: name,
+ Type: tp,
+ TypeName: generateTypeNameByExp(tp),
}
var defaultNil = "nil"
switch n := tp.(type) {
@@ -111,3 +129,50 @@ func newParameterInfo(name string, tp dst.Expr) *ParameterInfo {
return result
}
+
+func (p *PackagedParameterInfo) PackagedType() dst.Expr {
+ return addPackagePrefixForArgsAndClone(p.PackageName, p.Type)
+}
+
+func (p *PackagedParameterInfo) PackagedTypeName() string {
+ return generateTypeNameByExp(p.PackagedType())
+}
+
+func generateTypeNameByExp(exp dst.Expr) string {
+ var data string
+ switch n := exp.(type) {
+ case *dst.StarExpr:
+ data = "*" + generateTypeNameByExp(n.X)
+ case *dst.TypeAssertExpr:
+ data = generateTypeNameByExp(n.X)
+ case *dst.InterfaceType:
+ data = interfaceName
+ case *dst.Ident:
+ data = n.Name
+ case *dst.SelectorExpr:
+ data = generateTypeNameByExp(n.X) + "." + generateTypeNameByExp(n.Sel)
+ default:
+ return ""
+ }
+ return data
+}
+
+func addPackagePrefixForArgsAndClone(pkg string, tp dst.Expr) dst.Expr {
+ switch t := tp.(type) {
+ case *dst.Ident:
+ if IsBasicDataType(t.Name) {
+ return dst.Clone(tp).(dst.Expr)
+ }
+ // otherwise, add the package prefix
+ return &dst.SelectorExpr{
+ X: dst.NewIdent(pkg),
+ Sel: dst.NewIdent(t.Name),
+ }
+ case *dst.StarExpr:
+ expr := dst.Clone(tp).(*dst.StarExpr)
+ expr.X = addPackagePrefixForArgsAndClone(pkg, t.X)
+ return expr
+ default:
+ return dst.Clone(tp).(dst.Expr)
+ }
+}
diff --git a/tools/go-agent/instrument/plugins/register.go b/tools/go-agent/tools/types.go
similarity index 63%
copy from tools/go-agent/instrument/plugins/register.go
copy to tools/go-agent/tools/types.go
index 6caf205..664ffe0 100644
--- a/tools/go-agent/instrument/plugins/register.go
+++ b/tools/go-agent/tools/types.go
@@ -15,20 +15,12 @@
// specific language governing permissions and limitations
// under the License.
-package plugins
+package tools
-import (
- "github.com/apache/skywalking-go/plugins/core/instrument"
- "github.com/apache/skywalking-go/plugins/ginv2"
-)
-
-var instruments = make([]instrument.Instrument, 0)
-
-func init() {
- // register the plugins instrument
- registerFramework(ginv2.NewInstrument())
-}
-
-func registerFramework(ins instrument.Instrument) {
- instruments = append(instruments, ins)
+// nolint
+func IsBasicDataType(name string) bool {
+ return name == "bool" || name == "int8" || name == "int16" || name == "int32" || name == "int64" || name == "uint8" ||
+ name == "uint16" || name == "uint32" || name == "uint64" || name == "int" || name == "uint" || name == "uintptr" ||
+ name == "float32" || name == "float64" || name == "complex64" || name == "complex128" || name == "string" || name == "error" ||
+ name == "interface{}" || name == "_"
}