Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NH-76996 Otelcol: collecting Lambda function logs (code refactoring) #21

Merged
merged 11 commits into from
May 29, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Polish
jerrytfleung committed May 24, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 4b64bb5c87ad39712e69074f68dca670fef01c9e
87 changes: 42 additions & 45 deletions collector/receiver/telemetryapireceiver/receiver.go
Original file line number Diff line number Diff line change
@@ -20,6 +20,13 @@ import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strings"
"time"

"github.com/golang-collections/go-datastructures/queue"
telemetryapi "github.com/open-telemetry/opentelemetry-lambda/collector/receiver/telemetryapireceiver/internal/telemetryapi"
"go.opentelemetry.io/collector/component"
@@ -31,12 +38,6 @@ import (
"go.opentelemetry.io/collector/receiver"
semconv "go.opentelemetry.io/collector/semconv/v1.25.0"
"go.uber.org/zap"
"io"
"math/rand"
"net/http"
"os"
"strings"
"time"
)

const defaultListenerPort = "4325"
@@ -45,20 +46,16 @@ const timeFormatLayout = "2006-01-02T15:04:05.000Z"
const scopeName = "github.com/open-telemetry/opentelemetry-lambda/collector/receiver/telemetryapi"

type telemetryAPIReceiver struct {
httpServer *http.Server
logger *zap.Logger
queue *queue.Queue // queue is a synchronous queue and is used to put the received log events to be dispatched later
nextTraces consumer.Traces
nextMetrics consumer.Metrics
nextLogs consumer.Logs
lastPlatformStartTime string
lastPlatformEndTime string
firstPlatformInitReportTime time.Time
firstPlatformRuntimeDoneTime time.Time
firstPlatformReportTime time.Time
firstPlatformRestoreReportTime time.Time
extensionID string
resource pcommon.Resource
httpServer *http.Server
logger *zap.Logger
queue *queue.Queue // queue is a synchronous queue and is used to put the received log events to be dispatched later
nextTraces consumer.Traces
nextMetrics consumer.Metrics
nextLogs consumer.Logs
lastPlatformStartTime string
lastPlatformEndTime string
extensionID string
resource pcommon.Resource
}

