Skip to content

Commit

Permalink
[otelarrowreceiver, otelarrowexporter] Add internal/grpcutil package (#…
Browse files Browse the repository at this point in the history
…33688)

**Description:** 
With utilities to encode and decode timeout in the syntax specified by
gRPC.
This will be used by the otelarrow components to encode and decode
timeout values.
In that sense, the new code could also be added into the pending
internal/otelarrow package, see
#33579

As this code is derived from gRPC-Go, some text is added in `NOTICE`
according to the license. The code that this was derived from contained
a TODO, which was largely addressed by eliminating very short timeouts
from being encoded. This code will encode timeouts in milliseconds,
seconds, hours, and days but it will not encode microsecond/nanosecond
durations, these are rounded to `0m`. The decoder will handle all
durations that gRPC specifies, so that this logic can change in the
future.

**Link to tracking Issue:**
open-telemetry/otel-arrow#227

**Testing:** Adds basic tests.
  • Loading branch information
jmacd committed Aug 6, 2024
1 parent 17d059b commit 094f95e
Show file tree
Hide file tree
Showing 20 changed files with 255 additions and 13 deletions.
27 changes: 27 additions & 0 deletions .chloggen/add-grpcutil.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: internal/grpcutil

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add internal/grpcutil package with gRPC-specified timeout parsing

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [33688]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [api]
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ internal/coreinternal/ @open-teleme
internal/docker/ @open-telemetry/collector-contrib-approvers @rmfitzpatrick @jamesmoessis
internal/exp/metrics/ @open-telemetry/collector-contrib-approvers @sh0rez @RichieSams
internal/filter/ @open-telemetry/collector-contrib-approvers @open-telemetry/collector-approvers
internal/grpcutil/ @open-telemetry/collector-contrib-approvers @jmacd @moh-osman3 @lquerel
internal/k8sconfig/ @open-telemetry/collector-contrib-approvers @dmitryax
internal/k8stest/ @open-telemetry/collector-contrib-approvers @crobert-1
internal/kafka/ @open-telemetry/collector-contrib-approvers @pavolloffay @MovieStoreGuy
Expand Down
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/bug_report.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ body:
- internal/docker
- internal/exp/metrics
- internal/filter
- internal/grpcutil
- internal/k8sconfig
- internal/k8stest
- internal/kafka
Expand Down
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/feature_request.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ body:
- internal/docker
- internal/exp/metrics
- internal/filter
- internal/grpcutil
- internal/k8sconfig
- internal/k8stest
- internal/kafka
Expand Down
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/other.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ body:
- internal/docker
- internal/exp/metrics
- internal/filter
- internal/grpcutil
- internal/k8sconfig
- internal/k8stest
- internal/kafka
Expand Down
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/unmaintained.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ body:
- internal/docker
- internal/exp/metrics
- internal/filter
- internal/grpcutil
- internal/k8sconfig
- internal/k8stest
- internal/kafka
Expand Down
18 changes: 17 additions & 1 deletion NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,20 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
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.
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

internal/grpcutil contains code derived from gRPC-Go

