From e7d5027f52815c90d2fec73e85b4ef5d8534d884 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Fri, 25 Oct 2024 12:07:44 +0200 Subject: [PATCH 01/44] initialize collector reporter --- go.mod | 21 ++-- go.sum | 76 +++++++++++--- reporter/collector_reporter.go | 147 ++++++++++++++++++++++++++++ reporter/collector_reporter_test.go | 51 ++++++++++ 4 files changed, 277 insertions(+), 18 deletions(-) create mode 100644 reporter/collector_reporter.go create mode 100644 reporter/collector_reporter_test.go diff --git a/go.mod b/go.mod index d94fc264..35ae4bd7 100644 --- a/go.mod +++ b/go.mod @@ -19,13 +19,14 @@ require ( github.com/stretchr/testify v1.9.0 github.com/tklauser/numcpus v0.8.0 github.com/zeebo/xxh3 v1.0.2 + go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0 go.opentelemetry.io/otel v1.30.0 go.opentelemetry.io/proto/otlp v1.3.1 golang.org/x/arch v0.10.0 golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 golang.org/x/sync v0.8.0 golang.org/x/sys v0.26.0 - google.golang.org/grpc v1.66.2 + google.golang.org/grpc v1.67.1 ) require ( @@ -46,17 +47,25 @@ require ( github.com/aws/aws-sdk-go-v2/service/sts v1.30.8 // indirect github.com/aws/smithy-go v1.20.4 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/gogo/protobuf v1.3.2 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect github.com/josharian/native v1.1.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.3 // indirect github.com/mdlayher/netlink v1.7.2 // indirect github.com/mdlayher/socket v0.4.1 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - golang.org/x/net v0.26.0 // indirect - golang.org/x/text v0.16.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect - google.golang.org/protobuf v1.34.1 // indirect + go.opentelemetry.io/collector/consumer v0.112.0 // indirect + go.opentelemetry.io/collector/pdata v1.18.0 // indirect + go.opentelemetry.io/collector/pdata/pprofile v0.112.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/text v0.17.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect + google.golang.org/protobuf v1.35.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 10c61a9e..9ea94a43 100644 --- a/go.sum +++ b/go.sum @@ -51,8 +51,11 @@ github.com/elastic/go-perf v0.0.0-20241016160959-1342461adb4a h1:ymmtaN4bVCmKKeu github.com/elastic/go-perf v0.0.0-20241016160959-1342461adb4a/go.mod h1:Nt+pnRYvf0POC+7pXsrv8ubsEOSsaipJP0zlz1Ms1RM= github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0= @@ -63,6 +66,10 @@ github.com/jsimonetti/rtnetlink v1.4.2 h1:Df9w9TZ3npHTyDn0Ev9e1uzmN2odmXd0QX+J5G github.com/jsimonetti/rtnetlink v1.4.2/go.mod h1:92s6LJdE+1iOrw+F2/RO7LYI2Qd8pPpFNNUYW06gcoM= github.com/jsimonetti/rtnetlink/v2 v2.0.1 h1:xda7qaHDSVOsADNouv7ukSuicKZO7GgVUCXxpaIEIlM= github.com/jsimonetti/rtnetlink/v2 v2.0.1/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsTKP1pqKLUTVCvToE= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= @@ -77,6 +84,11 @@ github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/peterbourgon/ff/v3 v3.4.0 h1:QBvM/rizZM1cB0p0lGMdmR7HxZeI/ZrBWB4DqLkMUBc= github.com/peterbourgon/ff/v3 v3.4.0/go.mod h1:zjJVUhx+twciwfDl0zBcFzl4dW8axCRyXE/eKY9RztQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -86,41 +98,81 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY= github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +go.opentelemetry.io/collector/consumer v0.112.0 h1:tfO4FpuQ8MsD7AxgslC3tRNVYjd9Xkus34BOExsG4fM= +go.opentelemetry.io/collector/consumer v0.112.0/go.mod h1:ZKSeGvXvaofIlvPrWlARKQpONOmuw6R/yifgYCWHKRw= +go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0 h1:ym+QxemlbWwfMSUto1hRTfcZeYbj2q8FpMzjk8O+X60= +go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0/go.mod h1:4PjDUpURFh85R6NLEHrEf/uZjpk4LAYmmOrqu+iZsyE= +go.opentelemetry.io/collector/pdata v1.18.0 h1:/yg2rO2dxqDM2p6GutsMCxXN6sKlXwyIz/ZYyUPONBg= +go.opentelemetry.io/collector/pdata v1.18.0/go.mod h1:Ox1YVLe87cZDB/TL30i4SUz1cA5s6AM6SpFMfY61ICs= +go.opentelemetry.io/collector/pdata/pprofile v0.112.0 h1:t+LYorcMqZ3sDz5/jp3xU2l5lIhIXuIOOGO4Ef9CG2c= +go.opentelemetry.io/collector/pdata/pprofile v0.112.0/go.mod h1:F2aTCoDzIaxEUK1g92LZvMwradySFMo3ZsAnBIpOdUg= go.opentelemetry.io/otel v1.30.0 h1:F2t8sK4qf1fAmY9ua4ohFS/K+FUuOPemHUIXHtktrts= go.opentelemetry.io/otel v1.30.0/go.mod h1:tFw4Br9b7fOS+uEao81PJjVMjW/5fvNCbpsDIXqP0pc= go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= -golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= -golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= -golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= -google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 h1:+rdxYoE3E5htTEWIe15GlN6IfvbURM//Jt0mmkmm6ZU= -google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117/go.mod h1:OimBR/bc1wPO9iV4NC2bpyjy3VnAwZh5EBPQdtaE5oo= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= -google.golang.org/grpc v1.66.2 h1:3QdXkuq3Bkh7w+ywLdLvM56cmGvQHUMZpiCzt6Rqaoo= -google.golang.org/grpc v1.66.2/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= -google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= -google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142 h1:wKguEg1hsxI2/L3hUYrpo1RVi48K+uTyzKqprwLXsb8= +google.golang.org/genproto/googleapis/api v0.0.0-20240814211410-ddb44dafa142/go.mod h1:d6be+8HhtEtucleCbxpPW9PA9XwISACu8nvpPqF0BVo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= +google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E= +google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go new file mode 100644 index 00000000..26d63f44 --- /dev/null +++ b/reporter/collector_reporter.go @@ -0,0 +1,147 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" + +import ( + "context" + "time" + + lru "github.com/elastic/go-freelru" + "go.opentelemetry.io/collector/consumer/consumerprofiles" + "go.opentelemetry.io/collector/pdata/pprofile" + + "go.opentelemetry.io/ebpf-profiler/libpf" + "go.opentelemetry.io/ebpf-profiler/libpf/xsync" +) + +// Assert that we implement the full Reporter interface. +var _ Reporter = (*CollectorReporter)(nil) + +// OTLPReporter receives and transforms information to be Collector Collector compliant. +type CollectorReporter struct { + nextConsumer consumerprofiles.Profiles + + // hostmetadata stores metadata that is sent out with every request. + hostmetadata *lru.SyncedLRU[string, string] + + // executables stores metadata for executables. + executables *lru.SyncedLRU[libpf.FileID, execInfo] + + // frames maps frame information to its source location. + frames *lru.SyncedLRU[libpf.FileID, *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]] +} + +// NewCollector builds a new CollectorReporter +func NewCollector(nextConsumer consumerprofiles.Profiles) *CollectorReporter { + return &CollectorReporter{ + nextConsumer: nextConsumer, + } +} + +// ExecutableMetadata accepts a fileID with the corresponding filename +// and caches this information. +func (r *CollectorReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { + r.executables.Add(args.FileID, execInfo{ + fileName: args.FileName, + gnuBuildID: args.GnuBuildID, + }) +} + +// FrameKnown return true if the metadata of the Frame specified by frameID is +// cached in the reporter. +func (r *CollectorReporter) FrameKnown(frameID libpf.FrameID) bool { + known := false + if frameMapLock, exists := r.frames.Get(frameID.FileID()); exists { + frameMap := frameMapLock.RLock() + defer frameMapLock.RUnlock(&frameMap) + _, known = (*frameMap)[frameID.AddressOrLine()] + } + return known +} + +// FrameMetadata accepts metadata associated with a frame and caches this information. +func (r *CollectorReporter) FrameMetadata(args *FrameMetadataArgs) { + fileID := args.FrameID.FileID() + addressOrLine := args.FrameID.AddressOrLine() + + if frameMapLock, exists := r.frames.Get(fileID); exists { + frameMap := frameMapLock.WLock() + defer frameMapLock.WUnlock(&frameMap) + + sourceFile := args.SourceFile + if sourceFile == "" { + // The new SourceFile may be empty, and we don't want to overwrite + // an existing filePath with it. + if s, exists := (*frameMap)[addressOrLine]; exists { + sourceFile = s.filePath + } + } + + (*frameMap)[addressOrLine] = sourceInfo{ + lineNumber: args.SourceLine, + filePath: sourceFile, + functionOffset: args.FunctionOffset, + functionName: args.FunctionName, + } + return + } + + v := make(map[libpf.AddressOrLineno]sourceInfo) + v[addressOrLine] = sourceInfo{ + lineNumber: args.SourceLine, + filePath: args.SourceFile, + functionOffset: args.FunctionOffset, + functionName: args.FunctionName, + } + mu := xsync.NewRWMutex(v) + r.frames.Add(fileID, &mu) +} + +// GetMetrics returns internal metrics of CollectorReporter. +func (r *CollectorReporter) GetMetrics() Metrics { + return Metrics{} +} + +// ReportFramesForTrace is a NOP for CollectorReporter. +func (r *CollectorReporter) ReportFramesForTrace(_ *libpf.Trace) {} + +// ReportCountForTrace is a NOP for CollectorReporter. +func (r *CollectorReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { +} + +// ReportMetrics is a NOP for CollectorReporter. +func (r *CollectorReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} + +// Stop is a NOP for CollectorReporter +func (r *CollectorReporter) Stop() { +} + +// ReportHostMetadata enqueues host metadata. +func (r *CollectorReporter) ReportHostMetadata(metadataMap map[string]string) { + for k, v := range metadataMap { + r.hostmetadata.Add(k, v) + } +} + +func (r *CollectorReporter) SupportsReportTraceEvent() bool { return true } + +// ReportHostMetadataBlocking enqueues host metadata. +func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, + metadataMap map[string]string, _ int, _ time.Duration) error { + r.ReportHostMetadata(metadataMap) + return nil +} + +// ReportTraceEvent enqueues reported trace events for the Collector reporter. +func (r *CollectorReporter) ReportTraceEvent(_ *libpf.Trace, _ *TraceEventMeta) { + // TODO: get a context provided by the trace handler ? + ctx := context.Background() + // TODO: build pdata + data := pprofile.Profiles{} + + if r.nextConsumer != nil { + // TODO: handle errors in trace handler ? + _ = r.nextConsumer.ConsumeProfiles(ctx, data) + } +} diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go new file mode 100644 index 00000000..6f3fd3d5 --- /dev/null +++ b/reporter/collector_reporter_test.go @@ -0,0 +1,51 @@ +package reporter + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/consumer/consumerprofiles" + "go.opentelemetry.io/collector/pdata/pprofile" + + "go.opentelemetry.io/ebpf-profiler/libpf" +) + +func TestCollectorReporterReportTraceEvent(t *testing.T) { + for _, tt := range []struct { + name string + nextFn consumerprofiles.ConsumeProfilesFunc + trace *libpf.Trace + meta *TraceEventMeta + }{ + { + name: "with no next consumer", + }, + { + name: "with a next consumer that succeeds", + nextFn: func(_ context.Context, _ pprofile.Profiles) error { + return nil + }, + }, + { + name: "with a next consumer that returns an error", + nextFn: func(_ context.Context, _ pprofile.Profiles) error { + return errors.New("next consumer failed") + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + var next consumerprofiles.Profiles + + if tt.nextFn != nil { + var err error + next, err = consumerprofiles.NewProfiles(tt.nextFn) + require.NoError(t, err) + } + + r := NewCollector(next) + r.ReportTraceEvent(tt.trace, tt.meta) + }) + } +} From 368a1e2514fe2dda152142e98333b3a39480ab1f Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Fri, 25 Oct 2024 12:16:26 +0200 Subject: [PATCH 02/44] run make legal --- LICENSES/github.com/gogo/protobuf/LICENSE | 35 +++ LICENSES/github.com/json-iterator/go/LICENSE | 21 ++ .../github.com/modern-go/concurrent/LICENSE | 201 +++++++++++++++++ .../github.com/modern-go/reflect2/LICENSE | 201 +++++++++++++++++ .../collector/consumer/LICENSE | 202 ++++++++++++++++++ .../consumer/consumerprofiles/LICENSE | 202 ++++++++++++++++++ .../collector/pdata/LICENSE | 202 ++++++++++++++++++ .../collector/pdata/pprofile/LICENSE | 202 ++++++++++++++++++ LICENSES/go.uber.org/multierr/LICENSE.txt | 19 ++ LICENSES/golang.org/x/net/LICENSE | 4 +- LICENSES/golang.org/x/text/LICENSE | 4 +- 11 files changed, 1289 insertions(+), 4 deletions(-) create mode 100644 LICENSES/github.com/gogo/protobuf/LICENSE create mode 100644 LICENSES/github.com/json-iterator/go/LICENSE create mode 100644 LICENSES/github.com/modern-go/concurrent/LICENSE create mode 100644 LICENSES/github.com/modern-go/reflect2/LICENSE create mode 100644 LICENSES/go.opentelemetry.io/collector/consumer/LICENSE create mode 100644 LICENSES/go.opentelemetry.io/collector/consumer/consumerprofiles/LICENSE create mode 100644 LICENSES/go.opentelemetry.io/collector/pdata/LICENSE create mode 100644 LICENSES/go.opentelemetry.io/collector/pdata/pprofile/LICENSE create mode 100644 LICENSES/go.uber.org/multierr/LICENSE.txt diff --git a/LICENSES/github.com/gogo/protobuf/LICENSE b/LICENSES/github.com/gogo/protobuf/LICENSE new file mode 100644 index 00000000..f57de90d --- /dev/null +++ b/LICENSES/github.com/gogo/protobuf/LICENSE @@ -0,0 +1,35 @@ +Copyright (c) 2013, The GoGo Authors. All rights reserved. + +Protocol Buffers for Go with Gadgets + +Go support for Protocol Buffers - Google's data interchange format + +Copyright 2010 The Go Authors. All rights reserved. +https://github.com/golang/protobuf + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/LICENSES/github.com/json-iterator/go/LICENSE b/LICENSES/github.com/json-iterator/go/LICENSE new file mode 100644 index 00000000..2cf4f5ab --- /dev/null +++ b/LICENSES/github.com/json-iterator/go/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 json-iterator + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/LICENSES/github.com/modern-go/concurrent/LICENSE b/LICENSES/github.com/modern-go/concurrent/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/LICENSES/github.com/modern-go/concurrent/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/github.com/modern-go/reflect2/LICENSE b/LICENSES/github.com/modern-go/reflect2/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/LICENSES/github.com/modern-go/reflect2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/go.opentelemetry.io/collector/consumer/LICENSE b/LICENSES/go.opentelemetry.io/collector/consumer/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSES/go.opentelemetry.io/collector/consumer/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/go.opentelemetry.io/collector/consumer/consumerprofiles/LICENSE b/LICENSES/go.opentelemetry.io/collector/consumer/consumerprofiles/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSES/go.opentelemetry.io/collector/consumer/consumerprofiles/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/go.opentelemetry.io/collector/pdata/LICENSE b/LICENSES/go.opentelemetry.io/collector/pdata/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSES/go.opentelemetry.io/collector/pdata/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/go.opentelemetry.io/collector/pdata/pprofile/LICENSE b/LICENSES/go.opentelemetry.io/collector/pdata/pprofile/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSES/go.opentelemetry.io/collector/pdata/pprofile/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/go.uber.org/multierr/LICENSE.txt b/LICENSES/go.uber.org/multierr/LICENSE.txt new file mode 100644 index 00000000..413e30f7 --- /dev/null +++ b/LICENSES/go.uber.org/multierr/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017-2021 Uber Technologies, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/LICENSES/golang.org/x/net/LICENSE b/LICENSES/golang.org/x/net/LICENSE index 6a66aea5..2a7cf70d 100644 --- a/LICENSES/golang.org/x/net/LICENSE +++ b/LICENSES/golang.org/x/net/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/LICENSES/golang.org/x/text/LICENSE b/LICENSES/golang.org/x/text/LICENSE index 6a66aea5..2a7cf70d 100644 --- a/LICENSES/golang.org/x/text/LICENSE +++ b/LICENSES/golang.org/x/text/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. From 4ba37c13cc7e9e07f42f0b19a09d2942f4944f21 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Fri, 25 Oct 2024 15:38:28 +0200 Subject: [PATCH 03/44] generate and pass pprofile --- reporter/collector_reporter.go | 271 ++++++++++++++++++++++++++-- reporter/collector_reporter_test.go | 19 +- 2 files changed, 273 insertions(+), 17 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 26d63f44..b1ecac0b 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -5,10 +5,14 @@ package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" import ( "context" + "maps" + "slices" "time" lru "github.com/elastic/go-freelru" + log "github.com/sirupsen/logrus" "go.opentelemetry.io/collector/consumer/consumerprofiles" + "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/ebpf-profiler/libpf" @@ -20,8 +24,12 @@ var _ Reporter = (*CollectorReporter)(nil) // OTLPReporter receives and transforms information to be Collector Collector compliant. type CollectorReporter struct { + cfg *Config nextConsumer consumerprofiles.Profiles + // stopSignal is the stop signal for shutting down all background tasks. + stopSignal chan struct{} + // hostmetadata stores metadata that is sent out with every request. hostmetadata *lru.SyncedLRU[string, string] @@ -30,13 +38,62 @@ type CollectorReporter struct { // frames maps frame information to its source location. frames *lru.SyncedLRU[libpf.FileID, *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]] + + // traceEvents stores reported trace events (trace metadata with frames and counts) + traceEvents xsync.RWMutex[map[traceAndMetaKey]*traceEvents] + + // samplesPerSecond is the number of samples per second. + samplesPerSecond int } // NewCollector builds a new CollectorReporter -func NewCollector(nextConsumer consumerprofiles.Profiles) *CollectorReporter { +func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*CollectorReporter, error) { + executables, err := lru.NewSynced[libpf.FileID, execInfo](cfg.CacheSize, libpf.FileID.Hash32) + if err != nil { + return nil, err + } + + frames, err := lru.NewSynced[libpf.FileID, + *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]](cfg.CacheSize, libpf.FileID.Hash32) + if err != nil { + return nil, err + } + + // Next step: Dynamically configure the size of this LRU. + // Currently, we use the length of the JSON array in + // hostmetadata/hostmetadata.json. + hostmetadata, err := lru.NewSynced[string, string](115, hashString) + if err != nil { + return nil, err + } + return &CollectorReporter{ + cfg: cfg, nextConsumer: nextConsumer, - } + + executables: executables, + frames: frames, + hostmetadata: hostmetadata, + traceEvents: xsync.NewRWMutex(map[traceAndMetaKey]*traceEvents{}), + }, nil +} + +func (r *CollectorReporter) Start() { + go func() { + tick := time.NewTicker(r.cfg.ReportInterval) + defer tick.Stop() + for { + select { + case <-r.stopSignal: + return + case <-tick.C: + if err := r.reportProfile(context.Background()); err != nil { + log.Errorf("Request failed: %v", err) + } + tick.Reset(libpf.AddJitter(r.cfg.ReportInterval, 0.2)) + } + } + }() } // ExecutableMetadata accepts a fileID with the corresponding filename @@ -113,8 +170,8 @@ func (r *CollectorReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ * // ReportMetrics is a NOP for CollectorReporter. func (r *CollectorReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} -// Stop is a NOP for CollectorReporter func (r *CollectorReporter) Stop() { + close(r.stopSignal) } // ReportHostMetadata enqueues host metadata. @@ -134,14 +191,204 @@ func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, } // ReportTraceEvent enqueues reported trace events for the Collector reporter. -func (r *CollectorReporter) ReportTraceEvent(_ *libpf.Trace, _ *TraceEventMeta) { - // TODO: get a context provided by the trace handler ? - ctx := context.Background() - // TODO: build pdata - data := pprofile.Profiles{} - - if r.nextConsumer != nil { - // TODO: handle errors in trace handler ? - _ = r.nextConsumer.ConsumeProfiles(ctx, data) +func (r *CollectorReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { + if r.nextConsumer == nil { + return + } + + traceEventsMap := r.traceEvents.WLock() + defer r.traceEvents.WUnlock(&traceEventsMap) + + key := traceAndMetaKey{ + hash: trace.Hash, + comm: meta.Comm, + apmServiceName: meta.APMServiceName, + } + + if events, exists := (*traceEventsMap)[key]; exists { + events.timestamps = append(events.timestamps, uint64(meta.Timestamp)) + (*traceEventsMap)[key] = events + return + } + + (*traceEventsMap)[key] = &traceEvents{ + files: trace.Files, + linenos: trace.Linenos, + frameTypes: trace.FrameTypes, + mappingStarts: trace.MappingStart, + mappingEnds: trace.MappingEnd, + mappingFileOffsets: trace.MappingFileOffsets, + timestamps: []uint64{uint64(meta.Timestamp)}, + } +} + +// getProfile returns an OTLP profile containing all collected samples up to this moment. +func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, + endTS pcommon.Timestamp) { + traceEvents := r.traceEvents.WLock() + samples := maps.Clone(*traceEvents) + clear(*traceEvents) + r.traceEvents.WUnlock(&traceEvents) + + // stringMap is a temporary helper that will build the StringTable. + // By specification, the first element should be empty. + stringMap := make(map[string]uint32) + stringMap[""] = 0 + + // funcMap is a temporary helper that will build the Function array + // in profile and make sure information is deduplicated. + funcMap := make(map[funcInfo]uint64) + funcMap[funcInfo{name: "", fileName: ""}] = 0 + + st := profile.SampleType().AppendEmpty() + st.SetType(int64(getStringMapIndex(stringMap, "samples"))) + st.SetUnit(int64(getStringMapIndex(stringMap, "count"))) + + pt := profile.PeriodType() + pt.SetType(int64(getStringMapIndex(stringMap, "cpu"))) + pt.SetUnit(int64(getStringMapIndex(stringMap, "nanoseconds"))) + profile.SetPeriod(1e9 / int64(r.samplesPerSecond)) + + locationIndex := uint64(0) + + // Temporary lookup to reference existing Mappings. + fileIDtoMapping := make(map[libpf.FileID]uint64) + + for traceKey, traceInfo := range samples { + sample := profile.Sample().AppendEmpty() + sample.SetLocationsStartIndex(locationIndex) + + sample.SetStacktraceIdIndex(getStringMapIndex(stringMap, + traceKey.hash.Base64())) + + slices.Sort(traceInfo.timestamps) + startTS = pcommon.Timestamp(traceInfo.timestamps[0]) + endTS = pcommon.Timestamp(traceInfo.timestamps[len(traceInfo.timestamps)-1]) + + sample.TimestampsUnixNano().FromRaw(traceInfo.timestamps) + sample.Value().Append(1) + + // Walk every frame of the trace. + for i := range traceInfo.frameTypes { + profile.AttributeTable().PutStr("profile.frame.type", traceInfo.frameTypes[i].String()) + + loc := profile.Location().AppendEmpty() + loc.SetAddress(uint64(traceInfo.linenos[i])) + + switch frameKind := traceInfo.frameTypes[i]; frameKind { + case libpf.NativeFrame: + // As native frames are resolved in the backend, we use Mapping to + // report these frames. + + var locationMappingIndex uint64 + if tmpMappingIndex, exists := fileIDtoMapping[traceInfo.files[i]]; exists { + locationMappingIndex = tmpMappingIndex + } else { + idx := uint64(len(fileIDtoMapping)) + fileIDtoMapping[traceInfo.files[i]] = idx + locationMappingIndex = idx + + ei, exists := r.executables.Get(traceInfo.files[i]) + + // Next step: Select a proper default value, + // if the name of the executable is not known yet. + var fileName = "UNKNOWN" + if exists { + fileName = ei.fileName + } + + profile.AttributeTable().PutStr( + "process.executable.build_id.gnu", + ei.gnuBuildID, + ) + profile.AttributeTable().PutStr( + "process.executable.build_id.profiling", + traceInfo.files[i].StringNoQuotes(), + ) + + mapping := profile.Mapping().AppendEmpty() + mapping.SetMemoryStart(uint64(traceInfo.mappingStarts[i])) + mapping.SetMemoryLimit(uint64(traceInfo.mappingEnds[i])) + mapping.SetFileOffset(traceInfo.mappingFileOffsets[i]) + mapping.SetFilename(int64(getStringMapIndex(stringMap, fileName))) + } + loc.SetMappingIndex(locationMappingIndex) + case libpf.AbortFrame: + // Next step: Figure out how the OTLP protocol + // could handle artificial frames, like AbortFrame, + // that are not originated from a native or interpreted + // program. + default: + // Store interpreted frame information as a Line message: + line := loc.Line().AppendEmpty() + + fileIDInfoLock, exists := r.frames.Get(traceInfo.files[i]) + if !exists { + // At this point, we do not have enough information for the frame. + // Therefore, we report a dummy entry and use the interpreter as filename. + line.SetFunctionIndex(createFunctionEntry(funcMap, + "UNREPORTED", frameKind.String())) + } else { + fileIDInfo := fileIDInfoLock.RLock() + if si, exists := (*fileIDInfo)[traceInfo.linenos[i]]; exists { + line.SetLine(int64(si.lineNumber)) + + line.SetFunctionIndex(createFunctionEntry(funcMap, + si.functionName, si.filePath)) + } else { + // At this point, we do not have enough information for the frame. + // Therefore, we report a dummy entry and use the interpreter as filename. + // To differentiate this case from the case where no information about + // the file ID is available at all, we use a different name for reported + // function. + line.SetFunctionIndex(createFunctionEntry(funcMap, + "UNRESOLVED", frameKind.String())) + } + fileIDInfoLock.RUnlock(&fileIDInfo) + } + } + } + + sample.SetLocationsLength(uint64(len(traceInfo.frameTypes))) + locationIndex += sample.LocationsLength() + } + log.Debugf("Reporting OTLP profile with %d samples", profile.Sample().Len()) + + for v := range funcMap { + f := profile.Function().AppendEmpty() + f.SetName(int64(getStringMapIndex(stringMap, v.name))) + f.SetFilename(int64(getStringMapIndex(stringMap, v.fileName))) + } + + for v := range stringMap { + profile.StringTable().Append(v) + } + + // profile.LocationIndices is not optional, and we only write elements into + // profile.Location that at least one sample references. + for i := int64(0); i < int64(profile.Location().Len()); i++ { + profile.LocationIndices().Append(i) } + + profile.SetDuration(endTS - startTS) + profile.SetStartTime(startTS) + + return startTS, endTS +} + +// reportProfile sends a profile to the next consumer +func (r *CollectorReporter) reportProfile(ctx context.Context) error { + profiles := pprofile.NewProfiles() + rp := profiles.ResourceProfiles().AppendEmpty() + + sp := rp.ScopeProfiles().AppendEmpty() + + pc := sp.Profiles().AppendEmpty() + pc.SetProfileID(pprofile.ProfileID(mkProfileID())) + + startTS, endTS := r.setProfile(pc.Profile()) + pc.SetStartTime(startTS) + pc.SetEndTime(endTS) + + return r.nextConsumer.ConsumeProfiles(ctx, profiles) } diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index 6f3fd3d5..2445dd20 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -15,21 +15,27 @@ import ( func TestCollectorReporterReportTraceEvent(t *testing.T) { for _, tt := range []struct { name string - nextFn consumerprofiles.ConsumeProfilesFunc trace *libpf.Trace meta *TraceEventMeta + nextFn consumerprofiles.ConsumeProfilesFunc }{ { - name: "with no next consumer", + name: "with no next consumer", + trace: &libpf.Trace{}, + meta: &TraceEventMeta{}, }, { - name: "with a next consumer that succeeds", + name: "with a next consumer that succeeds", + trace: &libpf.Trace{}, + meta: &TraceEventMeta{}, nextFn: func(_ context.Context, _ pprofile.Profiles) error { return nil }, }, { - name: "with a next consumer that returns an error", + name: "with a next consumer that returns an error", + trace: &libpf.Trace{}, + meta: &TraceEventMeta{}, nextFn: func(_ context.Context, _ pprofile.Profiles) error { return errors.New("next consumer failed") }, @@ -44,7 +50,10 @@ func TestCollectorReporterReportTraceEvent(t *testing.T) { require.NoError(t, err) } - r := NewCollector(next) + r, err := NewCollector(&Config{ + CacheSize: 1, + }, next) + require.NoError(t, err) r.ReportTraceEvent(tt.trace, tt.meta) }) } From 319b4cbe73b2d3a8d3083c51a442ad13da68936a Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Fri, 25 Oct 2024 15:49:28 +0200 Subject: [PATCH 04/44] add ExecutableKnown method --- reporter/collector_reporter.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index b1ecac0b..d58d0a45 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -96,6 +96,13 @@ func (r *CollectorReporter) Start() { }() } +// ExecutableKnown returns true if the metadata of the Executable specified by fileID is +// cached in the reporter. +func (r *CollectorReporter) ExecutableKnown(fileID libpf.FileID) bool { + _, known := r.executables.Get(fileID) + return known +} + // ExecutableMetadata accepts a fileID with the corresponding filename // and caches this information. func (r *CollectorReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { From c00b6403588120b5cdb7d85c338a06941b5e8466 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 28 Oct 2024 10:02:49 +0100 Subject: [PATCH 05/44] add attributes to the attributes tables too --- reporter/collector_reporter.go | 63 +++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index d58d0a45..691c8e04 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -14,6 +14,7 @@ import ( "go.opentelemetry.io/collector/consumer/consumerprofiles" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/pprofile" + semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "go.opentelemetry.io/ebpf-profiler/libpf" "go.opentelemetry.io/ebpf-profiler/libpf/xsync" @@ -247,6 +248,11 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, funcMap := make(map[funcInfo]uint64) funcMap[funcInfo{name: "", fileName: ""}] = 0 + // attributeMap is a temporary helper that maps attribute values to + // their respective indices. + // This is to ensure that AttributeTable does not contain duplicates. + attributeMap := make(map[string]uint64) + st := profile.SampleType().AppendEmpty() st.SetType(int64(getStringMapIndex(stringMap, "samples"))) st.SetUnit(int64(getStringMapIndex(stringMap, "count"))) @@ -277,10 +283,13 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, // Walk every frame of the trace. for i := range traceInfo.frameTypes { - profile.AttributeTable().PutStr("profile.frame.type", traceInfo.frameTypes[i].String()) + frameAttributes := addPdataProfileAttributes(profile, []attrKeyValue{ + {key: "profile.frame.type", value: traceInfo.frameTypes[i].String()}, + }, attributeMap) loc := profile.Location().AppendEmpty() loc.SetAddress(uint64(traceInfo.linenos[i])) + loc.Attributes().FromRaw(frameAttributes) switch frameKind := traceInfo.frameTypes[i]; frameKind { case libpf.NativeFrame: @@ -304,20 +313,21 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, fileName = ei.fileName } - profile.AttributeTable().PutStr( - "process.executable.build_id.gnu", - ei.gnuBuildID, - ) - profile.AttributeTable().PutStr( - "process.executable.build_id.profiling", - traceInfo.files[i].StringNoQuotes(), - ) + mappingAttributes := addPdataProfileAttributes(profile, []attrKeyValue{ + // Once SemConv and its Go package is released with the new + // semantic convention for build_id, replace these hard coded + // strings. + {key: "process.executable.build_id.gnu", value: ei.gnuBuildID}, + {key: "process.executable.build_id.profiling", + value: traceInfo.files[i].StringNoQuotes()}, + }, attributeMap) mapping := profile.Mapping().AppendEmpty() mapping.SetMemoryStart(uint64(traceInfo.mappingStarts[i])) mapping.SetMemoryLimit(uint64(traceInfo.mappingEnds[i])) mapping.SetFileOffset(traceInfo.mappingFileOffsets[i]) mapping.SetFilename(int64(getStringMapIndex(stringMap, fileName))) + mapping.Attributes().FromRaw(mappingAttributes) } loc.SetMappingIndex(locationMappingIndex) case libpf.AbortFrame: @@ -356,6 +366,13 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, } } + sampleAttrs := addPdataProfileAttributes(profile, []attrKeyValue{ + {key: string(semconv.ContainerIDKey), value: traceKey.containerID}, + {key: string(semconv.ThreadNameKey), value: traceKey.comm}, + {key: string(semconv.ServiceNameKey), value: traceKey.apmServiceName}, + }, attributeMap) + sample.Attributes().FromRaw(sampleAttrs) + sample.SetLocationsLength(uint64(len(traceInfo.frameTypes))) locationIndex += sample.LocationsLength() } @@ -399,3 +416,31 @@ func (r *CollectorReporter) reportProfile(ctx context.Context) error { return r.nextConsumer.ConsumeProfiles(ctx, profiles) } + +// addPdataProfileAttributes adds attributes to Profile.attribute_table and returns +// the indices to these attributes. +func addPdataProfileAttributes(profile pprofile.Profile, + attributes []attrKeyValue, attributeMap map[string]uint64) []uint64 { + indices := make([]uint64, 0, len(attributes)) + + addAttr := func(attr attrKeyValue) { + if attr.value == "" { + return + } + attributeCompositeKey := attr.key + "_" + attr.value + if attributeIndex, exists := attributeMap[attributeCompositeKey]; exists { + indices = append(indices, attributeIndex) + return + } + newIndex := uint64(profile.AttributeTable().Len()) + indices = append(indices, newIndex) + profile.AttributeTable().PutStr(attr.key, attr.value) + attributeMap[attributeCompositeKey] = newIndex + } + + for i := range attributes { + addAttr(attributes[i]) + } + + return indices +} From 87e13db51651bae1f6cd798aaa8c2580ad7d21c2 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 28 Oct 2024 10:12:24 +0100 Subject: [PATCH 06/44] set the mapping index --- reporter/collector_reporter.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 691c8e04..6592227a 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -12,6 +12,7 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" "go.opentelemetry.io/collector/consumer/consumerprofiles" + otlpprofiles "go.opentelemetry.io/collector/pdata/internal/data/protogen/profiles/v1experimental" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/pprofile" semconv "go.opentelemetry.io/otel/semconv/v1.25.0" @@ -363,6 +364,10 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, } fileIDInfoLock.RUnlock(&fileIDInfo) } + + // To be compliant with the protocol, generate a dummy mapping entry. + loc.SetMappingIndex(getDummyPdataMappingIndex(fileIDtoMapping, stringMap, + profile, traceInfo.files[i])) } } @@ -378,6 +383,7 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, } log.Debugf("Reporting OTLP profile with %d samples", profile.Sample().Len()) + // Populate the deduplicated functions into profile. for v := range funcMap { f := profile.Function().AppendEmpty() f.SetName(int64(getStringMapIndex(stringMap, v.name))) @@ -444,3 +450,24 @@ func addPdataProfileAttributes(profile pprofile.Profile, return indices } + +// getDummyPdataMappingIndex inserts or looks up an entry for interpreted FileIDs. +func getDummyPdataMappingIndex(fileIDtoMapping map[libpf.FileID]uint64, + stringMap map[string]uint32, profile pprofile.Profile, + fileID libpf.FileID) uint64 { + var locationMappingIndex uint64 + if tmpMappingIndex, exists := fileIDtoMapping[fileID]; exists { + locationMappingIndex = tmpMappingIndex + } else { + idx := uint64(len(fileIDtoMapping)) + fileIDtoMapping[fileID] = idx + locationMappingIndex = idx + + mapping := profile.Mapping().AppendEmpty() + mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) + mapping.SetBuildID(int64(getStringMapIndex(stringMap, + fileID.StringNoQuotes()))) + mapping.SetBuildIDKind(otlpprofiles.BuildIdKind_BUILD_ID_BINARY_HASH) + } + return locationMappingIndex +} From 915301fdebc62b7a5c1fd731f1d592ceb2fe3161 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 28 Oct 2024 10:13:47 +0100 Subject: [PATCH 07/44] bring back stringMap comment --- reporter/collector_reporter.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 6592227a..d053839a 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -390,6 +390,9 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, f.SetFilename(int64(getStringMapIndex(stringMap, v.fileName))) } + // When ranging over stringMap, the order will be according to the + // hash value of the key. To get the correct order for profile.StringTable, + // put the values in stringMap, in the correct array order. for v := range stringMap { profile.StringTable().Append(v) } From 92694812a3ea8db22f6655e0411a0f00a786196e Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 28 Oct 2024 10:22:15 +0100 Subject: [PATCH 08/44] don't use private otlpprofile package --- reporter/collector_reporter.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index d053839a..6746085a 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -12,7 +12,6 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" "go.opentelemetry.io/collector/consumer/consumerprofiles" - otlpprofiles "go.opentelemetry.io/collector/pdata/internal/data/protogen/profiles/v1experimental" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/pprofile" semconv "go.opentelemetry.io/otel/semconv/v1.25.0" @@ -470,7 +469,7 @@ func getDummyPdataMappingIndex(fileIDtoMapping map[libpf.FileID]uint64, mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) mapping.SetBuildID(int64(getStringMapIndex(stringMap, fileID.StringNoQuotes()))) - mapping.SetBuildIDKind(otlpprofiles.BuildIdKind_BUILD_ID_BINARY_HASH) + mapping.SetBuildIDKind(1) } return locationMappingIndex } From 6e763c039e30828cde24d03223968df6c1262da3 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 28 Oct 2024 10:32:18 +0100 Subject: [PATCH 09/44] remove buildID and buildIDKind handling build ID kind is complicated at the moment, due to the use of internal types, and these fields are removed from the proto anyway --- reporter/collector_reporter.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 6746085a..c7943ffb 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -467,9 +467,6 @@ func getDummyPdataMappingIndex(fileIDtoMapping map[libpf.FileID]uint64, mapping := profile.Mapping().AppendEmpty() mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) - mapping.SetBuildID(int64(getStringMapIndex(stringMap, - fileID.StringNoQuotes()))) - mapping.SetBuildIDKind(1) } return locationMappingIndex } From 8a2e1661d2369629044638b5f3aca329592286a5 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 29 Oct 2024 15:01:33 +0100 Subject: [PATCH 10/44] add tests for ReportProfile --- reporter/collector_reporter.go | 17 +++- reporter/collector_reporter_test.go | 142 ++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+), 2 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index c7943ffb..9a03fa09 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -76,6 +76,8 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect frames: frames, hostmetadata: hostmetadata, traceEvents: xsync.NewRWMutex(map[traceAndMetaKey]*traceEvents{}), + + samplesPerSecond: cfg.SamplesPerSecond, }, nil } @@ -230,7 +232,8 @@ func (r *CollectorReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEven } } -// getProfile returns an OTLP profile containing all collected samples up to this moment. +// getProfile sets the data an OTLP profile with all collected samples up to +// this moment. func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, endTS pcommon.Timestamp) { traceEvents := r.traceEvents.WLock() @@ -392,7 +395,12 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, // When ranging over stringMap, the order will be according to the // hash value of the key. To get the correct order for profile.StringTable, // put the values in stringMap, in the correct array order. - for v := range stringMap { + stringTable := make([]string, len(stringMap)) + for v, idx := range stringMap { + stringTable[idx] = v + } + + for _, v := range stringTable { profile.StringTable().Append(v) } @@ -422,6 +430,11 @@ func (r *CollectorReporter) reportProfile(ctx context.Context) error { pc.SetStartTime(startTS) pc.SetEndTime(endTS) + if pc.Profile().Sample().Len() == 0 { + log.Debugf("Skip sending of profile to collector with no samples") + return nil + } + return r.nextConsumer.ConsumeProfiles(ctx, profiles) } diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index 2445dd20..32080642 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -5,9 +5,11 @@ import ( "errors" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer/consumerprofiles" "go.opentelemetry.io/collector/pdata/pprofile" + semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "go.opentelemetry.io/ebpf-profiler/libpf" ) @@ -58,3 +60,143 @@ func TestCollectorReporterReportTraceEvent(t *testing.T) { }) } } + +func TestCollectoReportProfile(t *testing.T) { + for _, tt := range []struct { + name string + reportTraceEvents func(*testing.T, Reporter) + + buildWantProfiles func(*testing.T) pprofile.Profiles + wantErr error + }{ + // Pending on https://github.com/open-telemetry/opentelemetry-collector/pull/11558 + /*{ + name: "with no data sent yet", + buildWantProfiles: func(t *testing.T) pprofile.Profiles { + return pprofile.NewProfiles() + }, + },*/ + { + name: "with a single sample", + reportTraceEvents: func(_ *testing.T, r Reporter) { + r.ReportTraceEvent( + &libpf.Trace{}, + &TraceEventMeta{ + Timestamp: libpf.UnixTime64(1), + Comm: "comm", + APMServiceName: "opentelemetry-ebpf-profiler", + }, + ) + }, + + buildWantProfiles: func(t *testing.T) pprofile.Profiles { + prof := pprofile.NewProfiles() + + rp := prof.ResourceProfiles().AppendEmpty() + sp := rp.ScopeProfiles().AppendEmpty() + + pc := sp.Profiles().AppendEmpty() + pc.SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) + pc.SetStartTime(1) + pc.SetEndTime(1) + + profile := pc.Profile() + profile.SetStartTime(1) + + fn := profile.Function().AppendEmpty() + fn.SetName(0) + fn.SetFilename(0) + + profile.StringTable().FromRaw([]string{ + "", + "samples", + "count", + "cpu", + "nanoseconds", + "AAAAAAAAAAAAAAAAAAAAAA", + }) + + require.NoError(t, profile.AttributeTable().FromRaw(map[string]any{ + string(semconv.ThreadNameKey): "comm", + string(semconv.ServiceNameKey): "opentelemetry-ebpf-profiler", + })) + + st := profile.SampleType().AppendEmpty() + st.SetType(1) + st.SetUnit(2) + + pt := profile.PeriodType() + pt.SetType(3) + pt.SetUnit(4) + profile.SetPeriod(1000000000) + + sample := profile.Sample().AppendEmpty() + sample.SetStacktraceIdIndex(5) + sample.Value().FromRaw([]int64{1}) + sample.TimestampsUnixNano().FromRaw([]uint64{1}) + sample.Attributes().FromRaw([]uint64{0, 1}) + + return prof + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + var gotProfiles pprofile.Profiles + next, err := consumerprofiles.NewProfiles( + func(_ context.Context, p pprofile.Profiles) error { + gotProfiles = p + return nil + }, + ) + require.NoError(t, err) + + r, err := NewCollector(&Config{ + CacheSize: 1, + SamplesPerSecond: 1, + }, next) + require.NoError(t, err) + + if tt.reportTraceEvents != nil { + tt.reportTraceEvents(t, r) + } + + err = r.reportProfile(context.Background()) + if tt.wantErr == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, tt.wantErr, err) + } + + wantProfiles := tt.buildWantProfiles(t) + if gotProfiles.SampleCount() == 0 { + assert.Equal(t, wantProfiles.SampleCount(), gotProfiles.SampleCount()) + return + } + + // Set a dummy profile ID to allow reproducible assertions + assert.NotEmpty(t, gotProfiles.ResourceProfiles().At(0). + ScopeProfiles().At(0). + Profiles().At(0).ProfileID()) + gotProfiles.ResourceProfiles().At(0). + ScopeProfiles().At(0). + Profiles().At(0). + SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) + + // Check the profile directly, as it's too nested for testify to provide + // a meaningful diff + require.Equal(t, + gotProfiles.ResourceProfiles().At(0). + ScopeProfiles().At(0). + Profiles().At(0). + Profile(), + wantProfiles.ResourceProfiles().At(0). + ScopeProfiles().At(0). + Profiles().At(0). + Profile(), + ) + + // Also check the global object + assert.Equal(t, wantProfiles, gotProfiles) + }) + } +} From 7466b86504140ccae4b41c492073daa0dfc6dc21 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Thu, 31 Oct 2024 10:37:32 +0100 Subject: [PATCH 11/44] bring back test with no data --- reporter/collector_reporter_test.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index 32080642..bb7c527d 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -66,16 +66,14 @@ func TestCollectoReportProfile(t *testing.T) { name string reportTraceEvents func(*testing.T, Reporter) + wantConsumedCount int buildWantProfiles func(*testing.T) pprofile.Profiles wantErr error }{ - // Pending on https://github.com/open-telemetry/opentelemetry-collector/pull/11558 - /*{ - name: "with no data sent yet", - buildWantProfiles: func(t *testing.T) pprofile.Profiles { - return pprofile.NewProfiles() - }, - },*/ + { + name: "with no data sent yet", + wantConsumedCount: 0, + }, { name: "with a single sample", reportTraceEvents: func(_ *testing.T, r Reporter) { @@ -89,6 +87,7 @@ func TestCollectoReportProfile(t *testing.T) { ) }, + wantConsumedCount: 1, buildWantProfiles: func(t *testing.T) pprofile.Profiles { prof := pprofile.NewProfiles() @@ -141,9 +140,11 @@ func TestCollectoReportProfile(t *testing.T) { }, } { t.Run(tt.name, func(t *testing.T) { + var consumedCount int var gotProfiles pprofile.Profiles next, err := consumerprofiles.NewProfiles( func(_ context.Context, p pprofile.Profiles) error { + consumedCount++ gotProfiles = p return nil }, @@ -167,6 +168,14 @@ func TestCollectoReportProfile(t *testing.T) { require.ErrorIs(t, tt.wantErr, err) } + assert.Equal(t, tt.wantConsumedCount, consumedCount) + + // If we don't expect anything to have been consumed, we don't have + // anything else to check. + if tt.wantConsumedCount == 0 { + return + } + wantProfiles := tt.buildWantProfiles(t) if gotProfiles.SampleCount() == 0 { assert.Equal(t, wantProfiles.SampleCount(), gotProfiles.SampleCount()) From 0d104ddf930016cfb59b83c6d6561be79bc665b8 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 4 Nov 2024 09:48:32 +0100 Subject: [PATCH 12/44] fix linter --- reporter/collector_reporter.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 9a03fa09..ff230f58 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -81,7 +81,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect }, nil } -func (r *CollectorReporter) Start() { +func (r *CollectorReporter) Start(context.Context) error { go func() { tick := time.NewTicker(r.cfg.ReportInterval) defer tick.Stop() @@ -97,6 +97,8 @@ func (r *CollectorReporter) Start() { } } }() + + return nil } // ExecutableKnown returns true if the metadata of the Executable specified by fileID is From ebbe4b28835edae902f45899966cce65c454b3c5 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Mon, 4 Nov 2024 10:07:15 +0100 Subject: [PATCH 13/44] use go-cmp to compare nested structs --- go.mod | 9 ++++----- go.sum | 4 ---- reporter/collector_reporter_test.go | 23 ++++++++--------------- 3 files changed, 12 insertions(+), 24 deletions(-) diff --git a/go.mod b/go.mod index 35ae4bd7..4e2b0581 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,14 @@ module go.opentelemetry.io/ebpf-profiler go 1.22.2 require ( + github.com/aws/aws-sdk-go-v2 v1.30.5 github.com/aws/aws-sdk-go-v2/config v1.27.35 - github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.21 github.com/aws/aws-sdk-go-v2/service/s3 v1.62.0 github.com/cespare/xxhash/v2 v2.3.0 github.com/cilium/ebpf v0.16.0 github.com/elastic/go-freelru v0.15.0 github.com/elastic/go-perf v0.0.0-20241016160959-1342461adb4a + github.com/google/go-cmp v0.6.0 github.com/google/uuid v1.6.0 github.com/jsimonetti/rtnetlink v1.4.2 github.com/klauspost/compress v1.17.9 @@ -20,6 +21,8 @@ require ( github.com/tklauser/numcpus v0.8.0 github.com/zeebo/xxh3 v1.0.2 go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0 + go.opentelemetry.io/collector/pdata v1.18.0 + go.opentelemetry.io/collector/pdata/pprofile v0.112.0 go.opentelemetry.io/otel v1.30.0 go.opentelemetry.io/proto/otlp v1.3.1 golang.org/x/arch v0.10.0 @@ -30,7 +33,6 @@ require ( ) require ( - github.com/aws/aws-sdk-go-v2 v1.30.5 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.4 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.17.33 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.13 // indirect @@ -48,7 +50,6 @@ require ( github.com/aws/smithy-go v1.20.4 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/google/go-cmp v0.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect github.com/josharian/native v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -59,8 +60,6 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect go.opentelemetry.io/collector/consumer v0.112.0 // indirect - go.opentelemetry.io/collector/pdata v1.18.0 // indirect - go.opentelemetry.io/collector/pdata/pprofile v0.112.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/net v0.28.0 // indirect golang.org/x/text v0.17.0 // indirect diff --git a/go.sum b/go.sum index 9ea94a43..89c48029 100644 --- a/go.sum +++ b/go.sum @@ -8,8 +8,6 @@ github.com/aws/aws-sdk-go-v2/credentials v1.17.33 h1:lBHAQQznENv0gLHAZ73ONiTSkCt github.com/aws/aws-sdk-go-v2/credentials v1.17.33/go.mod h1:MBuqCUOT3ChfLuxNDGyra67eskx7ge9e3YKYBce7wpI= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.13 h1:pfQ2sqNpMVK6xz2RbqLEL0GH87JOwSxPV2rzm8Zsb74= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.13/go.mod h1:NG7RXPUlqfsCLLFfi0+IpKN4sCB9D9fw/qTaSB+xRoU= -github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.21 h1:sV0doPPsRT7gMP0BnDPwSsysVTV/nKpB/nFmMnz8goE= -github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.21/go.mod h1:ictvfJWqE2gkUFDRJVp5VU/TrytuzK88DYcpan7UYuA= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.17 h1:pI7Bzt0BJtYA0N/JEC6B8fJ4RBrEMi1LBrkMdFYNSnQ= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.17/go.mod h1:Dh5zzJYMtxfIjYW+/evjQ8uj2OyR/ve2KROHGHlSFqE= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.17 h1:Mqr/V5gvrhA2gvgnF42Zh5iMiQNcOYthFYwCyrnuWlc= @@ -43,8 +41,6 @@ github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEn github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/elastic/go-freelru v0.13.0 h1:TKKY6yCfNNNky7Pj9xZAOEpBcdNgZJfihEftOb55omg= -github.com/elastic/go-freelru v0.13.0/go.mod h1:bSdWT4M0lW79K8QbX6XY2heQYSCqD7THoYf82pT/H3I= github.com/elastic/go-freelru v0.15.0 h1:Jo1aY8JAvpyxbTDJEudrsBfjFDaALpfVv8mxuh9sfvI= github.com/elastic/go-freelru v0.15.0/go.mod h1:bSdWT4M0lW79K8QbX6XY2heQYSCqD7THoYf82pT/H3I= github.com/elastic/go-perf v0.0.0-20241016160959-1342461adb4a h1:ymmtaN4bVCmKKeu4XEf6JEWNZKRXPMng1zjpKd+8rCU= diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index bb7c527d..56f2cdef 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -5,6 +5,7 @@ import ( "errors" "testing" + "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer/consumerprofiles" @@ -191,21 +192,13 @@ func TestCollectoReportProfile(t *testing.T) { Profiles().At(0). SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) - // Check the profile directly, as it's too nested for testify to provide - // a meaningful diff - require.Equal(t, - gotProfiles.ResourceProfiles().At(0). - ScopeProfiles().At(0). - Profiles().At(0). - Profile(), - wantProfiles.ResourceProfiles().At(0). - ScopeProfiles().At(0). - Profiles().At(0). - Profile(), - ) - - // Also check the global object - assert.Equal(t, wantProfiles, gotProfiles) + assert.Empty(t, cmp.Diff( + wantProfiles, + gotProfiles, + cmp.Comparer(func(a pprofile.Profiles, b pprofile.Profiles) bool { + return assert.ObjectsAreEqualValues(a, b) + }), + )) }) } } From 602f2b6998ff92eb08c7a36fba40ee5dcbeee97b Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 09:10:55 +0100 Subject: [PATCH 14/44] Update reporter/collector_reporter_test.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Tim Rühsen --- reporter/collector_reporter_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index 56f2cdef..ddd28b09 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -62,7 +62,7 @@ func TestCollectorReporterReportTraceEvent(t *testing.T) { } } -func TestCollectoReportProfile(t *testing.T) { +func TestCollectorReporterReportProfile(t *testing.T) { for _, tt := range []struct { name string reportTraceEvents func(*testing.T, Reporter) From 94f784629b20b6e14e4df4893ba2642a9f463478 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 09:13:51 +0100 Subject: [PATCH 15/44] add purgeTick --- reporter/collector_reporter.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index ff230f58..ab2f9001 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -85,6 +85,9 @@ func (r *CollectorReporter) Start(context.Context) error { go func() { tick := time.NewTicker(r.cfg.ReportInterval) defer tick.Stop() + purgeTick := time.NewTicker(5 * time.Minute) + defer purgeTick.Stop() + for { select { case <-r.stopSignal: @@ -94,6 +97,10 @@ func (r *CollectorReporter) Start(context.Context) error { log.Errorf("Request failed: %v", err) } tick.Reset(libpf.AddJitter(r.cfg.ReportInterval, 0.2)) + case <-purgeTick.C: + // Allow the GC to purge expired entries to avoid memory leaks. + r.executables.PurgeExpired() + r.frames.PurgeExpired() } } }() From d9e97f3bc0b739ef249cea3cb0fbee9a5befe800 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 09:16:36 +0100 Subject: [PATCH 16/44] add container ID --- reporter/collector_reporter.go | 63 +++++++++++++++++++++++++++++ reporter/collector_reporter_test.go | 10 +++-- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index ab2f9001..314d1e74 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -4,8 +4,11 @@ package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" import ( + "bufio" "context" + "fmt" "maps" + "os" "slices" "time" @@ -37,6 +40,9 @@ type CollectorReporter struct { // executables stores metadata for executables. executables *lru.SyncedLRU[libpf.FileID, execInfo] + // cgroupv2ID caches PID to container ID information for cgroupv2 containers. + cgroupv2ID *lru.SyncedLRU[libpf.PID, string] + // frames maps frame information to its source location. frames *lru.SyncedLRU[libpf.FileID, *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]] @@ -60,6 +66,14 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect return nil, err } + cgroupv2ID, err := lru.NewSynced[libpf.PID, string](cfg.CGroupCacheElements, + func(pid libpf.PID) uint32 { return uint32(pid) }) + if err != nil { + return nil, err + } + // Set a lifetime to reduce risk of invalid data in case of PID reuse. + cgroupv2ID.SetLifetime(90 * time.Second) + // Next step: Dynamically configure the size of this LRU. // Currently, we use the length of the JSON array in // hostmetadata/hostmetadata.json. @@ -76,6 +90,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect frames: frames, hostmetadata: hostmetadata, traceEvents: xsync.NewRWMutex(map[traceAndMetaKey]*traceEvents{}), + cgroupv2ID: cgroupv2ID, samplesPerSecond: cfg.SamplesPerSecond, }, nil @@ -218,10 +233,17 @@ func (r *CollectorReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEven traceEventsMap := r.traceEvents.WLock() defer r.traceEvents.WUnlock(&traceEventsMap) + containerID, err := r.lookupCgroupv2(meta.PID) + if err != nil { + log.Debugf("Failed to get a cgroupv2 ID as container ID for PID %d: %v", + meta.PID, err) + } + key := traceAndMetaKey{ hash: trace.Hash, comm: meta.Comm, apmServiceName: meta.APMServiceName, + containerID: containerID, } if events, exists := (*traceEventsMap)[key]; exists { @@ -447,6 +469,47 @@ func (r *CollectorReporter) reportProfile(ctx context.Context) error { return r.nextConsumer.ConsumeProfiles(ctx, profiles) } +// lookupCgroupv2 returns the cgroupv2 ID for pid. +func (r *CollectorReporter) lookupCgroupv2(pid libpf.PID) (string, error) { + id, ok := r.cgroupv2ID.Get(pid) + if ok { + return id, nil + } + + // Slow path + f, err := os.Open(fmt.Sprintf("/proc/%d/cgroup", pid)) + if err != nil { + return "", err + } + defer f.Close() + + var genericCgroupv2 string + scanner := bufio.NewScanner(f) + buf := make([]byte, 512) + // Providing a predefined buffer overrides the internal buffer that Scanner uses (4096 bytes). + // We can do that and also set a maximum allocation size on the following call. + // With a maximum of 4096 characters path in the kernel, 8192 should be fine here. We don't + // expect lines in /proc//cgroup to be longer than that. + scanner.Buffer(buf, 8192) + var pathParts []string + for scanner.Scan() { + line := scanner.Text() + pathParts = cgroupv2PathPattern.FindStringSubmatch(line) + if pathParts == nil { + log.Debugf("Could not extract cgroupv2 path from line: %s", line) + continue + } + genericCgroupv2 = pathParts[1] + break + } + + // Cache the cgroupv2 information. + // To avoid busy lookups, also empty cgroupv2 information is cached. + r.cgroupv2ID.Add(pid, genericCgroupv2) + + return genericCgroupv2, nil +} + // addPdataProfileAttributes adds attributes to Profile.attribute_table and returns // the indices to these attributes. func addPdataProfileAttributes(profile pprofile.Profile, diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index ddd28b09..b99799f7 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -54,7 +54,9 @@ func TestCollectorReporterReportTraceEvent(t *testing.T) { } r, err := NewCollector(&Config{ - CacheSize: 1, + ExecutablesCacheElements: 1, + FramesCacheElements: 1, + CGroupCacheElements: 1, }, next) require.NoError(t, err) r.ReportTraceEvent(tt.trace, tt.meta) @@ -153,8 +155,10 @@ func TestCollectorReporterReportProfile(t *testing.T) { require.NoError(t, err) r, err := NewCollector(&Config{ - CacheSize: 1, - SamplesPerSecond: 1, + ExecutablesCacheElements: 1, + FramesCacheElements: 1, + CGroupCacheElements: 1, + SamplesPerSecond: 1, }, next) require.NoError(t, err) From 9a739ba8bf82f6ae6a89d2032dae5572ff7be828 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 09:23:07 +0100 Subject: [PATCH 17/44] fix rebase error --- reporter/collector_reporter.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 314d1e74..b23e35dc 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -55,13 +55,15 @@ type CollectorReporter struct { // NewCollector builds a new CollectorReporter func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*CollectorReporter, error) { - executables, err := lru.NewSynced[libpf.FileID, execInfo](cfg.CacheSize, libpf.FileID.Hash32) + executables, err := + lru.NewSynced[libpf.FileID, execInfo](cfg.ExecutablesCacheElements, libpf.FileID.Hash32) if err != nil { return nil, err } frames, err := lru.NewSynced[libpf.FileID, - *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]](cfg.CacheSize, libpf.FileID.Hash32) + *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]]( + cfg.FramesCacheElements, libpf.FileID.Hash32) if err != nil { return nil, err } From b37d68e0f4313738263b475c67e45481b3617112 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 10:11:19 +0100 Subject: [PATCH 18/44] add set lifetimes --- reporter/collector_reporter.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index b23e35dc..ea9569fa 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -60,6 +60,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect if err != nil { return nil, err } + executables.SetLifetime(1 * time.Hour) // Allow GC to clean stale items. frames, err := lru.NewSynced[libpf.FileID, *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]]( @@ -67,6 +68,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect if err != nil { return nil, err } + frames.SetLifetime(1 * time.Hour) // Allow GC to clean stale items. cgroupv2ID, err := lru.NewSynced[libpf.PID, string](cfg.CGroupCacheElements, func(pid libpf.PID) uint32 { return uint32(pid) }) From f5f64c7567a9bc5fe86cb93dde3204cf604a121f Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 11:13:41 +0100 Subject: [PATCH 19/44] Update reporter/collector_reporter.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Tim Rühsen --- reporter/collector_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index ea9569fa..7564dfc1 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -26,7 +26,7 @@ import ( // Assert that we implement the full Reporter interface. var _ Reporter = (*CollectorReporter)(nil) -// OTLPReporter receives and transforms information to be Collector Collector compliant. +// CollectorReporter receives and transforms information to be Collector Collector compliant. type CollectorReporter struct { cfg *Config nextConsumer consumerprofiles.Profiles From f4f7d4166cc32ec5124cfca43d82d3680aaf17d3 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Tue, 5 Nov 2024 11:13:54 +0100 Subject: [PATCH 20/44] Update reporter/collector_reporter.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Tim Rühsen --- reporter/collector_reporter.go | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 7564dfc1..63039bca 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -546,16 +546,14 @@ func addPdataProfileAttributes(profile pprofile.Profile, func getDummyPdataMappingIndex(fileIDtoMapping map[libpf.FileID]uint64, stringMap map[string]uint32, profile pprofile.Profile, fileID libpf.FileID) uint64 { - var locationMappingIndex uint64 - if tmpMappingIndex, exists := fileIDtoMapping[fileID]; exists { - locationMappingIndex = tmpMappingIndex - } else { - idx := uint64(len(fileIDtoMapping)) - fileIDtoMapping[fileID] = idx - locationMappingIndex = idx - - mapping := profile.Mapping().AppendEmpty() - mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) + if mappingIndex, exists := fileIDtoMapping[fileID]; exists { + return mappingIndex } + + locationMappingIndex := uint64(len(fileIDtoMapping)) + fileIDtoMapping[fileID] = locationMappingIndex + + mapping := profile.Mapping().AppendEmpty() + mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) return locationMappingIndex } From cba2b900f81de04cec057cb7c2c2d703d062a9fa Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Fri, 8 Nov 2024 09:57:14 +0100 Subject: [PATCH 21/44] Update reporter/collector_reporter.go Co-authored-by: Florian Lehner --- reporter/collector_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 63039bca..b13e744c 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -356,7 +356,7 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, // semantic convention for build_id, replace these hard coded // strings. {key: "process.executable.build_id.gnu", value: ei.gnuBuildID}, - {key: "process.executable.build_id.profiling", + {key: "process.executable.build_id.htlhash", value: traceInfo.files[i].StringNoQuotes()}, }, attributeMap) From f8f2ab7e4ae219177ee297d02d37f80fc79181c2 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Fri, 8 Nov 2024 11:42:03 +0100 Subject: [PATCH 22/44] use attrKeyValue with generics --- reporter/collector_reporter.go | 36 ++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index b13e744c..80592f01 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -10,6 +10,7 @@ import ( "maps" "os" "slices" + "strconv" "time" lru "github.com/elastic/go-freelru" @@ -321,7 +322,7 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, // Walk every frame of the trace. for i := range traceInfo.frameTypes { - frameAttributes := addPdataProfileAttributes(profile, []attrKeyValue{ + frameAttributes := addPdataProfileAttributes(profile, []attrKeyValue[string]{ {key: "profile.frame.type", value: traceInfo.frameTypes[i].String()}, }, attributeMap) @@ -351,7 +352,7 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, fileName = ei.fileName } - mappingAttributes := addPdataProfileAttributes(profile, []attrKeyValue{ + mappingAttributes := addPdataProfileAttributes(profile, []attrKeyValue[string]{ // Once SemConv and its Go package is released with the new // semantic convention for build_id, replace these hard coded // strings. @@ -408,11 +409,14 @@ func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, } } - sampleAttrs := addPdataProfileAttributes(profile, []attrKeyValue{ + sampleAttrs := append(addPdataProfileAttributes(profile, []attrKeyValue[string]{ {key: string(semconv.ContainerIDKey), value: traceKey.containerID}, {key: string(semconv.ThreadNameKey), value: traceKey.comm}, {key: string(semconv.ServiceNameKey), value: traceKey.apmServiceName}, - }, attributeMap) + }, attributeMap), addPdataProfileAttributes(profile, []attrKeyValue[int64]{ + {key: string(semconv.ProcessPIDKey), value: traceKey.pid}, + }, attributeMap)...) + sample.Attributes().FromRaw(sampleAttrs) sample.SetLocationsLength(uint64(len(traceInfo.frameTypes))) @@ -516,22 +520,34 @@ func (r *CollectorReporter) lookupCgroupv2(pid libpf.PID) (string, error) { // addPdataProfileAttributes adds attributes to Profile.attribute_table and returns // the indices to these attributes. -func addPdataProfileAttributes(profile pprofile.Profile, - attributes []attrKeyValue, attributeMap map[string]uint64) []uint64 { +func addPdataProfileAttributes[T string | int64](profile pprofile.Profile, + attributes []attrKeyValue[T], attributeMap map[string]uint64) []uint64 { indices := make([]uint64, 0, len(attributes)) - addAttr := func(attr attrKeyValue) { - if attr.value == "" { + addAttr := func(attr attrKeyValue[T]) { + var attributeCompositeKey string + var attributeValue string + + switch val := any(attr.value).(type) { + case string: + attributeCompositeKey = attr.key + "_" + val + attributeValue = val + case int64: + strVal := strconv.FormatInt(val, 10) + attributeCompositeKey = attr.key + "_" + strVal + attributeValue = strVal + default: + log.Error("Unsupported attribute value type. Only string and int64 are supported.") return } - attributeCompositeKey := attr.key + "_" + attr.value + if attributeIndex, exists := attributeMap[attributeCompositeKey]; exists { indices = append(indices, attributeIndex) return } newIndex := uint64(profile.AttributeTable().Len()) indices = append(indices, newIndex) - profile.AttributeTable().PutStr(attr.key, attr.value) + profile.AttributeTable().PutStr(attr.key, attributeValue) attributeMap[attributeCompositeKey] = newIndex } From 0d545613e6763404365350a95a52f7785a44f446 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 10 Dec 2024 11:31:51 +0100 Subject: [PATCH 23/44] use the pdata package --- go.mod | 4 +- go.sum | 8 +- reporter/collector_reporter.go | 530 ++++++++-------------------- reporter/collector_reporter_test.go | 39 +- 4 files changed, 168 insertions(+), 413 deletions(-) diff --git a/go.mod b/go.mod index afc89abd..2bc0c08f 100644 --- a/go.mod +++ b/go.mod @@ -21,8 +21,8 @@ require ( github.com/tklauser/numcpus v0.8.0 github.com/zeebo/xxh3 v1.0.2 go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0 - go.opentelemetry.io/collector/pdata v1.18.0 - go.opentelemetry.io/collector/pdata/pprofile v0.112.0 + go.opentelemetry.io/collector/pdata v1.21.0 + go.opentelemetry.io/collector/pdata/pprofile v0.115.0 go.opentelemetry.io/otel v1.30.0 golang.org/x/arch v0.10.0 golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 diff --git a/go.sum b/go.sum index cce63524..6d51846e 100644 --- a/go.sum +++ b/go.sum @@ -108,10 +108,10 @@ go.opentelemetry.io/collector/consumer v0.112.0 h1:tfO4FpuQ8MsD7AxgslC3tRNVYjd9X go.opentelemetry.io/collector/consumer v0.112.0/go.mod h1:ZKSeGvXvaofIlvPrWlARKQpONOmuw6R/yifgYCWHKRw= go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0 h1:ym+QxemlbWwfMSUto1hRTfcZeYbj2q8FpMzjk8O+X60= go.opentelemetry.io/collector/consumer/consumerprofiles v0.112.0/go.mod h1:4PjDUpURFh85R6NLEHrEf/uZjpk4LAYmmOrqu+iZsyE= -go.opentelemetry.io/collector/pdata v1.18.0 h1:/yg2rO2dxqDM2p6GutsMCxXN6sKlXwyIz/ZYyUPONBg= -go.opentelemetry.io/collector/pdata v1.18.0/go.mod h1:Ox1YVLe87cZDB/TL30i4SUz1cA5s6AM6SpFMfY61ICs= -go.opentelemetry.io/collector/pdata/pprofile v0.112.0 h1:t+LYorcMqZ3sDz5/jp3xU2l5lIhIXuIOOGO4Ef9CG2c= -go.opentelemetry.io/collector/pdata/pprofile v0.112.0/go.mod h1:F2aTCoDzIaxEUK1g92LZvMwradySFMo3ZsAnBIpOdUg= +go.opentelemetry.io/collector/pdata v1.21.0 h1:PG+UbiFMJ35X/WcAR7Rf/PWmWtRdW0aHlOidsR6c5MA= +go.opentelemetry.io/collector/pdata v1.21.0/go.mod h1:GKb1/zocKJMvxKbS+sl0W85lxhYBTFJ6h6I1tphVyDU= +go.opentelemetry.io/collector/pdata/pprofile v0.115.0 h1:NI89hy13vNDw7EOnQf7Jtitks4HJFO0SUWznTssmP94= +go.opentelemetry.io/collector/pdata/pprofile v0.115.0/go.mod h1:jGzdNfO0XTtfLjXCL/uCC1livg1LlfR+ix2WE/z3RpQ= go.opentelemetry.io/otel v1.30.0 h1:F2t8sK4qf1fAmY9ua4ohFS/K+FUuOPemHUIXHtktrts= go.opentelemetry.io/otel v1.30.0/go.mod h1:tFw4Br9b7fOS+uEao81PJjVMjW/5fvNCbpsDIXqP0pc= go.opentelemetry.io/otel/trace v1.30.0 h1:7UBkkYzeg3C7kQX8VAidWh2biiQbtAKjyIML8dQ9wmc= diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 80592f01..26ec61d2 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -4,24 +4,21 @@ package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" import ( - "bufio" "context" - "fmt" "maps" - "os" - "slices" "strconv" "time" lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" "go.opentelemetry.io/collector/consumer/consumerprofiles" - "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/pprofile" semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "go.opentelemetry.io/ebpf-profiler/libpf" "go.opentelemetry.io/ebpf-profiler/libpf/xsync" + "go.opentelemetry.io/ebpf-profiler/reporter/internal/pdata" + "go.opentelemetry.io/ebpf-profiler/reporter/internal/samples" ) // Assert that we implement the full Reporter interface. @@ -32,45 +29,42 @@ type CollectorReporter struct { cfg *Config nextConsumer consumerprofiles.Profiles - // stopSignal is the stop signal for shutting down all background tasks. - stopSignal chan struct{} + // name is the ScopeProfile's name. + name string + + // version is the ScopeProfile's version. + version string + + // runLoop handles the run loop + runLoop *runLoop // hostmetadata stores metadata that is sent out with every request. hostmetadata *lru.SyncedLRU[string, string] - // executables stores metadata for executables. - executables *lru.SyncedLRU[libpf.FileID, execInfo] - // cgroupv2ID caches PID to container ID information for cgroupv2 containers. cgroupv2ID *lru.SyncedLRU[libpf.PID, string] - // frames maps frame information to its source location. - frames *lru.SyncedLRU[libpf.FileID, *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]] + // pdata holds the generator for the data being exported. + pdata *pdata.Pdata // traceEvents stores reported trace events (trace metadata with frames and counts) - traceEvents xsync.RWMutex[map[traceAndMetaKey]*traceEvents] + traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] + + // hostID is the unique identifier of the host. + hostID string + + // kernelVersion is the version of the kernel. + kernelVersion string - // samplesPerSecond is the number of samples per second. - samplesPerSecond int + // hostName is the name of the host. + hostName string + + // ipAddress is the IP address of the host. + ipAddress string } // NewCollector builds a new CollectorReporter func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*CollectorReporter, error) { - executables, err := - lru.NewSynced[libpf.FileID, execInfo](cfg.ExecutablesCacheElements, libpf.FileID.Hash32) - if err != nil { - return nil, err - } - executables.SetLifetime(1 * time.Hour) // Allow GC to clean stale items. - - frames, err := lru.NewSynced[libpf.FileID, - *xsync.RWMutex[map[libpf.AddressOrLineno]sourceInfo]]( - cfg.FramesCacheElements, libpf.FileID.Hash32) - if err != nil { - return nil, err - } - frames.SetLifetime(1 * time.Hour) // Allow GC to clean stale items. - cgroupv2ID, err := lru.NewSynced[libpf.PID, string](cfg.CGroupCacheElements, func(pid libpf.PID) uint32 { return uint32(pid) }) if err != nil { @@ -87,42 +81,57 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect return nil, err } - return &CollectorReporter{ - cfg: cfg, - nextConsumer: nextConsumer, + data, err := pdata.New( + cfg.SamplesPerSecond, + cfg.ExecutablesCacheElements, + cfg.FramesCacheElements, + cfg.ExtraSampleAttrProd, + ) + if err != nil { + return nil, err + } - executables: executables, - frames: frames, + return &CollectorReporter{ + cfg: cfg, + nextConsumer: nextConsumer, + name: cfg.Name, + version: cfg.Version, + kernelVersion: cfg.KernelVersion, + hostName: cfg.HostName, + ipAddress: cfg.IPAddress, + hostID: strconv.FormatUint(cfg.HostID, 10), + runLoop: &runLoop{ + stopSignal: make(chan libpf.Void), + }, + pdata: data, hostmetadata: hostmetadata, - traceEvents: xsync.NewRWMutex(map[traceAndMetaKey]*traceEvents{}), - cgroupv2ID: cgroupv2ID, - - samplesPerSecond: cfg.SamplesPerSecond, + traceEvents: xsync.NewRWMutex( + map[samples.TraceAndMetaKey]*samples.TraceEvents{}, + ), + cgroupv2ID: cgroupv2ID, }, nil } -func (r *CollectorReporter) Start(context.Context) error { - go func() { - tick := time.NewTicker(r.cfg.ReportInterval) - defer tick.Stop() - purgeTick := time.NewTicker(5 * time.Minute) - defer purgeTick.Stop() - - for { - select { - case <-r.stopSignal: - return - case <-tick.C: - if err := r.reportProfile(context.Background()); err != nil { - log.Errorf("Request failed: %v", err) - } - tick.Reset(libpf.AddJitter(r.cfg.ReportInterval, 0.2)) - case <-purgeTick.C: - // Allow the GC to purge expired entries to avoid memory leaks. - r.executables.PurgeExpired() - r.frames.PurgeExpired() - } +func (r *CollectorReporter) Start(ctx context.Context) error { + // Create a child context for reporting features + ctx, cancelReporting := context.WithCancel(ctx) + + r.runLoop.Start(ctx, r.cfg.ReportInterval, func() { + if err := r.reportProfile(context.Background()); err != nil { + log.Errorf("Request failed: %v", err) } + }, func() { + // Allow the GC to purge expired entries to avoid memory leaks. + r.pdata.Purge() + r.cgroupv2ID.PurgeExpired() + }) + + // When Stop() is called and a signal to 'stop' is received, then: + // - cancel the reporting functions currently running (using context) + // - close the gRPC connection with collection-agent + go func() { + <-r.runLoop.stopSignal + cancelReporting() }() return nil @@ -131,16 +140,16 @@ func (r *CollectorReporter) Start(context.Context) error { // ExecutableKnown returns true if the metadata of the Executable specified by fileID is // cached in the reporter. func (r *CollectorReporter) ExecutableKnown(fileID libpf.FileID) bool { - _, known := r.executables.Get(fileID) + _, known := r.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) return known } // ExecutableMetadata accepts a fileID with the corresponding filename // and caches this information. func (r *CollectorReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { - r.executables.Add(args.FileID, execInfo{ - fileName: args.FileName, - gnuBuildID: args.GnuBuildID, + r.pdata.Executables.Add(args.FileID, samples.ExecInfo{ + FileName: args.FileName, + GnuBuildID: args.GnuBuildID, }) } @@ -148,7 +157,8 @@ func (r *CollectorReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { // cached in the reporter. func (r *CollectorReporter) FrameKnown(frameID libpf.FrameID) bool { known := false - if frameMapLock, exists := r.frames.Get(frameID.FileID()); exists { + if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(frameID.FileID(), + pdata.FramesCacheLifetime); exists { frameMap := frameMapLock.RLock() defer frameMapLock.RUnlock(&frameMap) _, known = (*frameMap)[frameID.AddressOrLine()] @@ -161,7 +171,12 @@ func (r *CollectorReporter) FrameMetadata(args *FrameMetadataArgs) { fileID := args.FrameID.FileID() addressOrLine := args.FrameID.AddressOrLine() - if frameMapLock, exists := r.frames.Get(fileID); exists { + log.Debugf("FrameMetadata [%x] %v+%v at %v:%v", + fileID, args.FunctionName, args.FunctionOffset, + args.SourceFile, args.SourceLine) + + if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(fileID, + pdata.FramesCacheLifetime); exists { frameMap := frameMapLock.WLock() defer frameMapLock.WUnlock(&frameMap) @@ -170,28 +185,28 @@ func (r *CollectorReporter) FrameMetadata(args *FrameMetadataArgs) { // The new SourceFile may be empty, and we don't want to overwrite // an existing filePath with it. if s, exists := (*frameMap)[addressOrLine]; exists { - sourceFile = s.filePath + sourceFile = s.FilePath } } - (*frameMap)[addressOrLine] = sourceInfo{ - lineNumber: args.SourceLine, - filePath: sourceFile, - functionOffset: args.FunctionOffset, - functionName: args.FunctionName, + (*frameMap)[addressOrLine] = samples.SourceInfo{ + LineNumber: args.SourceLine, + FilePath: sourceFile, + FunctionOffset: args.FunctionOffset, + FunctionName: args.FunctionName, } return } - v := make(map[libpf.AddressOrLineno]sourceInfo) - v[addressOrLine] = sourceInfo{ - lineNumber: args.SourceLine, - filePath: args.SourceFile, - functionOffset: args.FunctionOffset, - functionName: args.FunctionName, + v := make(map[libpf.AddressOrLineno]samples.SourceInfo) + v[addressOrLine] = samples.SourceInfo{ + LineNumber: args.SourceLine, + FilePath: args.SourceFile, + FunctionOffset: args.FunctionOffset, + FunctionName: args.FunctionName, } mu := xsync.NewRWMutex(v) - r.frames.Add(fileID, &mu) + r.pdata.Frames.Add(fileID, &mu) } // GetMetrics returns internal metrics of CollectorReporter. @@ -210,7 +225,7 @@ func (r *CollectorReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ * func (r *CollectorReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} func (r *CollectorReporter) Stop() { - close(r.stopSignal) + r.runLoop.Stop() } // ReportHostMetadata enqueues host metadata. @@ -231,345 +246,86 @@ func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, // ReportTraceEvent enqueues reported trace events for the Collector reporter. func (r *CollectorReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { - if r.nextConsumer == nil { - return - } - traceEventsMap := r.traceEvents.WLock() defer r.traceEvents.WUnlock(&traceEventsMap) - containerID, err := r.lookupCgroupv2(meta.PID) + var extraMeta any + if r.cfg.ExtraSampleAttrProd != nil { + extraMeta = r.cfg.ExtraSampleAttrProd.CollectExtraSampleMeta(trace, meta) + } + + containerID, err := libpf.LookupCgroupv2(r.cgroupv2ID, meta.PID) if err != nil { log.Debugf("Failed to get a cgroupv2 ID as container ID for PID %d: %v", meta.PID, err) } - key := traceAndMetaKey{ - hash: trace.Hash, - comm: meta.Comm, - apmServiceName: meta.APMServiceName, - containerID: containerID, + key := samples.TraceAndMetaKey{ + Hash: trace.Hash, + Comm: meta.Comm, + Executable: meta.Executable, + ApmServiceName: meta.APMServiceName, + ContainerID: containerID, + Pid: int64(meta.PID), + ExtraMeta: extraMeta, } if events, exists := (*traceEventsMap)[key]; exists { - events.timestamps = append(events.timestamps, uint64(meta.Timestamp)) + events.Timestamps = append(events.Timestamps, uint64(meta.Timestamp)) (*traceEventsMap)[key] = events return } - (*traceEventsMap)[key] = &traceEvents{ - files: trace.Files, - linenos: trace.Linenos, - frameTypes: trace.FrameTypes, - mappingStarts: trace.MappingStart, - mappingEnds: trace.MappingEnd, - mappingFileOffsets: trace.MappingFileOffsets, - timestamps: []uint64{uint64(meta.Timestamp)}, + (*traceEventsMap)[key] = &samples.TraceEvents{ + Files: trace.Files, + Linenos: trace.Linenos, + FrameTypes: trace.FrameTypes, + MappingStarts: trace.MappingStart, + MappingEnds: trace.MappingEnd, + MappingFileOffsets: trace.MappingFileOffsets, + Timestamps: []uint64{uint64(meta.Timestamp)}, } } -// getProfile sets the data an OTLP profile with all collected samples up to -// this moment. -func (r *CollectorReporter) setProfile(profile pprofile.Profile) (startTS, - endTS pcommon.Timestamp) { +// reportProfile creates and sends out a profile. +func (r *CollectorReporter) reportProfile(ctx context.Context) error { traceEvents := r.traceEvents.WLock() - samples := maps.Clone(*traceEvents) + events := maps.Clone(*traceEvents) clear(*traceEvents) r.traceEvents.WUnlock(&traceEvents) - // stringMap is a temporary helper that will build the StringTable. - // By specification, the first element should be empty. - stringMap := make(map[string]uint32) - stringMap[""] = 0 - - // funcMap is a temporary helper that will build the Function array - // in profile and make sure information is deduplicated. - funcMap := make(map[funcInfo]uint64) - funcMap[funcInfo{name: "", fileName: ""}] = 0 - - // attributeMap is a temporary helper that maps attribute values to - // their respective indices. - // This is to ensure that AttributeTable does not contain duplicates. - attributeMap := make(map[string]uint64) - - st := profile.SampleType().AppendEmpty() - st.SetType(int64(getStringMapIndex(stringMap, "samples"))) - st.SetUnit(int64(getStringMapIndex(stringMap, "count"))) - - pt := profile.PeriodType() - pt.SetType(int64(getStringMapIndex(stringMap, "cpu"))) - pt.SetUnit(int64(getStringMapIndex(stringMap, "nanoseconds"))) - profile.SetPeriod(1e9 / int64(r.samplesPerSecond)) - - locationIndex := uint64(0) - - // Temporary lookup to reference existing Mappings. - fileIDtoMapping := make(map[libpf.FileID]uint64) - - for traceKey, traceInfo := range samples { - sample := profile.Sample().AppendEmpty() - sample.SetLocationsStartIndex(locationIndex) - - sample.SetStacktraceIdIndex(getStringMapIndex(stringMap, - traceKey.hash.Base64())) - - slices.Sort(traceInfo.timestamps) - startTS = pcommon.Timestamp(traceInfo.timestamps[0]) - endTS = pcommon.Timestamp(traceInfo.timestamps[len(traceInfo.timestamps)-1]) - - sample.TimestampsUnixNano().FromRaw(traceInfo.timestamps) - sample.Value().Append(1) - - // Walk every frame of the trace. - for i := range traceInfo.frameTypes { - frameAttributes := addPdataProfileAttributes(profile, []attrKeyValue[string]{ - {key: "profile.frame.type", value: traceInfo.frameTypes[i].String()}, - }, attributeMap) - - loc := profile.Location().AppendEmpty() - loc.SetAddress(uint64(traceInfo.linenos[i])) - loc.Attributes().FromRaw(frameAttributes) - - switch frameKind := traceInfo.frameTypes[i]; frameKind { - case libpf.NativeFrame: - // As native frames are resolved in the backend, we use Mapping to - // report these frames. - - var locationMappingIndex uint64 - if tmpMappingIndex, exists := fileIDtoMapping[traceInfo.files[i]]; exists { - locationMappingIndex = tmpMappingIndex - } else { - idx := uint64(len(fileIDtoMapping)) - fileIDtoMapping[traceInfo.files[i]] = idx - locationMappingIndex = idx - - ei, exists := r.executables.Get(traceInfo.files[i]) - - // Next step: Select a proper default value, - // if the name of the executable is not known yet. - var fileName = "UNKNOWN" - if exists { - fileName = ei.fileName - } - - mappingAttributes := addPdataProfileAttributes(profile, []attrKeyValue[string]{ - // Once SemConv and its Go package is released with the new - // semantic convention for build_id, replace these hard coded - // strings. - {key: "process.executable.build_id.gnu", value: ei.gnuBuildID}, - {key: "process.executable.build_id.htlhash", - value: traceInfo.files[i].StringNoQuotes()}, - }, attributeMap) - - mapping := profile.Mapping().AppendEmpty() - mapping.SetMemoryStart(uint64(traceInfo.mappingStarts[i])) - mapping.SetMemoryLimit(uint64(traceInfo.mappingEnds[i])) - mapping.SetFileOffset(traceInfo.mappingFileOffsets[i]) - mapping.SetFilename(int64(getStringMapIndex(stringMap, fileName))) - mapping.Attributes().FromRaw(mappingAttributes) - } - loc.SetMappingIndex(locationMappingIndex) - case libpf.AbortFrame: - // Next step: Figure out how the OTLP protocol - // could handle artificial frames, like AbortFrame, - // that are not originated from a native or interpreted - // program. - default: - // Store interpreted frame information as a Line message: - line := loc.Line().AppendEmpty() - - fileIDInfoLock, exists := r.frames.Get(traceInfo.files[i]) - if !exists { - // At this point, we do not have enough information for the frame. - // Therefore, we report a dummy entry and use the interpreter as filename. - line.SetFunctionIndex(createFunctionEntry(funcMap, - "UNREPORTED", frameKind.String())) - } else { - fileIDInfo := fileIDInfoLock.RLock() - if si, exists := (*fileIDInfo)[traceInfo.linenos[i]]; exists { - line.SetLine(int64(si.lineNumber)) - - line.SetFunctionIndex(createFunctionEntry(funcMap, - si.functionName, si.filePath)) - } else { - // At this point, we do not have enough information for the frame. - // Therefore, we report a dummy entry and use the interpreter as filename. - // To differentiate this case from the case where no information about - // the file ID is available at all, we use a different name for reported - // function. - line.SetFunctionIndex(createFunctionEntry(funcMap, - "UNRESOLVED", frameKind.String())) - } - fileIDInfoLock.RUnlock(&fileIDInfo) - } - - // To be compliant with the protocol, generate a dummy mapping entry. - loc.SetMappingIndex(getDummyPdataMappingIndex(fileIDtoMapping, stringMap, - profile, traceInfo.files[i])) - } - } - - sampleAttrs := append(addPdataProfileAttributes(profile, []attrKeyValue[string]{ - {key: string(semconv.ContainerIDKey), value: traceKey.containerID}, - {key: string(semconv.ThreadNameKey), value: traceKey.comm}, - {key: string(semconv.ServiceNameKey), value: traceKey.apmServiceName}, - }, attributeMap), addPdataProfileAttributes(profile, []attrKeyValue[int64]{ - {key: string(semconv.ProcessPIDKey), value: traceKey.pid}, - }, attributeMap)...) - - sample.Attributes().FromRaw(sampleAttrs) - - sample.SetLocationsLength(uint64(len(traceInfo.frameTypes))) - locationIndex += sample.LocationsLength() - } - log.Debugf("Reporting OTLP profile with %d samples", profile.Sample().Len()) - - // Populate the deduplicated functions into profile. - for v := range funcMap { - f := profile.Function().AppendEmpty() - f.SetName(int64(getStringMapIndex(stringMap, v.name))) - f.SetFilename(int64(getStringMapIndex(stringMap, v.fileName))) - } - - // When ranging over stringMap, the order will be according to the - // hash value of the key. To get the correct order for profile.StringTable, - // put the values in stringMap, in the correct array order. - stringTable := make([]string, len(stringMap)) - for v, idx := range stringMap { - stringTable[idx] = v - } - - for _, v := range stringTable { - profile.StringTable().Append(v) - } - - // profile.LocationIndices is not optional, and we only write elements into - // profile.Location that at least one sample references. - for i := int64(0); i < int64(profile.Location().Len()); i++ { - profile.LocationIndices().Append(i) + profiles := r.pdata.Generate(events) + for i := 0; i < profiles.ResourceProfiles().Len(); i++ { + r.setResource(profiles.ResourceProfiles().At(i)) } - profile.SetDuration(endTS - startTS) - profile.SetStartTime(startTS) - - return startTS, endTS -} - -// reportProfile sends a profile to the next consumer -func (r *CollectorReporter) reportProfile(ctx context.Context) error { - profiles := pprofile.NewProfiles() - rp := profiles.ResourceProfiles().AppendEmpty() - - sp := rp.ScopeProfiles().AppendEmpty() - - pc := sp.Profiles().AppendEmpty() - pc.SetProfileID(pprofile.ProfileID(mkProfileID())) - - startTS, endTS := r.setProfile(pc.Profile()) - pc.SetStartTime(startTS) - pc.SetEndTime(endTS) - - if pc.Profile().Sample().Len() == 0 { - log.Debugf("Skip sending of profile to collector with no samples") + if profiles.SampleCount() == 0 { + log.Debugf("Skip sending profile with no samples") return nil } return r.nextConsumer.ConsumeProfiles(ctx, profiles) } -// lookupCgroupv2 returns the cgroupv2 ID for pid. -func (r *CollectorReporter) lookupCgroupv2(pid libpf.PID) (string, error) { - id, ok := r.cgroupv2ID.Get(pid) - if ok { - return id, nil - } - - // Slow path - f, err := os.Open(fmt.Sprintf("/proc/%d/cgroup", pid)) - if err != nil { - return "", err - } - defer f.Close() - - var genericCgroupv2 string - scanner := bufio.NewScanner(f) - buf := make([]byte, 512) - // Providing a predefined buffer overrides the internal buffer that Scanner uses (4096 bytes). - // We can do that and also set a maximum allocation size on the following call. - // With a maximum of 4096 characters path in the kernel, 8192 should be fine here. We don't - // expect lines in /proc//cgroup to be longer than that. - scanner.Buffer(buf, 8192) - var pathParts []string - for scanner.Scan() { - line := scanner.Text() - pathParts = cgroupv2PathPattern.FindStringSubmatch(line) - if pathParts == nil { - log.Debugf("Could not extract cgroupv2 path from line: %s", line) - continue - } - genericCgroupv2 = pathParts[1] - break - } - - // Cache the cgroupv2 information. - // To avoid busy lookups, also empty cgroupv2 information is cached. - r.cgroupv2ID.Add(pid, genericCgroupv2) - - return genericCgroupv2, nil -} +// setResource sets the resource information of the origin of the profiles. +// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. +func (r *CollectorReporter) setResource(rp pprofile.ResourceProfiles) { + keys := r.hostmetadata.Keys() + attrs := rp.Resource().Attributes() -// addPdataProfileAttributes adds attributes to Profile.attribute_table and returns -// the indices to these attributes. -func addPdataProfileAttributes[T string | int64](profile pprofile.Profile, - attributes []attrKeyValue[T], attributeMap map[string]uint64) []uint64 { - indices := make([]uint64, 0, len(attributes)) - - addAttr := func(attr attrKeyValue[T]) { - var attributeCompositeKey string - var attributeValue string - - switch val := any(attr.value).(type) { - case string: - attributeCompositeKey = attr.key + "_" + val - attributeValue = val - case int64: - strVal := strconv.FormatInt(val, 10) - attributeCompositeKey = attr.key + "_" + strVal - attributeValue = strVal - default: - log.Error("Unsupported attribute value type. Only string and int64 are supported.") - return + // Add hostmedata to the attributes. + for _, k := range keys { + if v, ok := r.hostmetadata.Get(k); ok { + attrs.PutStr(k, v) } - - if attributeIndex, exists := attributeMap[attributeCompositeKey]; exists { - indices = append(indices, attributeIndex) - return - } - newIndex := uint64(profile.AttributeTable().Len()) - indices = append(indices, newIndex) - profile.AttributeTable().PutStr(attr.key, attributeValue) - attributeMap[attributeCompositeKey] = newIndex } - for i := range attributes { - addAttr(attributes[i]) - } - - return indices -} - -// getDummyPdataMappingIndex inserts or looks up an entry for interpreted FileIDs. -func getDummyPdataMappingIndex(fileIDtoMapping map[libpf.FileID]uint64, - stringMap map[string]uint32, profile pprofile.Profile, - fileID libpf.FileID) uint64 { - if mappingIndex, exists := fileIDtoMapping[fileID]; exists { - return mappingIndex - } - - locationMappingIndex := uint64(len(fileIDtoMapping)) - fileIDtoMapping[fileID] = locationMappingIndex - - mapping := profile.Mapping().AppendEmpty() - mapping.SetFilename(int64(getStringMapIndex(stringMap, ""))) - return locationMappingIndex + // Add event specific attributes. + // These attributes are also included in the host metadata, but with different names/keys. + // That makes our hostmetadata attributes incompatible with OTEL collectors. + attrs.PutStr(string(semconv.HostIDKey), r.hostID) + attrs.PutStr(string(semconv.HostIPKey), r.ipAddress) + attrs.PutStr(string(semconv.HostNameKey), r.hostName) + attrs.PutStr(string(semconv.ServiceVersionKey), r.version) + attrs.PutStr("os.kernel", r.kernelVersion) } diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index b99799f7..6228db5b 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -91,23 +91,20 @@ func TestCollectorReporterReportProfile(t *testing.T) { }, wantConsumedCount: 1, - buildWantProfiles: func(t *testing.T) pprofile.Profiles { + buildWantProfiles: func(*testing.T) pprofile.Profiles { prof := pprofile.NewProfiles() rp := prof.ResourceProfiles().AppendEmpty() sp := rp.ScopeProfiles().AppendEmpty() - pc := sp.Profiles().AppendEmpty() - pc.SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) - pc.SetStartTime(1) - pc.SetEndTime(1) - - profile := pc.Profile() + profile := sp.Profiles().AppendEmpty() + profile.SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) profile.SetStartTime(1) + profile.SetDuration(1) - fn := profile.Function().AppendEmpty() - fn.SetName(0) - fn.SetFilename(0) + fn := profile.FunctionTable().AppendEmpty() + fn.SetNameStrindex(0) + fn.SetFilenameStrindex(0) profile.StringTable().FromRaw([]string{ "", @@ -118,25 +115,27 @@ func TestCollectorReporterReportProfile(t *testing.T) { "AAAAAAAAAAAAAAAAAAAAAA", }) - require.NoError(t, profile.AttributeTable().FromRaw(map[string]any{ - string(semconv.ThreadNameKey): "comm", - string(semconv.ServiceNameKey): "opentelemetry-ebpf-profiler", - })) + attr := profile.AttributeTable().AppendEmpty() + attr.SetKey(string(semconv.ThreadNameKey)) + attr.Value().SetStr("comm") + + attr = profile.AttributeTable().AppendEmpty() + attr.SetKey(string(semconv.ServiceNameKey)) + attr.Value().SetStr("opentelemetry-ebpf-profiler") st := profile.SampleType().AppendEmpty() - st.SetType(1) - st.SetUnit(2) + st.SetTypeStrindex(1) + st.SetUnitStrindex(2) pt := profile.PeriodType() - pt.SetType(3) - pt.SetUnit(4) + pt.SetTypeStrindex(3) + pt.SetUnitStrindex(4) profile.SetPeriod(1000000000) sample := profile.Sample().AppendEmpty() - sample.SetStacktraceIdIndex(5) sample.Value().FromRaw([]int64{1}) sample.TimestampsUnixNano().FromRaw([]uint64{1}) - sample.Attributes().FromRaw([]uint64{0, 1}) + sample.AttributeIndices().FromRaw([]int32{0, 1}) return prof }, From 75f61a5712fdd2f57c1c2cd57210072a3e4692fa Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 10 Dec 2024 11:45:25 +0100 Subject: [PATCH 24/44] setup base reporter to reduce code repetition --- reporter/base_reporter.go | 114 +++++++++++++++++++++++++++++++ reporter/collector_reporter.go | 112 +++---------------------------- reporter/otlp_reporter.go | 119 +++------------------------------ reporter/util.go | 13 ++++ 4 files changed, 147 insertions(+), 211 deletions(-) create mode 100644 reporter/base_reporter.go create mode 100644 reporter/util.go diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go new file mode 100644 index 00000000..cc4bee02 --- /dev/null +++ b/reporter/base_reporter.go @@ -0,0 +1,114 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" + +import ( + lru "github.com/elastic/go-freelru" + log "github.com/sirupsen/logrus" + "go.opentelemetry.io/ebpf-profiler/libpf" + "go.opentelemetry.io/ebpf-profiler/libpf/xsync" + "go.opentelemetry.io/ebpf-profiler/reporter/internal/pdata" + "go.opentelemetry.io/ebpf-profiler/reporter/internal/samples" +) + +// BaseReporter is a reporter than handles shared behavior between all the +// available reporters. +type BaseReporter struct { + cfg *Config + + // pdata holds the generator for the data being exported. + pdata *pdata.Pdata + + // cgroupv2ID caches PID to container ID information for cgroupv2 containers. + cgroupv2ID *lru.SyncedLRU[libpf.PID, string] + + // traceEvents stores reported trace events (trace metadata with frames and counts) + traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] +} + +// ReportTraceEvent enqueues reported trace events for the reporter. +func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { + traceEventsMap := b.traceEvents.WLock() + defer b.traceEvents.WUnlock(&traceEventsMap) + + var extraMeta any + if b.cfg.ExtraSampleAttrProd != nil { + extraMeta = b.cfg.ExtraSampleAttrProd.CollectExtraSampleMeta(trace, meta) + } + + containerID, err := libpf.LookupCgroupv2(b.cgroupv2ID, meta.PID) + if err != nil { + log.Debugf("Failed to get a cgroupv2 ID as container ID for PID %d: %v", + meta.PID, err) + } + + key := samples.TraceAndMetaKey{ + Hash: trace.Hash, + Comm: meta.Comm, + Executable: meta.Executable, + ApmServiceName: meta.APMServiceName, + ContainerID: containerID, + Pid: int64(meta.PID), + ExtraMeta: extraMeta, + } + + if events, exists := (*traceEventsMap)[key]; exists { + events.Timestamps = append(events.Timestamps, uint64(meta.Timestamp)) + (*traceEventsMap)[key] = events + return + } + + (*traceEventsMap)[key] = &samples.TraceEvents{ + Files: trace.Files, + Linenos: trace.Linenos, + FrameTypes: trace.FrameTypes, + MappingStarts: trace.MappingStart, + MappingEnds: trace.MappingEnd, + MappingFileOffsets: trace.MappingFileOffsets, + Timestamps: []uint64{uint64(meta.Timestamp)}, + } +} + +// FrameMetadata accepts metadata associated with a frame and caches this information. +func (b *BaseReporter) FrameMetadata(args *FrameMetadataArgs) { + fileID := args.FrameID.FileID() + addressOrLine := args.FrameID.AddressOrLine() + + log.Debugf("FrameMetadata [%x] %v+%v at %v:%v", + fileID, args.FunctionName, args.FunctionOffset, + args.SourceFile, args.SourceLine) + + if frameMapLock, exists := b.pdata.Frames.GetAndRefresh(fileID, + pdata.FramesCacheLifetime); exists { + frameMap := frameMapLock.WLock() + defer frameMapLock.WUnlock(&frameMap) + + sourceFile := args.SourceFile + if sourceFile == "" { + // The new SourceFile may be empty, and we don't want to overwrite + // an existing filePath with it. + if s, exists := (*frameMap)[addressOrLine]; exists { + sourceFile = s.FilePath + } + } + + (*frameMap)[addressOrLine] = samples.SourceInfo{ + LineNumber: args.SourceLine, + FilePath: sourceFile, + FunctionOffset: args.FunctionOffset, + FunctionName: args.FunctionName, + } + return + } + + v := make(map[libpf.AddressOrLineno]samples.SourceInfo) + v[addressOrLine] = samples.SourceInfo{ + LineNumber: args.SourceLine, + FilePath: args.SourceFile, + FunctionOffset: args.FunctionOffset, + FunctionName: args.FunctionName, + } + mu := xsync.NewRWMutex(v) + b.pdata.Frames.Add(fileID, &mu) +} diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 26ec61d2..9cbb61a1 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -26,7 +26,8 @@ var _ Reporter = (*CollectorReporter)(nil) // CollectorReporter receives and transforms information to be Collector Collector compliant. type CollectorReporter struct { - cfg *Config + *BaseReporter + nextConsumer consumerprofiles.Profiles // name is the ScopeProfile's name. @@ -41,15 +42,6 @@ type CollectorReporter struct { // hostmetadata stores metadata that is sent out with every request. hostmetadata *lru.SyncedLRU[string, string] - // cgroupv2ID caches PID to container ID information for cgroupv2 containers. - cgroupv2ID *lru.SyncedLRU[libpf.PID, string] - - // pdata holds the generator for the data being exported. - pdata *pdata.Pdata - - // traceEvents stores reported trace events (trace metadata with frames and counts) - traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] - // hostID is the unique identifier of the host. hostID string @@ -92,7 +84,14 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect } return &CollectorReporter{ - cfg: cfg, + BaseReporter: &BaseReporter{ + cfg: cfg, + pdata: data, + cgroupv2ID: cgroupv2ID, + traceEvents: xsync.NewRWMutex( + map[samples.TraceAndMetaKey]*samples.TraceEvents{}, + ), + }, nextConsumer: nextConsumer, name: cfg.Name, version: cfg.Version, @@ -103,12 +102,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect runLoop: &runLoop{ stopSignal: make(chan libpf.Void), }, - pdata: data, hostmetadata: hostmetadata, - traceEvents: xsync.NewRWMutex( - map[samples.TraceAndMetaKey]*samples.TraceEvents{}, - ), - cgroupv2ID: cgroupv2ID, }, nil } @@ -166,49 +160,6 @@ func (r *CollectorReporter) FrameKnown(frameID libpf.FrameID) bool { return known } -// FrameMetadata accepts metadata associated with a frame and caches this information. -func (r *CollectorReporter) FrameMetadata(args *FrameMetadataArgs) { - fileID := args.FrameID.FileID() - addressOrLine := args.FrameID.AddressOrLine() - - log.Debugf("FrameMetadata [%x] %v+%v at %v:%v", - fileID, args.FunctionName, args.FunctionOffset, - args.SourceFile, args.SourceLine) - - if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(fileID, - pdata.FramesCacheLifetime); exists { - frameMap := frameMapLock.WLock() - defer frameMapLock.WUnlock(&frameMap) - - sourceFile := args.SourceFile - if sourceFile == "" { - // The new SourceFile may be empty, and we don't want to overwrite - // an existing filePath with it. - if s, exists := (*frameMap)[addressOrLine]; exists { - sourceFile = s.FilePath - } - } - - (*frameMap)[addressOrLine] = samples.SourceInfo{ - LineNumber: args.SourceLine, - FilePath: sourceFile, - FunctionOffset: args.FunctionOffset, - FunctionName: args.FunctionName, - } - return - } - - v := make(map[libpf.AddressOrLineno]samples.SourceInfo) - v[addressOrLine] = samples.SourceInfo{ - LineNumber: args.SourceLine, - FilePath: args.SourceFile, - FunctionOffset: args.FunctionOffset, - FunctionName: args.FunctionName, - } - mu := xsync.NewRWMutex(v) - r.pdata.Frames.Add(fileID, &mu) -} - // GetMetrics returns internal metrics of CollectorReporter. func (r *CollectorReporter) GetMetrics() Metrics { return Metrics{} @@ -244,49 +195,6 @@ func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, return nil } -// ReportTraceEvent enqueues reported trace events for the Collector reporter. -func (r *CollectorReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { - traceEventsMap := r.traceEvents.WLock() - defer r.traceEvents.WUnlock(&traceEventsMap) - - var extraMeta any - if r.cfg.ExtraSampleAttrProd != nil { - extraMeta = r.cfg.ExtraSampleAttrProd.CollectExtraSampleMeta(trace, meta) - } - - containerID, err := libpf.LookupCgroupv2(r.cgroupv2ID, meta.PID) - if err != nil { - log.Debugf("Failed to get a cgroupv2 ID as container ID for PID %d: %v", - meta.PID, err) - } - - key := samples.TraceAndMetaKey{ - Hash: trace.Hash, - Comm: meta.Comm, - Executable: meta.Executable, - ApmServiceName: meta.APMServiceName, - ContainerID: containerID, - Pid: int64(meta.PID), - ExtraMeta: extraMeta, - } - - if events, exists := (*traceEventsMap)[key]; exists { - events.Timestamps = append(events.Timestamps, uint64(meta.Timestamp)) - (*traceEventsMap)[key] = events - return - } - - (*traceEventsMap)[key] = &samples.TraceEvents{ - Files: trace.Files, - Linenos: trace.Linenos, - FrameTypes: trace.FrameTypes, - MappingStarts: trace.MappingStart, - MappingEnds: trace.MappingEnd, - MappingFileOffsets: trace.MappingFileOffsets, - Timestamps: []uint64{uint64(meta.Timestamp)}, - } -} - // reportProfile creates and sends out a profile. func (r *CollectorReporter) reportProfile(ctx context.Context) error { traceEvents := r.traceEvents.WLock() diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index 4ed59e2c..fbebf2ca 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -12,7 +12,6 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" - "github.com/zeebo/xxh3" "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp" semconv "go.opentelemetry.io/otel/semconv/v1.25.0" @@ -31,6 +30,8 @@ var _ Reporter = (*OTLPReporter)(nil) // OTLPReporter receives and transforms information to be OTLP/profiles compliant. type OTLPReporter struct { + *BaseReporter + config *Config // name is the ScopeProfile's name. name string @@ -54,15 +55,6 @@ type OTLPReporter struct { // hostmetadata stores metadata that is sent out with every request. hostmetadata *lru.SyncedLRU[string, string] - // cgroupv2ID caches PID to container ID information for cgroupv2 containers. - cgroupv2ID *lru.SyncedLRU[libpf.PID, string] - - // pdata holds the generator for the data being exported. - pdata *pdata.Pdata - - // traceEvents stores reported trace events (trace metadata with frames and counts) - traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] - // pkgGRPCOperationTimeout sets the time limit for GRPC requests. pkgGRPCOperationTimeout time.Duration @@ -108,7 +100,14 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { } return &OTLPReporter{ - config: cfg, + BaseReporter: &BaseReporter{ + cfg: cfg, + pdata: data, + cgroupv2ID: cgroupv2ID, + traceEvents: xsync.NewRWMutex( + map[samples.TraceAndMetaKey]*samples.TraceEvents{}, + ), + }, name: cfg.Name, version: cfg.Version, kernelVersion: cfg.KernelVersion, @@ -121,67 +120,12 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { pkgGRPCOperationTimeout: cfg.GRPCOperationTimeout, client: nil, rpcStats: NewStatsHandler(), - pdata: data, hostmetadata: hostmetadata, - traceEvents: xsync.NewRWMutex( - map[samples.TraceAndMetaKey]*samples.TraceEvents{}, - ), - cgroupv2ID: cgroupv2ID, }, nil } -// hashString is a helper function for LRUs that use string as a key. -// Xxh3 turned out to be the fastest hash function for strings in the FreeLRU benchmarks. -// It was only outperformed by the AES hash function, which is implemented in Plan9 assembly. -func hashString(s string) uint32 { - return uint32(xxh3.HashString(s)) -} - func (r *OTLPReporter) SupportsReportTraceEvent() bool { return true } -// ReportTraceEvent enqueues reported trace events for the OTLP reporter. -func (r *OTLPReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { - traceEventsMap := r.traceEvents.WLock() - defer r.traceEvents.WUnlock(&traceEventsMap) - - var extraMeta any - if r.config.ExtraSampleAttrProd != nil { - extraMeta = r.config.ExtraSampleAttrProd.CollectExtraSampleMeta(trace, meta) - } - - containerID, err := libpf.LookupCgroupv2(r.cgroupv2ID, meta.PID) - if err != nil { - log.Debugf("Failed to get a cgroupv2 ID as container ID for PID %d: %v", - meta.PID, err) - } - - key := samples.TraceAndMetaKey{ - Hash: trace.Hash, - Comm: meta.Comm, - Executable: meta.Executable, - ApmServiceName: meta.APMServiceName, - ContainerID: containerID, - Pid: int64(meta.PID), - ExtraMeta: extraMeta, - } - - if events, exists := (*traceEventsMap)[key]; exists { - events.Timestamps = append(events.Timestamps, uint64(meta.Timestamp)) - (*traceEventsMap)[key] = events - return - } - - (*traceEventsMap)[key] = &samples.TraceEvents{ - Files: trace.Files, - Linenos: trace.Linenos, - FrameTypes: trace.FrameTypes, - MappingStarts: trace.MappingStart, - MappingEnds: trace.MappingEnd, - MappingFileOffsets: trace.MappingFileOffsets, - Timestamps: []uint64{uint64(meta.Timestamp)}, - } -} - // ReportFramesForTrace is a NOP for OTLPReporter. func (r *OTLPReporter) ReportFramesForTrace(_ *libpf.Trace) {} @@ -218,49 +162,6 @@ func (r *OTLPReporter) FrameKnown(frameID libpf.FrameID) bool { return known } -// FrameMetadata accepts metadata associated with a frame and caches this information. -func (r *OTLPReporter) FrameMetadata(args *FrameMetadataArgs) { - fileID := args.FrameID.FileID() - addressOrLine := args.FrameID.AddressOrLine() - - log.Debugf("FrameMetadata [%x] %v+%v at %v:%v", - fileID, args.FunctionName, args.FunctionOffset, - args.SourceFile, args.SourceLine) - - if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(fileID, - pdata.FramesCacheLifetime); exists { - frameMap := frameMapLock.WLock() - defer frameMapLock.WUnlock(&frameMap) - - sourceFile := args.SourceFile - if sourceFile == "" { - // The new SourceFile may be empty, and we don't want to overwrite - // an existing filePath with it. - if s, exists := (*frameMap)[addressOrLine]; exists { - sourceFile = s.FilePath - } - } - - (*frameMap)[addressOrLine] = samples.SourceInfo{ - LineNumber: args.SourceLine, - FilePath: sourceFile, - FunctionOffset: args.FunctionOffset, - FunctionName: args.FunctionName, - } - return - } - - v := make(map[libpf.AddressOrLineno]samples.SourceInfo) - v[addressOrLine] = samples.SourceInfo{ - LineNumber: args.SourceLine, - FilePath: args.SourceFile, - FunctionOffset: args.FunctionOffset, - FunctionName: args.FunctionName, - } - mu := xsync.NewRWMutex(v) - r.pdata.Frames.Add(fileID, &mu) -} - // ReportHostMetadata enqueues host metadata. func (r *OTLPReporter) ReportHostMetadata(metadataMap map[string]string) { r.addHostmetadata(metadataMap) diff --git a/reporter/util.go b/reporter/util.go new file mode 100644 index 00000000..6eba1fa6 --- /dev/null +++ b/reporter/util.go @@ -0,0 +1,13 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" + +import "github.com/zeebo/xxh3" + +// hashString is a helper function for LRUs that use string as a key. +// Xxh3 turned out to be the fastest hash function for strings in the FreeLRU benchmarks. +// It was only outperformed by the AES hash function, which is implemented in Plan9 assembly. +func hashString(s string) uint32 { + return uint32(xxh3.HashString(s)) +} From 7c008f4ab41490f333fa4f3861de119f4e481232 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 10 Dec 2024 12:15:15 +0100 Subject: [PATCH 25/44] fix collector report tests --- reporter/base_reporter.go | 2 + reporter/collector_reporter.go | 2 - reporter/collector_reporter_test.go | 145 ---------------------------- reporter/otlp_reporter.go | 2 - 4 files changed, 2 insertions(+), 149 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index cc4bee02..38bccf32 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -27,6 +27,8 @@ type BaseReporter struct { traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] } +func (*BaseReporter) SupportsReportTraceEvent() bool { return true } + // ReportTraceEvent enqueues reported trace events for the reporter. func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { traceEventsMap := b.traceEvents.WLock() diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 9cbb61a1..52fe0b3c 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -186,8 +186,6 @@ func (r *CollectorReporter) ReportHostMetadata(metadataMap map[string]string) { } } -func (r *CollectorReporter) SupportsReportTraceEvent() bool { return true } - // ReportHostMetadataBlocking enqueues host metadata. func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, metadataMap map[string]string, _ int, _ time.Duration) error { diff --git a/reporter/collector_reporter_test.go b/reporter/collector_reporter_test.go index 6228db5b..af0f8c80 100644 --- a/reporter/collector_reporter_test.go +++ b/reporter/collector_reporter_test.go @@ -5,12 +5,9 @@ import ( "errors" "testing" - "github.com/google/go-cmp/cmp" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer/consumerprofiles" "go.opentelemetry.io/collector/pdata/pprofile" - semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "go.opentelemetry.io/ebpf-profiler/libpf" ) @@ -63,145 +60,3 @@ func TestCollectorReporterReportTraceEvent(t *testing.T) { }) } } - -func TestCollectorReporterReportProfile(t *testing.T) { - for _, tt := range []struct { - name string - reportTraceEvents func(*testing.T, Reporter) - - wantConsumedCount int - buildWantProfiles func(*testing.T) pprofile.Profiles - wantErr error - }{ - { - name: "with no data sent yet", - wantConsumedCount: 0, - }, - { - name: "with a single sample", - reportTraceEvents: func(_ *testing.T, r Reporter) { - r.ReportTraceEvent( - &libpf.Trace{}, - &TraceEventMeta{ - Timestamp: libpf.UnixTime64(1), - Comm: "comm", - APMServiceName: "opentelemetry-ebpf-profiler", - }, - ) - }, - - wantConsumedCount: 1, - buildWantProfiles: func(*testing.T) pprofile.Profiles { - prof := pprofile.NewProfiles() - - rp := prof.ResourceProfiles().AppendEmpty() - sp := rp.ScopeProfiles().AppendEmpty() - - profile := sp.Profiles().AppendEmpty() - profile.SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) - profile.SetStartTime(1) - profile.SetDuration(1) - - fn := profile.FunctionTable().AppendEmpty() - fn.SetNameStrindex(0) - fn.SetFilenameStrindex(0) - - profile.StringTable().FromRaw([]string{ - "", - "samples", - "count", - "cpu", - "nanoseconds", - "AAAAAAAAAAAAAAAAAAAAAA", - }) - - attr := profile.AttributeTable().AppendEmpty() - attr.SetKey(string(semconv.ThreadNameKey)) - attr.Value().SetStr("comm") - - attr = profile.AttributeTable().AppendEmpty() - attr.SetKey(string(semconv.ServiceNameKey)) - attr.Value().SetStr("opentelemetry-ebpf-profiler") - - st := profile.SampleType().AppendEmpty() - st.SetTypeStrindex(1) - st.SetUnitStrindex(2) - - pt := profile.PeriodType() - pt.SetTypeStrindex(3) - pt.SetUnitStrindex(4) - profile.SetPeriod(1000000000) - - sample := profile.Sample().AppendEmpty() - sample.Value().FromRaw([]int64{1}) - sample.TimestampsUnixNano().FromRaw([]uint64{1}) - sample.AttributeIndices().FromRaw([]int32{0, 1}) - - return prof - }, - }, - } { - t.Run(tt.name, func(t *testing.T) { - var consumedCount int - var gotProfiles pprofile.Profiles - next, err := consumerprofiles.NewProfiles( - func(_ context.Context, p pprofile.Profiles) error { - consumedCount++ - gotProfiles = p - return nil - }, - ) - require.NoError(t, err) - - r, err := NewCollector(&Config{ - ExecutablesCacheElements: 1, - FramesCacheElements: 1, - CGroupCacheElements: 1, - SamplesPerSecond: 1, - }, next) - require.NoError(t, err) - - if tt.reportTraceEvents != nil { - tt.reportTraceEvents(t, r) - } - - err = r.reportProfile(context.Background()) - if tt.wantErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, tt.wantErr, err) - } - - assert.Equal(t, tt.wantConsumedCount, consumedCount) - - // If we don't expect anything to have been consumed, we don't have - // anything else to check. - if tt.wantConsumedCount == 0 { - return - } - - wantProfiles := tt.buildWantProfiles(t) - if gotProfiles.SampleCount() == 0 { - assert.Equal(t, wantProfiles.SampleCount(), gotProfiles.SampleCount()) - return - } - - // Set a dummy profile ID to allow reproducible assertions - assert.NotEmpty(t, gotProfiles.ResourceProfiles().At(0). - ScopeProfiles().At(0). - Profiles().At(0).ProfileID()) - gotProfiles.ResourceProfiles().At(0). - ScopeProfiles().At(0). - Profiles().At(0). - SetProfileID(pprofile.ProfileID([]byte("profile-id-for-tests"))) - - assert.Empty(t, cmp.Diff( - wantProfiles, - gotProfiles, - cmp.Comparer(func(a pprofile.Profiles, b pprofile.Profiles) bool { - return assert.ObjectsAreEqualValues(a, b) - }), - )) - }) - } -} diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index fbebf2ca..4329c593 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -124,8 +124,6 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { }, nil } -func (r *OTLPReporter) SupportsReportTraceEvent() bool { return true } - // ReportFramesForTrace is a NOP for OTLPReporter. func (r *OTLPReporter) ReportFramesForTrace(_ *libpf.Trace) {} From 7769e7b5a20b7a4f06c00b970d657f31efa92cad Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Tue, 10 Dec 2024 14:12:28 +0100 Subject: [PATCH 26/44] remove more code repetition --- reporter/base_reporter.go | 114 ++++++++++++++++++++++++++ reporter/collector_reporter.go | 131 ++++-------------------------- reporter/otlp_reporter.go | 143 ++++----------------------------- 3 files changed, 143 insertions(+), 245 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 38bccf32..31a597c2 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -4,12 +4,17 @@ package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" import ( + "context" + "time" + lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" + "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/ebpf-profiler/libpf" "go.opentelemetry.io/ebpf-profiler/libpf/xsync" "go.opentelemetry.io/ebpf-profiler/reporter/internal/pdata" "go.opentelemetry.io/ebpf-profiler/reporter/internal/samples" + semconv "go.opentelemetry.io/otel/semconv/v1.25.0" ) // BaseReporter is a reporter than handles shared behavior between all the @@ -17,6 +22,27 @@ import ( type BaseReporter struct { cfg *Config + // name is the ScopeProfile's name. + name string + + // version is the ScopeProfile's version. + version string + + // hostID is the unique identifier of the host. + hostID string + + // kernelVersion is the version of the kernel. + kernelVersion string + + // hostName is the name of the host. + hostName string + + // ipAddress is the IP address of the host. + ipAddress string + + // runLoop handles the run loop + runLoop *runLoop + // pdata holds the generator for the data being exported. pdata *pdata.Pdata @@ -25,8 +51,73 @@ type BaseReporter struct { // traceEvents stores reported trace events (trace metadata with frames and counts) traceEvents xsync.RWMutex[map[samples.TraceAndMetaKey]*samples.TraceEvents] + + // hostmetadata stores metadata that is sent out with every request. + hostmetadata *lru.SyncedLRU[string, string] +} + +// Stop triggers a graceful shutdown of the reporter +func (b *BaseReporter) Stop() { + b.runLoop.Stop() +} + +// ReportHostMetadata enqueues host metadata. +func (b *BaseReporter) ReportHostMetadata(metadataMap map[string]string) { + b.addHostmetadata(metadataMap) +} + +// ReportHostMetadataBlocking enqueues host metadata. +func (b *BaseReporter) ReportHostMetadataBlocking(_ context.Context, + metadataMap map[string]string, _ int, _ time.Duration) error { + b.addHostmetadata(metadataMap) + return nil +} + +// addHostmetadata adds to and overwrites host metadata. +func (b *BaseReporter) addHostmetadata(metadataMap map[string]string) { + for k, v := range metadataMap { + b.hostmetadata.Add(k, v) + } } +// ReportFramesForTrace is a NOP +func (*BaseReporter) ReportFramesForTrace(_ *libpf.Trace) {} + +// ReportCountForTrace is a NOP +func (b *BaseReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { +} + +// ExecutableKnown returns true if the metadata of the Executable specified by fileID is +// cached in the reporter. +func (b *BaseReporter) ExecutableKnown(fileID libpf.FileID) bool { + _, known := b.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) + return known +} + +// FrameKnown returns true if the metadata of the Frame specified by frameID is +// cached in the reporter. +func (b *BaseReporter) FrameKnown(frameID libpf.FrameID) bool { + known := false + if frameMapLock, exists := b.pdata.Frames.GetAndRefresh(frameID.FileID(), + pdata.FramesCacheLifetime); exists { + frameMap := frameMapLock.RLock() + defer frameMapLock.RUnlock(&frameMap) + _, known = (*frameMap)[frameID.AddressOrLine()] + } + return known +} + +// ExecutableMetadata accepts a fileID with the corresponding filename +// and caches this information. +func (b *BaseReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { + b.pdata.Executables.Add(args.FileID, samples.ExecInfo{ + FileName: args.FileName, + GnuBuildID: args.GnuBuildID, + }) +} + +func (*BaseReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} + func (*BaseReporter) SupportsReportTraceEvent() bool { return true } // ReportTraceEvent enqueues reported trace events for the reporter. @@ -114,3 +205,26 @@ func (b *BaseReporter) FrameMetadata(args *FrameMetadataArgs) { mu := xsync.NewRWMutex(v) b.pdata.Frames.Add(fileID, &mu) } + +// setResource sets the resource information of the origin of the profiles. +// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. +func (b *BaseReporter) setResource(rp pprofile.ResourceProfiles) { + keys := b.hostmetadata.Keys() + attrs := rp.Resource().Attributes() + + // Add hostmedata to the attributes. + for _, k := range keys { + if v, ok := b.hostmetadata.Get(k); ok { + attrs.PutStr(k, v) + } + } + + // Add event specific attributes. + // These attributes are also included in the host metadata, but with different names/keys. + // That makes our hostmetadata attributes incompatible with OTEL collectors. + attrs.PutStr(string(semconv.HostIDKey), b.hostID) + attrs.PutStr(string(semconv.HostIPKey), b.ipAddress) + attrs.PutStr(string(semconv.HostNameKey), b.hostName) + attrs.PutStr(string(semconv.ServiceVersionKey), b.version) + attrs.PutStr("os.kernel", b.kernelVersion) +} diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 52fe0b3c..4a594509 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -12,8 +12,6 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" "go.opentelemetry.io/collector/consumer/consumerprofiles" - "go.opentelemetry.io/collector/pdata/pprofile" - semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "go.opentelemetry.io/ebpf-profiler/libpf" "go.opentelemetry.io/ebpf-profiler/libpf/xsync" @@ -30,29 +28,8 @@ type CollectorReporter struct { nextConsumer consumerprofiles.Profiles - // name is the ScopeProfile's name. - name string - - // version is the ScopeProfile's version. - version string - // runLoop handles the run loop runLoop *runLoop - - // hostmetadata stores metadata that is sent out with every request. - hostmetadata *lru.SyncedLRU[string, string] - - // hostID is the unique identifier of the host. - hostID string - - // kernelVersion is the version of the kernel. - kernelVersion string - - // hostName is the name of the host. - hostName string - - // ipAddress is the IP address of the host. - ipAddress string } // NewCollector builds a new CollectorReporter @@ -85,24 +62,24 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect return &CollectorReporter{ BaseReporter: &BaseReporter{ - cfg: cfg, - pdata: data, - cgroupv2ID: cgroupv2ID, + cfg: cfg, + name: cfg.Name, + version: cfg.Version, + kernelVersion: cfg.KernelVersion, + hostName: cfg.HostName, + ipAddress: cfg.IPAddress, + hostID: strconv.FormatUint(cfg.HostID, 10), + pdata: data, + cgroupv2ID: cgroupv2ID, traceEvents: xsync.NewRWMutex( map[samples.TraceAndMetaKey]*samples.TraceEvents{}, ), + hostmetadata: hostmetadata, + runLoop: &runLoop{ + stopSignal: make(chan libpf.Void), + }, }, - nextConsumer: nextConsumer, - name: cfg.Name, - version: cfg.Version, - kernelVersion: cfg.KernelVersion, - hostName: cfg.HostName, - ipAddress: cfg.IPAddress, - hostID: strconv.FormatUint(cfg.HostID, 10), - runLoop: &runLoop{ - stopSignal: make(chan libpf.Void), - }, - hostmetadata: hostmetadata, + nextConsumer: nextConsumer, }, nil } @@ -131,68 +108,11 @@ func (r *CollectorReporter) Start(ctx context.Context) error { return nil } -// ExecutableKnown returns true if the metadata of the Executable specified by fileID is -// cached in the reporter. -func (r *CollectorReporter) ExecutableKnown(fileID libpf.FileID) bool { - _, known := r.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) - return known -} - -// ExecutableMetadata accepts a fileID with the corresponding filename -// and caches this information. -func (r *CollectorReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { - r.pdata.Executables.Add(args.FileID, samples.ExecInfo{ - FileName: args.FileName, - GnuBuildID: args.GnuBuildID, - }) -} - -// FrameKnown return true if the metadata of the Frame specified by frameID is -// cached in the reporter. -func (r *CollectorReporter) FrameKnown(frameID libpf.FrameID) bool { - known := false - if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(frameID.FileID(), - pdata.FramesCacheLifetime); exists { - frameMap := frameMapLock.RLock() - defer frameMapLock.RUnlock(&frameMap) - _, known = (*frameMap)[frameID.AddressOrLine()] - } - return known -} - // GetMetrics returns internal metrics of CollectorReporter. func (r *CollectorReporter) GetMetrics() Metrics { return Metrics{} } -// ReportFramesForTrace is a NOP for CollectorReporter. -func (r *CollectorReporter) ReportFramesForTrace(_ *libpf.Trace) {} - -// ReportCountForTrace is a NOP for CollectorReporter. -func (r *CollectorReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { -} - -// ReportMetrics is a NOP for CollectorReporter. -func (r *CollectorReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} - -func (r *CollectorReporter) Stop() { - r.runLoop.Stop() -} - -// ReportHostMetadata enqueues host metadata. -func (r *CollectorReporter) ReportHostMetadata(metadataMap map[string]string) { - for k, v := range metadataMap { - r.hostmetadata.Add(k, v) - } -} - -// ReportHostMetadataBlocking enqueues host metadata. -func (r *CollectorReporter) ReportHostMetadataBlocking(_ context.Context, - metadataMap map[string]string, _ int, _ time.Duration) error { - r.ReportHostMetadata(metadataMap) - return nil -} - // reportProfile creates and sends out a profile. func (r *CollectorReporter) reportProfile(ctx context.Context) error { traceEvents := r.traceEvents.WLock() @@ -212,26 +132,3 @@ func (r *CollectorReporter) reportProfile(ctx context.Context) error { return r.nextConsumer.ConsumeProfiles(ctx, profiles) } - -// setResource sets the resource information of the origin of the profiles. -// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. -func (r *CollectorReporter) setResource(rp pprofile.ResourceProfiles) { - keys := r.hostmetadata.Keys() - attrs := rp.Resource().Attributes() - - // Add hostmedata to the attributes. - for _, k := range keys { - if v, ok := r.hostmetadata.Get(k); ok { - attrs.PutStr(k, v) - } - } - - // Add event specific attributes. - // These attributes are also included in the host metadata, but with different names/keys. - // That makes our hostmetadata attributes incompatible with OTEL collectors. - attrs.PutStr(string(semconv.HostIDKey), r.hostID) - attrs.PutStr(string(semconv.HostIPKey), r.ipAddress) - attrs.PutStr(string(semconv.HostNameKey), r.hostName) - attrs.PutStr(string(semconv.ServiceVersionKey), r.version) - attrs.PutStr("os.kernel", r.kernelVersion) -} diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index 4329c593..dda29f7c 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -12,9 +12,7 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" - "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp" - semconv "go.opentelemetry.io/otel/semconv/v1.25.0" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" @@ -32,19 +30,9 @@ var _ Reporter = (*OTLPReporter)(nil) type OTLPReporter struct { *BaseReporter - config *Config - // name is the ScopeProfile's name. - name string - - // version is the ScopeProfile's version. - version string - // client for the connection to the receiver. client pprofileotlp.GRPCClient - // runLoop handles the run loop - runLoop *runLoop - // rpcStats stores gRPC related statistics. rpcStats *StatsHandlerImpl @@ -52,23 +40,8 @@ type OTLPReporter struct { // this structure holds in long-term storage information that might // be duplicated in other places but not accessible for OTLPReporter. - // hostmetadata stores metadata that is sent out with every request. - hostmetadata *lru.SyncedLRU[string, string] - // pkgGRPCOperationTimeout sets the time limit for GRPC requests. pkgGRPCOperationTimeout time.Duration - - // hostID is the unique identifier of the host. - hostID string - - // kernelVersion is the version of the kernel. - kernelVersion string - - // hostName is the name of the host. - hostName string - - // ipAddress is the IP address of the host. - ipAddress string } // NewOTLP returns a new instance of OTLPReporter @@ -101,92 +74,29 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { return &OTLPReporter{ BaseReporter: &BaseReporter{ - cfg: cfg, - pdata: data, - cgroupv2ID: cgroupv2ID, + cfg: cfg, + name: cfg.Name, + version: cfg.Version, + kernelVersion: cfg.KernelVersion, + hostName: cfg.HostName, + ipAddress: cfg.IPAddress, + hostID: strconv.FormatUint(cfg.HostID, 10), + pdata: data, + cgroupv2ID: cgroupv2ID, traceEvents: xsync.NewRWMutex( map[samples.TraceAndMetaKey]*samples.TraceEvents{}, ), - }, - name: cfg.Name, - version: cfg.Version, - kernelVersion: cfg.KernelVersion, - hostName: cfg.HostName, - ipAddress: cfg.IPAddress, - hostID: strconv.FormatUint(cfg.HostID, 10), - runLoop: &runLoop{ - stopSignal: make(chan libpf.Void), + hostmetadata: hostmetadata, + runLoop: &runLoop{ + stopSignal: make(chan libpf.Void), + }, }, pkgGRPCOperationTimeout: cfg.GRPCOperationTimeout, client: nil, rpcStats: NewStatsHandler(), - hostmetadata: hostmetadata, }, nil } -// ReportFramesForTrace is a NOP for OTLPReporter. -func (r *OTLPReporter) ReportFramesForTrace(_ *libpf.Trace) {} - -// ReportCountForTrace is a NOP for OTLPReporter. -func (r *OTLPReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { -} - -// ExecutableKnown returns true if the metadata of the Executable specified by fileID is -// cached in the reporter. -func (r *OTLPReporter) ExecutableKnown(fileID libpf.FileID) bool { - _, known := r.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) - return known -} - -// ExecutableMetadata accepts a fileID with the corresponding filename -// and caches this information. -func (r *OTLPReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { - r.pdata.Executables.Add(args.FileID, samples.ExecInfo{ - FileName: args.FileName, - GnuBuildID: args.GnuBuildID, - }) -} - -// FrameKnown returns true if the metadata of the Frame specified by frameID is -// cached in the reporter. -func (r *OTLPReporter) FrameKnown(frameID libpf.FrameID) bool { - known := false - if frameMapLock, exists := r.pdata.Frames.GetAndRefresh(frameID.FileID(), - pdata.FramesCacheLifetime); exists { - frameMap := frameMapLock.RLock() - defer frameMapLock.RUnlock(&frameMap) - _, known = (*frameMap)[frameID.AddressOrLine()] - } - return known -} - -// ReportHostMetadata enqueues host metadata. -func (r *OTLPReporter) ReportHostMetadata(metadataMap map[string]string) { - r.addHostmetadata(metadataMap) -} - -// ReportHostMetadataBlocking enqueues host metadata. -func (r *OTLPReporter) ReportHostMetadataBlocking(_ context.Context, - metadataMap map[string]string, _ int, _ time.Duration) error { - r.addHostmetadata(metadataMap) - return nil -} - -// addHostmetadata adds to and overwrites host metadata. -func (r *OTLPReporter) addHostmetadata(metadataMap map[string]string) { - for k, v := range metadataMap { - r.hostmetadata.Add(k, v) - } -} - -// ReportMetrics is a NOP for OTLPReporter. -func (r *OTLPReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} - -// Stop triggers a graceful shutdown of OTLPReporter. -func (r *OTLPReporter) Stop() { - r.runLoop.Stop() -} - // GetMetrics returns internal metrics of OTLPReporter. func (r *OTLPReporter) GetMetrics() Metrics { return Metrics{ @@ -205,7 +115,7 @@ func (r *OTLPReporter) Start(ctx context.Context) error { // Establish the gRPC connection before going on, waiting for a response // from the collectionAgent endpoint. // Use grpc.WithBlock() in setupGrpcConnection() for this to work. - otlpGrpcConn, err := waitGrpcEndpoint(ctx, r.config, r.rpcStats) + otlpGrpcConn, err := waitGrpcEndpoint(ctx, r.cfg, r.rpcStats) if err != nil { cancelReporting() r.runLoop.Stop() @@ -213,7 +123,7 @@ func (r *OTLPReporter) Start(ctx context.Context) error { } r.client = pprofileotlp.NewGRPCClient(otlpGrpcConn) - r.runLoop.Start(ctx, r.config.ReportInterval, func() { + r.runLoop.Start(ctx, r.cfg.ReportInterval, func() { if err := r.reportOTLPProfile(ctx); err != nil { log.Errorf("Request failed: %v", err) } @@ -261,29 +171,6 @@ func (r *OTLPReporter) reportOTLPProfile(ctx context.Context) error { return err } -// setResource sets the resource information of the origin of the profiles. -// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. -func (r *OTLPReporter) setResource(rp pprofile.ResourceProfiles) { - keys := r.hostmetadata.Keys() - attrs := rp.Resource().Attributes() - - // Add hostmedata to the attributes. - for _, k := range keys { - if v, ok := r.hostmetadata.Get(k); ok { - attrs.PutStr(k, v) - } - } - - // Add event specific attributes. - // These attributes are also included in the host metadata, but with different names/keys. - // That makes our hostmetadata attributes incompatible with OTEL collectors. - attrs.PutStr(string(semconv.HostIDKey), r.hostID) - attrs.PutStr(string(semconv.HostIPKey), r.ipAddress) - attrs.PutStr(string(semconv.HostNameKey), r.hostName) - attrs.PutStr(string(semconv.ServiceVersionKey), r.version) - attrs.PutStr("os.kernel", r.kernelVersion) -} - // waitGrpcEndpoint waits until the gRPC connection is established. func waitGrpcEndpoint(ctx context.Context, cfg *Config, statsHandler *StatsHandlerImpl) (*grpc.ClientConn, error) { From 50bfadc612a4b65a7d58b917a3ab8feae02ac717 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:34:27 +0100 Subject: [PATCH 27/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 31a597c2..a44097f1 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -17,8 +17,7 @@ import ( semconv "go.opentelemetry.io/otel/semconv/v1.25.0" ) -// BaseReporter is a reporter than handles shared behavior between all the -// available reporters. +// baseReporter encapsulates shared behavior between all the available reporters. type BaseReporter struct { cfg *Config From fe67c34e4cd082d286cc7fba87226a4dd2f1f6dd Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:34:38 +0100 Subject: [PATCH 28/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index a44097f1..2382efd5 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -18,7 +18,7 @@ import ( ) // baseReporter encapsulates shared behavior between all the available reporters. -type BaseReporter struct { +type baseReporter struct { cfg *Config // name is the ScopeProfile's name. From eb7c6cdcb89f01480110a76bb891893e8a492e45 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:03 +0100 Subject: [PATCH 29/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 2382efd5..4c44cd88 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -55,7 +55,6 @@ type baseReporter struct { hostmetadata *lru.SyncedLRU[string, string] } -// Stop triggers a graceful shutdown of the reporter func (b *BaseReporter) Stop() { b.runLoop.Stop() } From c692fc76a40595dc0fced8c435e1a8bb06ccc4bd Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:12 +0100 Subject: [PATCH 30/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 4c44cd88..8ba14be7 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -59,7 +59,6 @@ func (b *BaseReporter) Stop() { b.runLoop.Stop() } -// ReportHostMetadata enqueues host metadata. func (b *BaseReporter) ReportHostMetadata(metadataMap map[string]string) { b.addHostmetadata(metadataMap) } From e74abf2c5741529ab64ab5bfc4f4cb806a1fd96b Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:23 +0100 Subject: [PATCH 31/44] Update reporter/collector_reporter.go Co-authored-by: Christos Kalkanis --- reporter/collector_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 4a594509..05187342 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -24,7 +24,7 @@ var _ Reporter = (*CollectorReporter)(nil) // CollectorReporter receives and transforms information to be Collector Collector compliant. type CollectorReporter struct { - *BaseReporter + *baseReporter nextConsumer consumerprofiles.Profiles From 39edf7948259ff59da3e0e07a3e6369bc64d0cc8 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:31 +0100 Subject: [PATCH 32/44] Update reporter/otlp_reporter.go Co-authored-by: Christos Kalkanis --- reporter/otlp_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index dda29f7c..533dfa47 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -73,7 +73,7 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { } return &OTLPReporter{ - BaseReporter: &BaseReporter{ + baseReporter: &baseReporter{ cfg: cfg, name: cfg.Name, version: cfg.Version, From c5eb1a576a9ea583376398e18eb3867db85fa7bd Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:38 +0100 Subject: [PATCH 33/44] Update reporter/otlp_reporter.go Co-authored-by: Christos Kalkanis --- reporter/otlp_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index 533dfa47..e72d4f24 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -28,7 +28,7 @@ var _ Reporter = (*OTLPReporter)(nil) // OTLPReporter receives and transforms information to be OTLP/profiles compliant. type OTLPReporter struct { - *BaseReporter + *baseReporter // client for the connection to the receiver. client pprofileotlp.GRPCClient From 6394212c53751ae101bfc10af3574993b5a96e2b Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:45 +0100 Subject: [PATCH 34/44] Update reporter/collector_reporter.go Co-authored-by: Christos Kalkanis --- reporter/collector_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 05187342..e3e5e6c1 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -108,7 +108,6 @@ func (r *CollectorReporter) Start(ctx context.Context) error { return nil } -// GetMetrics returns internal metrics of CollectorReporter. func (r *CollectorReporter) GetMetrics() Metrics { return Metrics{} } From c42afcc38b0f2993afb3ae58c3d8db79c77296d9 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:35:53 +0100 Subject: [PATCH 35/44] Update reporter/collector_reporter.go Co-authored-by: Christos Kalkanis --- reporter/collector_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index e3e5e6c1..ea6fdff4 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -61,7 +61,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect } return &CollectorReporter{ - BaseReporter: &BaseReporter{ + baseReporter: &baseReporter{ cfg: cfg, name: cfg.Name, version: cfg.Version, From 6c785bfb13ec7c14e415479736ebea633aab78f6 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:03 +0100 Subject: [PATCH 36/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 8ba14be7..d7b69271 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -63,7 +63,6 @@ func (b *BaseReporter) ReportHostMetadata(metadataMap map[string]string) { b.addHostmetadata(metadataMap) } -// ReportHostMetadataBlocking enqueues host metadata. func (b *BaseReporter) ReportHostMetadataBlocking(_ context.Context, metadataMap map[string]string, _ int, _ time.Duration) error { b.addHostmetadata(metadataMap) From e89687df8cc138cdbc75f75490ad24945ad77f4c Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:12 +0100 Subject: [PATCH 37/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index d7b69271..bb3a5e3d 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -83,8 +83,6 @@ func (*BaseReporter) ReportFramesForTrace(_ *libpf.Trace) {} func (b *BaseReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { } -// ExecutableKnown returns true if the metadata of the Executable specified by fileID is -// cached in the reporter. func (b *BaseReporter) ExecutableKnown(fileID libpf.FileID) bool { _, known := b.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) return known From c004f451fe50d9d9d32f1a5aaf220094d96a227d Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:21 +0100 Subject: [PATCH 38/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index bb3a5e3d..51081278 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -88,8 +88,6 @@ func (b *BaseReporter) ExecutableKnown(fileID libpf.FileID) bool { return known } -// FrameKnown returns true if the metadata of the Frame specified by frameID is -// cached in the reporter. func (b *BaseReporter) FrameKnown(frameID libpf.FrameID) bool { known := false if frameMapLock, exists := b.pdata.Frames.GetAndRefresh(frameID.FileID(), From 942ac8a6c941aaa67dd18c05fbe20c752105a521 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:30 +0100 Subject: [PATCH 39/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 51081278..08d95738 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -99,8 +99,6 @@ func (b *BaseReporter) FrameKnown(frameID libpf.FrameID) bool { return known } -// ExecutableMetadata accepts a fileID with the corresponding filename -// and caches this information. func (b *BaseReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { b.pdata.Executables.Add(args.FileID, samples.ExecInfo{ FileName: args.FileName, From f58d5efe8ca8aa56aee8ab42634edd94b2a47560 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:38 +0100 Subject: [PATCH 40/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 08d95738..2883decd 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -110,7 +110,6 @@ func (*BaseReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} func (*BaseReporter) SupportsReportTraceEvent() bool { return true } -// ReportTraceEvent enqueues reported trace events for the reporter. func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { traceEventsMap := b.traceEvents.WLock() defer b.traceEvents.WUnlock(&traceEventsMap) From d5b59d03402723cd75942df9bd9cb2b088a7c6d7 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:36:47 +0100 Subject: [PATCH 41/44] Update reporter/base_reporter.go Co-authored-by: Christos Kalkanis --- reporter/base_reporter.go | 1 - 1 file changed, 1 deletion(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 2883decd..bf4a81c5 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -152,7 +152,6 @@ func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta } } -// FrameMetadata accepts metadata associated with a frame and caches this information. func (b *BaseReporter) FrameMetadata(args *FrameMetadataArgs) { fileID := args.FrameID.FileID() addressOrLine := args.FrameID.AddressOrLine() From 638ea8ec669caad94048e349f9967924c67356f6 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 09:49:14 +0100 Subject: [PATCH 42/44] rename remaining BaseReporter --- reporter/base_reporter.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index bf4a81c5..5273f75f 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -55,40 +55,40 @@ type baseReporter struct { hostmetadata *lru.SyncedLRU[string, string] } -func (b *BaseReporter) Stop() { +func (b *baseReporter) Stop() { b.runLoop.Stop() } -func (b *BaseReporter) ReportHostMetadata(metadataMap map[string]string) { +func (b *baseReporter) ReportHostMetadata(metadataMap map[string]string) { b.addHostmetadata(metadataMap) } -func (b *BaseReporter) ReportHostMetadataBlocking(_ context.Context, +func (b *baseReporter) ReportHostMetadataBlocking(_ context.Context, metadataMap map[string]string, _ int, _ time.Duration) error { b.addHostmetadata(metadataMap) return nil } // addHostmetadata adds to and overwrites host metadata. -func (b *BaseReporter) addHostmetadata(metadataMap map[string]string) { +func (b *baseReporter) addHostmetadata(metadataMap map[string]string) { for k, v := range metadataMap { b.hostmetadata.Add(k, v) } } // ReportFramesForTrace is a NOP -func (*BaseReporter) ReportFramesForTrace(_ *libpf.Trace) {} +func (*baseReporter) ReportFramesForTrace(_ *libpf.Trace) {} // ReportCountForTrace is a NOP -func (b *BaseReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { +func (b *baseReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *TraceEventMeta) { } -func (b *BaseReporter) ExecutableKnown(fileID libpf.FileID) bool { +func (b *baseReporter) ExecutableKnown(fileID libpf.FileID) bool { _, known := b.pdata.Executables.GetAndRefresh(fileID, pdata.ExecutableCacheLifetime) return known } -func (b *BaseReporter) FrameKnown(frameID libpf.FrameID) bool { +func (b *baseReporter) FrameKnown(frameID libpf.FrameID) bool { known := false if frameMapLock, exists := b.pdata.Frames.GetAndRefresh(frameID.FileID(), pdata.FramesCacheLifetime); exists { @@ -99,18 +99,18 @@ func (b *BaseReporter) FrameKnown(frameID libpf.FrameID) bool { return known } -func (b *BaseReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { +func (b *baseReporter) ExecutableMetadata(args *ExecutableMetadataArgs) { b.pdata.Executables.Add(args.FileID, samples.ExecInfo{ FileName: args.FileName, GnuBuildID: args.GnuBuildID, }) } -func (*BaseReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} +func (*baseReporter) ReportMetrics(_ uint32, _ []uint32, _ []int64) {} -func (*BaseReporter) SupportsReportTraceEvent() bool { return true } +func (*baseReporter) SupportsReportTraceEvent() bool { return true } -func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { +func (b *baseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta) { traceEventsMap := b.traceEvents.WLock() defer b.traceEvents.WUnlock(&traceEventsMap) @@ -152,7 +152,7 @@ func (b *BaseReporter) ReportTraceEvent(trace *libpf.Trace, meta *TraceEventMeta } } -func (b *BaseReporter) FrameMetadata(args *FrameMetadataArgs) { +func (b *baseReporter) FrameMetadata(args *FrameMetadataArgs) { fileID := args.FrameID.FileID() addressOrLine := args.FrameID.AddressOrLine() @@ -196,7 +196,7 @@ func (b *BaseReporter) FrameMetadata(args *FrameMetadataArgs) { // setResource sets the resource information of the origin of the profiles. // Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. -func (b *BaseReporter) setResource(rp pprofile.ResourceProfiles) { +func (b *baseReporter) setResource(rp pprofile.ResourceProfiles) { keys := b.hostmetadata.Keys() attrs := rp.Resource().Attributes() From 9a977a61cd3a16d11adcc3e7d85ecfbf847b6bbf Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Thu, 12 Dec 2024 10:18:27 +0100 Subject: [PATCH 43/44] remove resources from the collector reporter --- reporter/base_reporter.go | 37 ----------------------- reporter/collector_reporter.go | 19 ++++-------- reporter/otlp_reporter.go | 55 ++++++++++++++++++++++++++++------ 3 files changed, 51 insertions(+), 60 deletions(-) diff --git a/reporter/base_reporter.go b/reporter/base_reporter.go index 5273f75f..00c3deb6 100644 --- a/reporter/base_reporter.go +++ b/reporter/base_reporter.go @@ -9,12 +9,10 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" - "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/ebpf-profiler/libpf" "go.opentelemetry.io/ebpf-profiler/libpf/xsync" "go.opentelemetry.io/ebpf-profiler/reporter/internal/pdata" "go.opentelemetry.io/ebpf-profiler/reporter/internal/samples" - semconv "go.opentelemetry.io/otel/semconv/v1.25.0" ) // baseReporter encapsulates shared behavior between all the available reporters. @@ -27,18 +25,6 @@ type baseReporter struct { // version is the ScopeProfile's version. version string - // hostID is the unique identifier of the host. - hostID string - - // kernelVersion is the version of the kernel. - kernelVersion string - - // hostName is the name of the host. - hostName string - - // ipAddress is the IP address of the host. - ipAddress string - // runLoop handles the run loop runLoop *runLoop @@ -193,26 +179,3 @@ func (b *baseReporter) FrameMetadata(args *FrameMetadataArgs) { mu := xsync.NewRWMutex(v) b.pdata.Frames.Add(fileID, &mu) } - -// setResource sets the resource information of the origin of the profiles. -// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. -func (b *baseReporter) setResource(rp pprofile.ResourceProfiles) { - keys := b.hostmetadata.Keys() - attrs := rp.Resource().Attributes() - - // Add hostmedata to the attributes. - for _, k := range keys { - if v, ok := b.hostmetadata.Get(k); ok { - attrs.PutStr(k, v) - } - } - - // Add event specific attributes. - // These attributes are also included in the host metadata, but with different names/keys. - // That makes our hostmetadata attributes incompatible with OTEL collectors. - attrs.PutStr(string(semconv.HostIDKey), b.hostID) - attrs.PutStr(string(semconv.HostIPKey), b.ipAddress) - attrs.PutStr(string(semconv.HostNameKey), b.hostName) - attrs.PutStr(string(semconv.ServiceVersionKey), b.version) - attrs.PutStr("os.kernel", b.kernelVersion) -} diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index ea6fdff4..2d76b767 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -6,7 +6,6 @@ package reporter // import "go.opentelemetry.io/ebpf-profiler/reporter" import ( "context" "maps" - "strconv" "time" lru "github.com/elastic/go-freelru" @@ -62,15 +61,11 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect return &CollectorReporter{ baseReporter: &baseReporter{ - cfg: cfg, - name: cfg.Name, - version: cfg.Version, - kernelVersion: cfg.KernelVersion, - hostName: cfg.HostName, - ipAddress: cfg.IPAddress, - hostID: strconv.FormatUint(cfg.HostID, 10), - pdata: data, - cgroupv2ID: cgroupv2ID, + cfg: cfg, + name: cfg.Name, + version: cfg.Version, + pdata: data, + cgroupv2ID: cgroupv2ID, traceEvents: xsync.NewRWMutex( map[samples.TraceAndMetaKey]*samples.TraceEvents{}, ), @@ -120,10 +115,6 @@ func (r *CollectorReporter) reportProfile(ctx context.Context) error { r.traceEvents.WUnlock(&traceEvents) profiles := r.pdata.Generate(events) - for i := 0; i < profiles.ResourceProfiles().Len(); i++ { - r.setResource(profiles.ResourceProfiles().At(i)) - } - if profiles.SampleCount() == 0 { log.Debugf("Skip sending profile with no samples") return nil diff --git a/reporter/otlp_reporter.go b/reporter/otlp_reporter.go index e72d4f24..4525f642 100644 --- a/reporter/otlp_reporter.go +++ b/reporter/otlp_reporter.go @@ -12,7 +12,9 @@ import ( lru "github.com/elastic/go-freelru" log "github.com/sirupsen/logrus" + "go.opentelemetry.io/collector/pdata/pprofile" "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp" + semconv "go.opentelemetry.io/otel/semconv/v1.22.0" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" @@ -30,6 +32,18 @@ var _ Reporter = (*OTLPReporter)(nil) type OTLPReporter struct { *baseReporter + // hostID is the unique identifier of the host. + hostID string + + // kernelVersion is the version of the kernel. + kernelVersion string + + // hostName is the name of the host. + hostName string + + // ipAddress is the IP address of the host. + ipAddress string + // client for the connection to the receiver. client pprofileotlp.GRPCClient @@ -74,15 +88,11 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { return &OTLPReporter{ baseReporter: &baseReporter{ - cfg: cfg, - name: cfg.Name, - version: cfg.Version, - kernelVersion: cfg.KernelVersion, - hostName: cfg.HostName, - ipAddress: cfg.IPAddress, - hostID: strconv.FormatUint(cfg.HostID, 10), - pdata: data, - cgroupv2ID: cgroupv2ID, + cfg: cfg, + name: cfg.Name, + version: cfg.Version, + pdata: data, + cgroupv2ID: cgroupv2ID, traceEvents: xsync.NewRWMutex( map[samples.TraceAndMetaKey]*samples.TraceEvents{}, ), @@ -91,6 +101,10 @@ func NewOTLP(cfg *Config) (*OTLPReporter, error) { stopSignal: make(chan libpf.Void), }, }, + kernelVersion: cfg.KernelVersion, + hostName: cfg.HostName, + ipAddress: cfg.IPAddress, + hostID: strconv.FormatUint(cfg.HostID, 10), pkgGRPCOperationTimeout: cfg.GRPCOperationTimeout, client: nil, rpcStats: NewStatsHandler(), @@ -171,6 +185,29 @@ func (r *OTLPReporter) reportOTLPProfile(ctx context.Context) error { return err } +// setResource sets the resource information of the origin of the profiles. +// Next step: maybe extend this information with go.opentelemetry.io/otel/sdk/resource. +func (r *OTLPReporter) setResource(rp pprofile.ResourceProfiles) { + keys := r.hostmetadata.Keys() + attrs := rp.Resource().Attributes() + + // Add hostmedata to the attributes. + for _, k := range keys { + if v, ok := r.hostmetadata.Get(k); ok { + attrs.PutStr(k, v) + } + } + + // Add event specific attributes. + // These attributes are also included in the host metadata, but with different names/keys. + // That makes our hostmetadata attributes incompatible with OTEL collectors. + attrs.PutStr(string(semconv.HostIDKey), r.hostID) + attrs.PutStr(string(semconv.HostIPKey), r.ipAddress) + attrs.PutStr(string(semconv.HostNameKey), r.hostName) + attrs.PutStr(string(semconv.ServiceVersionKey), r.version) + attrs.PutStr("os.kernel", r.kernelVersion) +} + // waitGrpcEndpoint waits until the gRPC connection is established. func waitGrpcEndpoint(ctx context.Context, cfg *Config, statsHandler *StatsHandlerImpl) (*grpc.ClientConn, error) { From b87cd3fa57d809d790efeb5b628a8b5e40856a86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20R=C3=BChsen?= Date: Fri, 13 Dec 2024 09:01:58 +0100 Subject: [PATCH 44/44] Update reporter/collector_reporter.go --- reporter/collector_reporter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reporter/collector_reporter.go b/reporter/collector_reporter.go index 2d76b767..24978f70 100644 --- a/reporter/collector_reporter.go +++ b/reporter/collector_reporter.go @@ -38,7 +38,7 @@ func NewCollector(cfg *Config, nextConsumer consumerprofiles.Profiles) (*Collect if err != nil { return nil, err } - // Set a lifetime to reduce risk of invalid data in case of PID reuse. + // Set a lifetime to reduce the risk of invalid data in case of PID reuse. cgroupv2ID.SetLifetime(90 * time.Second) // Next step: Dynamically configure the size of this LRU.