func (r *telemetryAPIReceiver) Start(ctx context.Context, host component.Host) error {
@@ -162,31 +159,6 @@ func (r *telemetryAPIReceiver) httpHandler(w http.ResponseWriter, req *http.Requ
slice = nil
}

func (r *telemetryAPIReceiver) createPlatformInitSpan(start, end string) (ptrace.Traces, error) {
traceData := ptrace.NewTraces()
rs := traceData.ResourceSpans().AppendEmpty()
r.resource.CopyTo(rs.Resource())
ss := rs.ScopeSpans().AppendEmpty()
ss.Scope().SetName(scopeName)
span := ss.Spans().AppendEmpty()
span.SetTraceID(newTraceID())
span.SetSpanID(newSpanID())
span.SetName("platform.initRuntimeDone")
span.SetKind(ptrace.SpanKindInternal)
span.Attributes().PutBool(semconv.AttributeFaaSColdstart, true)
startTime, err := time.Parse(timeFormatLayout, start)
if err != nil {
return ptrace.Traces{}, err
}
span.SetStartTimestamp(pcommon.NewTimestampFromTime(startTime))
endTime, err := time.Parse(timeFormatLayout, end)
if err != nil {
return ptrace.Traces{}, err
}
span.SetEndTimestamp(pcommon.NewTimestampFromTime(endTime))
return traceData, nil
}

func (r *telemetryAPIReceiver) createTraces(slice []telemetryapi.Event) (ptrace.Traces, error) {
for _, el := range slice {
r.logger.Debug(fmt.Sprintf("Event: %s", el.Type), zap.Any("event", el))
@@ -356,6 +328,31 @@ func (r *telemetryAPIReceiver) registerLogsConsumer(next consumer.Logs) {
r.nextLogs = next
}

func (r *telemetryAPIReceiver) createPlatformInitSpan(start, end string) (ptrace.Traces, error) {
traceData := ptrace.NewTraces()
rs := traceData.ResourceSpans().AppendEmpty()
r.resource.CopyTo(rs.Resource())
ss := rs.ScopeSpans().AppendEmpty()
ss.Scope().SetName(scopeName)
span := ss.Spans().AppendEmpty()
span.SetTraceID(newTraceID())
span.SetSpanID(newSpanID())
span.SetName("platform.initRuntimeDone")
span.SetKind(ptrace.SpanKindInternal)
span.Attributes().PutBool(semconv.AttributeFaaSColdstart, true)
startTime, err := time.Parse(timeFormatLayout, start)
if err != nil {
return ptrace.Traces{}, err
}
span.SetStartTimestamp(pcommon.NewTimestampFromTime(startTime))
endTime, err := time.Parse(timeFormatLayout, end)
if err != nil {
return ptrace.Traces{}, err
}
span.SetEndTimestamp(pcommon.NewTimestampFromTime(endTime))
return traceData, nil
}

func newTelemetryAPIReceiver(
cfg *Config,
set receiver.CreateSettings,
119 changes: 2 additions & 117 deletions collector/receiver/telemetryapireceiver/receiver_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
// Copyright The OpenTelemetry 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
// 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.

package telemetryapireceiver // import "github.com/open-telemetry/opentelemetry-lambda/collector/receiver/telemetryapireceiver"

import (
@@ -162,119 +160,6 @@ func TestCreatePlatformInitSpan(t *testing.T) {
}
}

func TestCreateMetrics(t *testing.T) {
testCases := []struct {
desc string
slice []telemetryapi.Event
expectedLogRecords int
expectedType string
expectedTimestamp string
expectedBody string
expectedSeverityText string
expectedContainsRequestId bool
expectedRequestId string
expectedSeverityNumber plog.SeverityNumber
expectError bool
}{
{
desc: "platform.initReport",
slice: []telemetryapi.Event{
{
Time: "2024-05-15T23:58:26.858Z",
Type: "platform.initReport",
Record: map[string]any{
"initializationType": "on-demand",
"metrics": map[string]any{
"durationMs": 1819.081,
},
"phase": "init",
"status": "success",
},
},
},
expectedLogRecords: 1,
expectedType: "platform.initReport",
expectedTimestamp: "2024-05-15T23:58:26.858Z",
expectedBody: "{\"initializationType\":\"on-demand\",\"metrics\":{\"durationMs\":1819.081},\"phase\":\"init\",\"status\":\"success\"}",
expectedContainsRequestId: false,
expectedSeverityText: "INFO",
expectedSeverityNumber: plog.SeverityNumberInfo,
expectError: false,
},
{
desc: "platform.report",
slice: []telemetryapi.Event{
{
Time: "2024-05-15T23:58:39.317Z",
Type: "platform.report",
Record: map[string]any{
"metrics": map[string]any{
"billedDurationMs": 12456,
"durationMs": 12455.155,
"initDurationMs": 1819.881,
"maxMemoryUsedMB": 128,
"memorySizeMB": 128,
},
"requestId": "882e9658-570e-4b2f-aaa8-5dfb88f7eccb",
"status": "success",
},
},
{
Time: "2024-05-15T23:59:39.317Z",
Type: "platform.report",
Record: map[string]any{
"metrics": map[string]any{
"billedDurationMs": 12456,
"durationMs": 13655.155,
"initDurationMs": 1819.881,
"maxMemoryUsedMB": 128,
"memorySizeMB": 128,
},
"requestId": "882e9658-570e-4b2f-aaa8-5dfb88f7abcb",
"status": "success",
},
},
},
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
r := newTelemetryAPIReceiver(
&Config{},
receivertest.NewNopCreateSettings(),
)
r.createMetrics(tc.slice)
//if tc.expectError {
// require.Error(t, err)
//} else {
// require.Equal(t, 1, log.ResourceLogs().Len())
// resourceLog := log.ResourceLogs().At(0)
// require.Equal(t, 1, resourceLog.ScopeLogs().Len())
// scopeLog := resourceLog.ScopeLogs().At(0)
// require.Equal(t, scopeName, scopeLog.Scope().Name())
// require.Equal(t, tc.expectedLogRecords, scopeLog.LogRecords().Len())
// if scopeLog.LogRecords().Len() > 0 {
// logRecord := scopeLog.LogRecords().At(0)
// attr, ok := logRecord.Attributes().Get("type")
// require.True(t, ok)
// require.Equal(t, tc.expectedType, attr.Str())
// expectedTime, err := time.Parse(timeFormatLayout, tc.expectedTimestamp)
// require.NoError(t, err)
// require.Equal(t, pcommon.NewTimestampFromTime(expectedTime), logRecord.Timestamp())
// requestId, ok := logRecord.Attributes().Get(semconv.AttributeFaaSInvocationID)
// require.Equal(t, tc.expectedContainsRequestId, ok)
// if ok {
// require.Equal(t, tc.expectedRequestId, requestId.Str())
// }
// require.Equal(t, tc.expectedSeverityText, logRecord.SeverityText())
// require.Equal(t, tc.expectedSeverityNumber, logRecord.SeverityNumber())
// require.Equal(t, tc.expectedBody, logRecord.Body().Str())
// }
//}
})
}
}

func TestCreateLogs(t *testing.T) {
testCases := []struct {
desc string