Copyright 2014 gRPC authors.

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.
4 changes: 2 additions & 2 deletions exporter/otelarrowexporter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
<!-- status autogenerated section -->
| Status | |
| ------------- |-----------|
| Stability | [alpha]: traces, metrics, logs |
| Stability | [beta]: traces, metrics, logs |
| Distributions | [] |
| Issues | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Aexporter%2Fotelarrow%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Aexporter%2Fotelarrow) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Aexporter%2Fotelarrow%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Aexporter%2Fotelarrow) |
| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner) | [@jmacd](https://www.github.com/jmacd), [@moh-osman3](https://www.github.com/moh-osman3), [@lquerel](https://www.github.com/lquerel) |

[alpha]: https://github.com/open-telemetry/opentelemetry-collector#alpha
[beta]: https://github.com/open-telemetry/opentelemetry-collector#beta
<!-- end autogenerated section -->

Exports telemetry data using [OpenTelemetry Protocol with Apache
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion exporter/otelarrowexporter/metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ scope_name: otelcol/otelarrow
status:
class: exporter
stability:
alpha: [traces, metrics, logs]
beta: [traces, metrics, logs]
distributions: []
codeowners:
active: [jmacd, moh-osman3, lquerel]
Expand Down
1 change: 1 addition & 0 deletions internal/grpcutil/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include ../../Makefile.Common
11 changes: 11 additions & 0 deletions internal/grpcutil/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/open-telemetry/opentelemetry-collector-contrib/internal/grpcutil

go 1.21.0

require github.com/stretchr/testify v1.9.0

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
10 changes: 10 additions & 0 deletions internal/grpcutil/go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions internal/grpcutil/metadata.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
status:
codeowners:
active: [jmacd, moh-osman3, lquerel]
114 changes: 114 additions & 0 deletions internal/grpcutil/timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

// The EncodeTimeout function is forked and modified from the original
// https://github.com/grpc/grpc-go/blob/master/internal/grpcutil/encode_duration.go

// This DecodeTimeout function is forked and modified from the original
// https://github.com/grpc/grpc-go/blob/master/internal/transport/http_util.go

package grpcutil // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/grpcutil"

import (
"fmt"
"math"
"strconv"
"time"
)

const maxTimeoutValue int64 = 100000000 - 1

// div does integer division and round-up the result. Note that this is
// equivalent to (d+r-1)/r but has less chance to overflow.
func div(d, r time.Duration) int64 {
if d%r > 0 {
return int64(d/r + 1)
}
return int64(d / r)
}

type timeoutUnit uint8

const (
hour timeoutUnit = 'H'
minute timeoutUnit = 'M'
second timeoutUnit = 'S'
millisecond timeoutUnit = 'm'
microsecond timeoutUnit = 'u'
nanosecond timeoutUnit = 'n'
)

// EncodeTimeout encodes the duration to the format grpc-timeout
// header accepts. This is copied from the gRPC-Go implementation,
// with two branches of the original six branches removed, leaving the
// four you see for milliseconds, seconds, minutes, and hours. This
// code will not encode timeouts less than one millisecond. See:
//
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
func EncodeTimeout(t time.Duration) string {
if t < time.Millisecond {
return "0m"
}
if d := div(t, time.Millisecond); d <= maxTimeoutValue {
return fmt.Sprintf("%d%c", d, millisecond)
}
if d := div(t, time.Second); d <= maxTimeoutValue {
return fmt.Sprintf("%d%c", d, second)
}
if d := div(t, time.Minute); d <= maxTimeoutValue {
return fmt.Sprintf("%d%c", d, minute)
}
// Note that maxTimeoutValue * time.Hour > MaxInt64.
return fmt.Sprintf("%d%c", div(t, time.Hour), hour)
}

func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
switch u {
case hour:
return time.Hour, true
case minute:
return time.Minute, true
case second:
return time.Second, true
case millisecond:
return time.Millisecond, true
case microsecond:
return time.Microsecond, true
case nanosecond:
return time.Nanosecond, true
default:
}
return
}

// DecodeTimeout parses a string associated with the "grpc-timeout"
// header. Note this will accept all valid gRPC units including
// microseconds and nanoseconds, which EncodeTimeout avoids. This is
// specified in:
//
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
func DecodeTimeout(s string) (time.Duration, error) {
size := len(s)
if size < 2 {
return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
}
if size > 9 {
// Spec allows for 8 digits plus the unit.
return 0, fmt.Errorf("transport: timeout string is too long: %q", s)
}
unit := timeoutUnit(s[size-1])
d, ok := timeoutUnitToDuration(unit)
if !ok {
return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
}
t, err := strconv.ParseInt(s[:size-1], 10, 64)
if err != nil {
return 0, err
}
const maxHours = math.MaxInt64 / int64(time.Hour)
if d == time.Hour && t > maxHours {
// This timeout would overflow math.MaxInt64; clamp it.
return time.Duration(math.MaxInt64), nil
}
return d * time.Duration(t), nil
}
54 changes: 54 additions & 0 deletions internal/grpcutil/timeout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package grpcutil

import (
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestTimeoutEncode(t *testing.T) {
// Note the gRPC specification limits durations to 8 digits,
// so the use of 123456789 as a multiplier below forces the
// next-larger unit to be used.
require.Equal(t, "0m", EncodeTimeout(-time.Second))
require.Equal(t, "1000m", EncodeTimeout(time.Second))
require.Equal(t, "123m", EncodeTimeout(123*time.Millisecond))
require.Equal(t, "123457S", EncodeTimeout(123456789*time.Millisecond))
require.Equal(t, "2057614M", EncodeTimeout(123456789*time.Second))
require.Equal(t, "2057614H", EncodeTimeout(123456789*time.Minute))
}

func mustDecode(t *testing.T, s string) time.Duration {
d, err := DecodeTimeout(s)
require.NoError(t, err, "must parse a timeout")
return d
}

func TestTimeoutDecode(t *testing.T) {
// Note the gRPC specification limits durations to 8 digits,
// so the use of 123456789 as a multiplier below forces the
// next-larger unit to be used.
require.Equal(t, time.Duration(0), mustDecode(t, "0m"))
require.Equal(t, time.Second, mustDecode(t, "1000m"))
require.Equal(t, 123*time.Millisecond, mustDecode(t, "123m"))
require.Equal(t, 123*time.Second, mustDecode(t, "123S"))
require.Equal(t, 123*time.Minute, mustDecode(t, "123M"))
require.Equal(t, 123*time.Hour, mustDecode(t, "123H"))

// these are not encoded by EncodeTimeout, but will be decoded
require.Equal(t, 123*time.Microsecond, mustDecode(t, "123u"))
require.Equal(t, 123*time.Nanosecond, mustDecode(t, "123n"))

// error cases
testError := func(s string) {
_, err := DecodeTimeout(s)
require.Error(t, err)
}
testError("123x")
testError("x")
testError("")
}
4 changes: 2 additions & 2 deletions receiver/otelarrowreceiver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
<!-- status autogenerated section -->
| Status | |
| ------------- |-----------|
| Stability | [alpha]: traces, metrics, logs |
| Stability | [beta]: traces, metrics, logs |
| Distributions | [contrib] |
| Issues | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Fotelarrow%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Fotelarrow) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Fotelarrow%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Fotelarrow) |
| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner) | [@jmacd](https://www.github.com/jmacd), [@moh-osman3](https://www.github.com/moh-osman3) |

[alpha]: https://github.com/open-telemetry/opentelemetry-collector#alpha
[beta]: https://github.com/open-telemetry/opentelemetry-collector#beta
[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib
<!-- end autogenerated section -->

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion receiver/otelarrowreceiver/metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ scope_name: otelcol/otelarrowreceiver
status:
class: receiver
stability:
alpha: [traces, metrics, logs]
beta: [traces, metrics, logs]
distributions: [contrib]
codeowners:
active: [jmacd, moh-osman3]
Expand Down
1 change: 1 addition & 0 deletions versions.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ module-sets:
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/docker
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/exp/metrics
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/filter
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/grpcutil
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8stest
- github.com/open-telemetry/opentelemetry-collector-contrib/internal/kafka
Expand Down

0 comments on commit 094f95e

Please sign in to comment.