Skip to content
This repository was archived by the owner on Aug 30, 2023. It is now read-only.

Commit 5fe579f

Browse files
retgitsvikramraman
authored andcommitted
Update documentation (#6)
* feat: update docs * chore: update docs with PR feedback * fix: update function comment
1 parent af8346d commit 5fe579f

File tree

5 files changed

+151
-78
lines changed

5 files changed

+151
-78
lines changed

.gitignore

+41
Original file line numberDiff line numberDiff line change
@@ -1 +1,42 @@
1+
# General
12
.DS_Store
3+
.AppleDouble
4+
.LSOverride
5+
6+
# Icon must end with two \r
7+
Icon
8+
9+
# Thumbnails
10+
._*
11+
12+
# Files that might appear in the root of a volume
13+
.DocumentRevisions-V100
14+
.fseventsd
15+
.Spotlight-V100
16+
.TemporaryItems
17+
.Trashes
18+
.VolumeIcon.icns
19+
.com.apple.timemachine.donotpresent
20+
21+
# Directories potentially created on remote AFP share
22+
.AppleDB
23+
.AppleDesktop
24+
Network Trash Folder
25+
Temporary Items
26+
.apdisk
27+
28+
# Binaries for programs and plugins
29+
*.exe
30+
*.exe~
31+
*.dll
32+
*.so
33+
*.dylib
34+
35+
# Test binary, built with `go test -c`
36+
*.test
37+
38+
# Output of the go coverage tool, specifically when used with LiteIDE
39+
*.out
40+
41+
# Dependency directories
42+
vendor/

README.md

+45-50
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,86 @@
1-
# wavefront-lambda-go [![travis build status](https://travis-ci.com/wavefrontHQ/wavefront-lambda-go.svg?branch=master)](https://travis-ci.com/wavefrontHQ/wavefront-lambda-go)
1+
# wavefront-lambda-go
22

3-
This is a Wavefront Go wrapper for AWS Lambda to enable reporting standard lambda metrics and custom app metrics directly to wavefront.
3+
[![travis build status](https://travis-ci.com/wavefrontHQ/wavefront-lambda-go.svg?branch=master)](https://travis-ci.com/wavefrontHQ/wavefront-lambda-go)
4+
[![Go Report Card](https://goreportcard.com/badge/github.com/wavefrontHQ/wavefront-lambda-go)](https://goreportcard.com/report/github.com/wavefrontHQ/wavefront-lambda-go)
45

5-
## Requirements
6-
Go 1.x
6+
A Go wrapper for AWS Lambda so you can monitor everything from your [Wavefront](https://wavefront.com) dashboard
77

88
## Installation
9-
```
9+
10+
Using `go get`
11+
12+
```bash
1013
go get github.com/wavefronthq/wavefront-lambda-go
1114
```
1215

13-
## Environment variables
14-
WAVEFRONT_URL = https://\<INSTANCE>.wavefront.com
15-
WAVEFRONT_API_TOKEN = Wavefront API token with Direct Data Ingestion permission.
16-
REPORT_STANDARD_METRICS = Set to False or false to not report standard lambda metrics directly to wavefront.
16+
## Basic Usage
1717

18-
## Usage
18+
To connect your Lambda functions to Wavefront, you'll need to set two environment variables, import this module, and wrap your AWS Lambda handler function with `wflambda.Wrapper(handler)`. The environment variables you'll need to set are:
1919

20-
Wrap your AWS Lambda handler function with wavefront_lambda.Wrapper(LambdaHandler).
20+
* `WAVEFRONT_URL`: The URL of your Wavefront instance (like, `https://myinstance.wavefront.com`).
21+
* `WAVEFRONT_API_TOKEN`: Your Wavefront API token (see the [docs](https://docs.wavefront.com/wavefront_api.html) how to create an API token).
2122

2223
```go
2324
package main
2425

2526
import (
27+
"github.com/aws/aws-lambda-go/events"
2628
"github.com/aws/aws-lambda-go/lambda"
27-
"github.com/rcrowley/go-metrics"
28-
"github.com/wavefronthq/go-metrics-wavefront"
29-
"github.com/wavefronthq/wavefront-lambda-go"
29+
wflambda "github.com/wavefronthq/wavefront-lambda-go" // Import this library
3030
)
3131

32-
// Lambda handler function that includes the code which will be executed when lambda is invoked.
33-
func HandleLambdaRequest() {
34-
// your code
32+
func handler() (string, error){
33+
return "Hello World", nil
3534
}
3635

3736
func main() {
38-
// Wrap your Lambda Handler Function with wflambda.Wrapper
39-
lambda.Start(wflambda.Wrapper(HandleLambdaRequest))
37+
// Wrap the handler with wflambda.Wrapper()
38+
lambda.Start(wflambda.Wrapper(handler))
4039
}
4140
```
4241

43-
## Standard Lambda Metrics reported by Wavefront Lambda wrapper
42+
## Standard Point Tags
43+
44+
Point tags are key-value pairs (strings) that are associated with a point. Point tags provide additional context for your data and allow you to fine-tune your queries so the output shows just what you need. The below point tags are sent to Wavefront for each metric.
4445

45-
The Lambda wrapper sends the following standard lambda metrics to wavefront:
46+
| Point Tag | Description |
47+
| --------------------- | ------------------------------------------------------------------------------------------ |
48+
| LambdaArn | ARN (**Amazon Resource Name**) of the Lambda function. |
49+
| Region | AWS Region of the Lambda function. |
50+
| accountId | AWS Account ID from which the Lambda function was invoked. |
51+
| ExecutedVersion | The version of Lambda function. |
52+
| FunctionName | The name of Lambda function. |
53+
| Resource | The name and version/alias of Lambda function. (like `DemoLambdaFunc:aliasProd`) |
54+
| EventSourceMappings | AWS Event source mapping Id. (Set in case of Lambda invocation by AWS Poll-Based Services) |
4655

47-
| Metric Name | Type | Description |
48-
| ----------------------------------|:------------------:| ----------------------------------------------------------------------- |
49-
| aws.lambda.wf.invocations.count | Delta Counter | Count of number of lambda function invocations aggregated at the server.|
50-
| aws.lambda.wf.errors.count | Delta Counter | Count of number of errors aggregated at the server. |
51-
| aws.lambda.wf.coldstarts.count | Delta Counter | Count of number of cold starts aggregated at the server. |
52-
| aws.lambda.wf.duration.value | Gauge | Execution time of the Lambda handler function in milliseconds. |
56+
## Standard Metrics
5357

54-
The Lambda wrapper adds the following point tags to all metrics sent to wavefront:
58+
Based on the environment variable `REPORT_STANDARD_METRICS` the wrapper will send standard metrics to Wavefront. Set the variable to to `false` to not send the standard metrics. When the variable is not set, it will use the default value `true`.
5559

56-
| Point Tag | Description |
57-
| --------------------- | ----------------------------------------------------------------------------- |
58-
| LambdaArn | ARN(Amazon Resource Name) of the Lambda function. |
59-
| Region | AWS Region of the Lambda function. |
60-
| accountId | AWS Account ID from which the Lambda function was invoked. |
61-
| ExecutedVersion | The version of Lambda function. |
62-
| FunctionName | The name of Lambda function. |
63-
| Resource | The name and version/alias of Lambda function. (Ex: DemoLambdaFunc:aliasProd) |
64-
| EventSourceMappings | AWS Event source mapping Id. (Set in case of Lambda invocation by AWS Poll-Based Services)|
60+
| Metric Name | Type | Description |
61+
| --------------------------------- | ------------- | ----------------------------------------------------------------------- |
62+
| aws.lambda.wf.invocations.count | Delta Counter | Count of number of lambda function invocations aggregated at the server.|
63+
| aws.lambda.wf.errors.count | Delta Counter | Count of number of errors aggregated at the server. |
64+
| aws.lambda.wf.coldstarts.count | Delta Counter | Count of number of cold starts aggregated at the server. |
65+
| aws.lambda.wf.duration.value | Gauge | Execution time of the Lambda handler function in milliseconds. |
6566

66-
## Custom Lambda Metrics
67+
## Custom Metrics
6768

68-
The wavefront Go lambda wrapper reports custom business metrics via API's provided by the [go-metrics-wavefront client] (https://github.com/wavefrontHQ/go-metrics-wavefront).
69-
Please refer to the below code sample which shows how you can send custom business metrics to wavefront from your lambda function.
69+
You can send custom business metrics to Wavefront using the [go-metrics-wavefront](https://github.com/wavefrontHQ/go-metrics-wavefront) client. The below code reports a _counter_, a _delta counter_, and two _gauges_. All metric names should be unique. If you have metrics that you want to track as both _counter_ and _delta counter_, you'll have to add a suffix to one of the metrics. Having the same metric name for any two types of metrics will result in only one time series at the server and thus cause collisions.
7070

71-
### Code Sample
71+
The code below imported this module and wrapped the _handler_ function argument in _main_ with `wflambda.Wrapper(handler)`. During each execution four metrics are collected and sent to Wavefront with both the [standard point tags](#standard-point-tags) and the point tags created in the handler.
7272

7373
```go
7474
package main
7575

7676
import (
7777
"github.com/aws/aws-lambda-go/lambda"
7878
"github.com/rcrowley/go-metrics"
79-
"github.com/wavefronthq/go-metrics-wavefront"
80-
"github.com/wavefronthq/wavefront-lambda-go"
79+
wavefront "github.com/wavefronthq/go-metrics-wavefront"
80+
wflambda "github.com/wavefronthq/wavefront-lambda-go"
8181
)
8282

83-
// Lambda handler function that includes the code which will be executed when lambda is invoked.
84-
func HandleLambdaRequest() {
83+
func handler() {
8584
// Point Tags
8685
appTags := map[string]string{
8786
"key2": "val1",
@@ -114,10 +113,6 @@ func HandleLambdaRequest() {
114113
}
115114

116115
func main() {
117-
//Wrapping with wflambda.Wrapper
118-
lambda.Start(wflambda.Wrapper(HandleLambdaRequest))
116+
lambda.Start(wflambda.Wrapper(handler))
119117
}
120118
```
121-
122-
Note: Having the same metric name for any two types of metrics will result in only one time series at the server and thus cause collisions.
123-
In general, all metric names should be different. In case you have metrics that you want to track as both a Counter and Delta Counter, consider adding a relevant suffix to one of the metrics to differentiate one metric name from another.

handler.go

+17-1
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,23 @@ import (
66
"reflect"
77
)
88

9-
// Validate the input lambda handler based on source code at
9+
// validateLambdaHandler validates the lambdaHandler is a valid handler function. When the handler is a valid handler function,
10+
// the function will check whether one of the arguments is a context. The function returns a non-nil error if lambdaHandler is
11+
// not a valid handler. When the lambdaHandler is valid, the boolean indicates whether the lambdaHandler has a context parameter.
12+
// is returned. The code of the function is based on source code at
1013
// https://github.com/aws/aws-lambda-go/blob/ea03c2814414b2223eff860ed2286a83ed8a195c/lambda/handler.go#L75
1114
func validateLambdaHandler(lambdaHandler interface{}) (bool, error) {
1215
if lambdaHandler == nil {
1316
return false, fmt.Errorf("handler is nil")
1417
}
1518
handlerType := reflect.TypeOf(lambdaHandler)
19+
1620
// Validate lambdaHandler Kind.
1721
if handlerType.Kind() != reflect.Func {
1822
return false, fmt.Errorf("handler kind %s is not %s", handlerType.Kind(), reflect.Func)
1923
}
24+
25+
// Check if the lambdaHandler takes a context argument.
2026
takesContext, err := validateArguments(handlerType)
2127
if err != nil {
2228
return false, err
@@ -28,6 +34,11 @@ func validateLambdaHandler(lambdaHandler interface{}) (bool, error) {
2834
return takesContext, nil
2935
}
3036

37+
// validateArguments validates whether the arguments passed as part of the lambdaHandler are valid. A valid lambdaHandler
38+
// has a maximum of two arguments. When there are two arguments, the first one must be a Context. The function returns
39+
// true or false depending on whether the lambdaHandler has a context argument. If the arguments are not valid, an error
40+
// is returned. Detailed information on the valid handler signatures can be found in the AWS Lambda documentation
41+
// https://docs.aws.amazon.com/lambda/latest/dg/go-programming-model-handler-types.html
3142
func validateArguments(handler reflect.Type) (bool, error) {
3243
handlerTakesContext := false
3344
if handler.NumIn() > 2 {
@@ -44,6 +55,11 @@ func validateArguments(handler reflect.Type) (bool, error) {
4455
return handlerTakesContext, nil
4556
}
4657

58+
// validateReturns validates whether the arguments returned by the lambdaHandler are valid or not. A valid lambdaHandler
59+
// returns a maximum of two arguments. When there are two arguments, the second argument must be of type error. When there
60+
// is only one argument, that one must be of type error. Detailed information on the valid handler signatures can be found
61+
// in the AWS Lambda documentation
62+
// https://docs.aws.amazon.com/lambda/latest/dg/go-programming-model-handler-types.html
4763
func validateReturns(handler reflect.Type) error {
4864
errorType := reflect.TypeOf((*error)(nil)).Elem()
4965
if handler.NumOut() > 2 {

reporter.go

+21-17
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,23 @@ import (
1212
"github.com/wavefronthq/go-metrics-wavefront"
1313
)
1414

15-
// Increment counter if report is true
15+
// incrementCounter increments the counter by the given value if report is true
1616
func incrementCounter(counter metrics.Counter, value int64, report bool) {
1717
if report {
1818
counter.Inc(value)
1919
}
2020
}
2121

22-
// Update gauge value if report is true
22+
// updateGaugeFloat64 increments the counter by the given value if report is true
2323
func updateGaugeFloat64(gauge metrics.GaugeFloat64, value float64, report bool) {
2424
if report {
2525
gauge.Update(value)
2626
}
2727
}
2828

29-
// Register the standard lambda metrics.
29+
// registerStandardLambdaMetrics creates counters and gauges for the standard AWS Lambda metrics that are reported
30+
// to Wavefront. Whether or not the metrics are actually sent to Wavefront is determined by the environment variable
31+
// REPORT_STANDARD_METRICS.
3032
func registerStandardLambdaMetrics() {
3133
// Register cold start counter.
3234
csCounter = metrics.NewCounter()
@@ -38,19 +40,19 @@ func registerStandardLambdaMetrics() {
3840
invocationsCounterName := wavefront.DeltaCounterName(getStandardLambdaMetricName("invocations"))
3941
wavefront.RegisterMetric(invocationsCounterName, invocationsCounter, nil)
4042

41-
// Register Error counter
43+
// Register Error counter.
4244
errCounter = metrics.NewCounter()
4345
errCounterName := wavefront.DeltaCounterName(getStandardLambdaMetricName("errors"))
4446
wavefront.RegisterMetric(errCounterName, errCounter, nil)
4547

46-
// Register duration gauge
48+
// Register duration gauge.
4749
durationGauge = metrics.NewGaugeFloat64()
4850
wavefront.RegisterMetric(getStandardLambdaMetricName("duration"), durationGauge, nil)
4951
}
5052

51-
// Method to send all metrics in the registry to wavefront.
53+
// reportMetrics sends the collected metrics in the registry to Wavefront. With each metric,
54+
// the point tags listed in the README are sent by the reporter.
5255
func reportMetrics(ctx context.Context) {
53-
// Get standard lambda point tags
5456
lc, ok := lambdacontext.FromContext(ctx)
5557
if ok {
5658
invokedFunctionArn := lc.InvokedFunctionArn
@@ -66,6 +68,7 @@ func reportMetrics(ctx context.Context) {
6668
"Region": splitArn[3],
6769
"accountId": splitArn[4],
6870
}
71+
6972
if splitArn[5] == "function" {
7073
hostTags["Resource"] = splitArn[6]
7174
if len(splitArn) == 8 {
@@ -90,28 +93,29 @@ func reportMetrics(ctx context.Context) {
9093
}
9194
}
9295

93-
// Util method that returns the standard lambda metric name.
94-
// Ex:
95-
// getStandardLambdaMetricName("invocation", true) returns "aws.lambda.wf.invocation_event"
96-
// getStandardLambdaMetricName("invocations", false) returns "aws.lambda.wf.invocations"
97-
96+
// getStandardLambdaMetricName adds the standard Wavefront prefix (aws.lambda.wf) to the name of the metric and returns
97+
// the newly created string.
98+
// for example, getStandardLambdaMetricName("invocations") returns "aws.lambda.wf.invocations"
9899
func getStandardLambdaMetricName(metric string) string {
99-
const metric_prefix string = "aws.lambda.wf."
100-
return strings.Join([]string{metric_prefix, metric}, "")
100+
const metricPrefix string = "aws.lambda.wf."
101+
return strings.Join([]string{metricPrefix, metric}, "")
101102
}
102103

103-
// Util method to validate the specified environment variables and return if standard lambda Metrics
104-
// should be collected by the wrapper.
104+
// getAndValidateLambdaEnvironment validates whether the required environment variables WAVEFRONT_URL and
105+
// WAVEFRONT_API_TOKEN have been set. If they are not set, the function will panic. The function also checks
106+
// whether the environment variable REPORT_STANDARD_METRICS has been set to false (it will default to true).
107+
// to determine if the standard metrics should be reported.
105108
func getAndValidateLambdaEnvironment() bool {
106-
// Validate environment variables required by wavefrontLambda wrapper.
107109
server = os.Getenv("WAVEFRONT_URL")
108110
if server == "" {
109111
log.Panicf("Environment variable WAVEFRONT_URL is not set.")
110112
}
113+
111114
authToken = os.Getenv("WAVEFRONT_API_TOKEN")
112115
if authToken == "" {
113116
log.Panicf("Environment variable WAVEFRONT_API_TOKEN is not set.")
114117
}
118+
115119
reportStandardLambdaMetrics := os.Getenv("REPORT_STANDARD_METRICS")
116120
reportStandardMetrics := true
117121
if reportStandardLambdaMetrics == "False" || reportStandardLambdaMetrics == "false" {

0 commit comments

Comments
 (0)