Skip to content

Commit

Permalink
v0.9.0
Browse files Browse the repository at this point in the history
  • Loading branch information
timstudd committed Jan 4, 2017
0 parents commit 680a7de
Show file tree
Hide file tree
Showing 42 changed files with 2,703 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
examples/http-client/http-client
examples/http-server/http-server
examples/grpc-client/grpc-client
examples/grpc-server/grpc-server
22 changes: 22 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Copyright (c) 2016 GoGuardian


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.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Go SDK for AWX X-Ray

> SDK for instrumenting Go applications for AWS X-Ray
## AWS X-Ray
More information about AWS X-Ray can be found at the [product website](https://aws.amazon.com/xray/).

## Getting Started

### Client Example
The outbound request is traced
```go
import "github.com/goguardian/aws-xray-go/xray"

func main() {
ctx := xray.NewContext("service-name", nil)
defer xray.Close(ctx)

http := xray.GetHTTPClient(ctx)
http.Get("http://127.0.0.1:3000")
}
```

### Server Example
All inbound requests will be traced
```go
import (
"log"
"net/http"
"github.com/goguardian/aws-xray-go/xray"
)

func main() {
http.HandleFunc("/", xray.Middleware("service-name", handler))
http.ListenAndServe(":3000", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hiya"))
}
```

### Sampling
The sampling configuration can be modified using `xray.SetSampler`. The default settings are to sample all of the first ten requests of any second and five percent of all other requests that second.
```go
import "github.com/goguardian/aws-xray-go/xray"

func example() {
fixedTarget := 10 // First ten requests per second
fallbackRate := 0.05 // Five percent of all other requests
xray.SetSampler(fixedTarget, fallbackRate)
}
64 changes: 64 additions & 0 deletions attributes/local.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package attributes

import (
"github.com/goguardian/aws-xray-go/utils"
"net/http"
)

// Local represents an incoming HTTP/HTTPS call.
type Local struct {
Request *LocalRequest `json:"request,omitempty"`
Response *LocalResponse `json:"response,omitempty"`
}

// LocalRequest represents the request of an incoming HTTP/HTTPS call.
type LocalRequest struct {
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
ClientIP string `json:"client_ip,omitempty"`
}

// LocalResponse represents the response to an incoming HTTP/HTTPS call.
type LocalResponse struct {
Status int `json:"status"`
ContentLength int `json:"content_length"`
}

// NewLocal creates a new Local object from an HTTP request.
func NewLocal(req *http.Request) *Local {
local := &Local{
Request: &LocalRequest{},
Response: &LocalResponse{},
}

if req == nil {
return local
}

urlStr := ""
if req.URL != nil {
urlStr = req.URL.String()
}

local.Request = &LocalRequest{
Method: req.Method,
UserAgent: req.UserAgent(),
ClientIP: utils.GetClientIP(req),
URL: urlStr,
}

return local
}

// Close closes a local HTTP/HTTPS request, adding response data.
func (l *Local) Close(res *http.Response) {
if res == nil {
return
}

l.Response.Status = res.StatusCode

contentLength, _ := utils.GetContentLength(res)
l.Response.ContentLength = contentLength
}
22 changes: 22 additions & 0 deletions attributes/local_exception.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package attributes

// LocalException represents a local exception.
type LocalException struct {
Message string `json:"message,omitempty"`
Type string `json:"type,omitempty"`
Stack []LocalExceptionStack `json:"stack,omitempty"`
}

// LocalExceptionStack represents the stack of a local exception.
type LocalExceptionStack struct {
Path []string `json:"path"`
Line int `json:"line"`
Label string `json:"label"`
}

// NewLocalException creates a new local exception from an error.
func NewLocalException(err error) *LocalException {
return &LocalException{
Message: err.Error(),
}
}
15 changes: 15 additions & 0 deletions attributes/local_exception_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package attributes

import (
"errors"
"testing"
)

func TestNewLocalException(t *testing.T) {
err := errors.New("An error")
exception := NewLocalException(err)

if exception.Message != err.Error() {
t.Error("Local exception exception message incorrect")
}
}
87 changes: 87 additions & 0 deletions attributes/local_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package attributes

import (
"net/http"
"net/url"
"testing"
)

func TestNewLocal(t *testing.T) {
tests := []struct {
req *http.Request
res *http.Response
expectMethod string
expectURL string
expectIP string
expectAgent string
expectContentLength int
expectStatus int
}{
{},
{
req: &http.Request{},
res: &http.Response{},
},
{
req: &http.Request{
Method: http.MethodGet,
URL: &url.URL{
Scheme: "https",
Host: "www.example.com",
Path: "/test",
},
RemoteAddr: "127.0.0.1:2000",
Header: http.Header{
"User-Agent": []string{"user-agent"},
},
},
res: &http.Response{
Header: http.Header{
"Content-Length": []string{"123"},
},
StatusCode: 200,
},
expectMethod: http.MethodGet,
expectURL: "https://www.example.com/test",
expectIP: "127.0.0.1",
expectAgent: "user-agent",
expectContentLength: 123,
expectStatus: 200,
},
}

for _, test := range tests {
local := NewLocal(test.req)
local.Close(test.res)

if local.Request.ClientIP != test.expectIP {
t.Errorf("Expected client IP '%s', got '%s'",
test.expectIP, local.Request.ClientIP)
}

if local.Request.Method != test.expectMethod {
t.Errorf("Expected method '%s', got '%s'",
test.expectMethod, local.Request.Method)
}

if local.Request.URL != test.expectURL {
t.Errorf("Expected URL '%s', got '%s'",
test.expectURL, local.Request.URL)
}

if local.Request.UserAgent != test.expectAgent {
t.Errorf("Expected user agent '%s', got '%s'",
test.expectAgent, local.Request.UserAgent)
}

if local.Response.ContentLength != test.expectContentLength {
t.Errorf("Expected content length '%d', got '%d'",
test.expectContentLength, local.Response.ContentLength)
}

if local.Response.Status != test.expectStatus {
t.Errorf("Expected status '%d', got '%d'",
test.expectStatus, local.Response.Status)
}
}
}
20 changes: 20 additions & 0 deletions attributes/remote.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package attributes

// Remote represents a remote call with request and response data.
type Remote struct {
Request *RemoteRequest `json:"request,omitempty"`
Response *RemoteResponse `json:"response,omitemtpy"`
}

// RemoteRequest represents remote requests details.
type RemoteRequest struct {
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
Traced bool `json:"traced"`
}

// RemoteResponse represents remote response details.
type RemoteResponse struct {
Status int `json:"status"`
ContentLength int `json:"content_length"`
}
35 changes: 35 additions & 0 deletions examples/grpc-client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
pb "github.com/goguardian/aws-xray-go/examples/protobuf/demo"
"github.com/goguardian/aws-xray-go/xray"
"log"
"time"

"google.golang.org/grpc"
)

func main() {
ctx := xray.NewContext("grpc-server-one", nil)
defer xray.Close(ctx)

conn, err := xray.GetGRPCClientConn("127.0.0.1:2000",
grpc.WithInsecure(),
grpc.WithTimeout(10*time.Second))
if err != nil {
panic(err)
}
client := pb.NewDemoClient(conn)

resp, hierr := client.Hi(ctx, &pb.HiRequest{Message: "hola"})
if hierr != nil {
panic(hierr)
}
log.Println(resp.Message)

helloResp, err := client.Hello(ctx, &pb.HelloRequest{Message: "hello"})
if err != nil {
panic(err)
}
log.Println(helloResp.Message)
}
55 changes: 55 additions & 0 deletions examples/grpc-server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
pb "github.com/goguardian/aws-xray-go/examples/protobuf/demo"
"github.com/goguardian/aws-xray-go/xray"
"log"
"net"

"golang.org/x/net/context"
)

const listenAddr = ":2000"
const serviceName = "grpc-server-two"

func main() {
listener, err := net.Listen("tcp", listenAddr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}

server := xray.NewGRPCServer(serviceName)

pb.RegisterDemoServer(server, &grpcServer{})

log.Println("Listening on:", listenAddr)
log.Fatal(server.Serve(listener))
}

type grpcServer struct{}

func (g *grpcServer) Hi(
ctx context.Context,
req *pb.HiRequest,
) (*pb.HiResponse, error) {

ctx = xray.NewContext(serviceName, ctx)
defer xray.Close(ctx)

http, err := xray.GetHTTPClient(ctx)
if err != nil {
panic(err)
}

http.Get("http://www.example.com")

return &pb.HiResponse{Message: "hiya"}, nil
}

func (g *grpcServer) Hello(
ctx context.Context,
req *pb.HelloRequest,
) (*pb.HelloResponse, error) {

return &pb.HelloResponse{Message: "hello"}, nil
}
Loading

0 comments on commit 680a7de

Please sign in to comment.