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

[hotrod] Add links to traces #2536

Merged
merged 6 commits into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
23 changes: 18 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ We gratefully welcome improvements to documentation as well as to code.
## Getting Started

### Pre-requisites
* Install [Go](https://golang.org/doc/install) and setup GOPATH and add $GOPATH/bin in PATH
* Install [Go](https://golang.org/doc/install) and setup GOPATH and add $GOPATH/bin in PATH

This library uses Go modules to manage dependencies.

Expand Down Expand Up @@ -116,18 +116,32 @@ import (

## Testing guidelines

We strive to maintain as high code coverage as possible. Since `go test` command does not generate
We strive to maintain as high code coverage as possible. The current repository limit is set at 95%,
with some exclusions discussed below.

### Combining code coverage

We use [cover.sh](./scripts/cover.sh) script to run tests and combine code coverage from all packages
(see also [issue # 797](https://github.com/jaegertracing/jaeger/issues/797)).

### Packages with no tests

Since `go test` command does not generate
code coverage information for packages that have no test files, we have a build step (`make nocover`)
that breaks the build when such packages are discovered, with an error like this:
that breaks the build when such packages are discovered, with the following error:

```
error: at least one *_test.go file must be in all directories with go files
so that they are counted for code coverage.
If no tests are possible for a package (e.g. it only defines types), create empty_test.go
```

As the message says, all packages are required to have at least one `*_test.go` file.

### Excluding packages from testing

There are conditions that cannot be tested without external dependencies, such as a function that
creates a gocql.Session, because it requires an active connection to Cassandra database. It is
creates a `gocql.Session`, because it requires an active connection to Cassandra database. It is
recommended to isolate such functions in a separate package with bare minimum of code and add a
file `.nocover` to exclude the package from coverage calculations. The file should contain
a comment explaining why it is there, for example:
Expand All @@ -145,4 +159,3 @@ Before merging a PR make sure:

Merge the PR by using "Squash and merge" option on Github. Avoid creating merge commits.
After the merge make sure referenced issues were closed.

15 changes: 13 additions & 2 deletions examples/hotrod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ Jaeger UI can be accessed at http://localhost:16686.

```bash
git clone [email protected]:jaegertracing/jaeger.git jaeger
cd jaeger/examples/hotrod
go run ./main.go all
cd jaeger
go run ./examples/hotrod/main.go all
```

### Run HotROD from docker
Expand All @@ -73,3 +73,14 @@ The app exposes metrics in either Go's `expvar` format (by default) or in Promet

[hotrod-tutorial]: https://medium.com/@YuriShkuro/take-opentracing-for-a-hotrod-ride-f6e3141f7941
[hotrod-openshift]: https://blog.openshift.com/openshift-commons-briefing-82-distributed-tracing-with-jaeger-prometheus-on-kubernetes/

## Linking to traces

The HotROD UI can generate links to the Jaeger UI to find traces corresponding
to each executed request. By default it uses the standard Jaeger UI address
http://localhost:16686, but if your Jaeger UI is running at a different address,
it can be customized via `-j <address>` flag passed to HotROD, e.g.

```
go run ./examples/hotrod/main.go all -j http://jaeger-ui:16686
```
1 change: 1 addition & 0 deletions examples/hotrod/cmd/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var frontendCmd = &cobra.Command{
options.CustomerHostPort = net.JoinHostPort("0.0.0.0", strconv.Itoa(customerPort))
options.RouteHostPort = net.JoinHostPort("0.0.0.0", strconv.Itoa(routePort))
options.Basepath = basepath
options.JaegerUI = jaegerUI

zapLogger := logger.With(zap.String("service", "frontend"))
logger := log.NewFactory(zapLogger)
Expand Down
2 changes: 2 additions & 0 deletions examples/hotrod/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ var (
routePort int

basepath string
jaegerUI string
)

// RootCmd represents the base command when called without any subcommands
Expand Down Expand Up @@ -77,6 +78,7 @@ func init() {

// Flag for serving frontend at custom basepath url
RootCmd.PersistentFlags().StringVarP(&basepath, "basepath", "b", "", `Basepath for frontend service(default "/")`)
RootCmd.PersistentFlags().StringVarP(&jaegerUI, "jaeger-ui", "j", "http://localhost:16686", "Address of Jaeger UI to create [find trace] links")

rand.Seed(int64(time.Now().Nanosecond()))
logger, _ = zap.NewDevelopment(
Expand Down
2 changes: 2 additions & 0 deletions examples/hotrod/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ services:
command: ["all"]
environment:
- JAEGER_AGENT_HOST=jaeger
# Note: if your application is using Node.js Jaeger Client, you need port 6832,
# unless issue https://github.com/jaegertracing/jaeger/issues/1596 is resolved.
- JAEGER_AGENT_PORT=6831
networks:
- jaeger-example
Expand Down
59 changes: 31 additions & 28 deletions examples/hotrod/services/frontend/gen_assets.go

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

17 changes: 16 additions & 1 deletion examples/hotrod/services/frontend/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type Server struct {
bestETA *bestETA
assetFS http.FileSystem
basepath string
jaegerUI string
}

// ConfigOptions used to make sure service clients
Expand All @@ -46,6 +47,7 @@ type ConfigOptions struct {
CustomerHostPort string
RouteHostPort string
Basepath string
JaegerUI string
}

// NewServer creates a new frontend.Server
Expand All @@ -58,6 +60,7 @@ func NewServer(options ConfigOptions, tracer opentracing.Tracer, logger log.Fact
bestETA: newBestETA(tracer, logger, options),
assetFS: assetFS,
basepath: options.Basepath,
jaegerUI: options.JaegerUI,
}
}

Expand All @@ -73,9 +76,17 @@ func (s *Server) createServeMux() http.Handler {
p := path.Join("/", s.basepath)
mux.Handle(p, http.StripPrefix(p, http.FileServer(s.assetFS)))
mux.Handle(path.Join(p, "/dispatch"), http.HandlerFunc(s.dispatch))
mux.Handle(path.Join(p, "/config"), http.HandlerFunc(s.config))
return mux
}

func (s *Server) config(w http.ResponseWriter, r *http.Request) {
config := map[string]string{
"jaeger": s.jaegerUI,
}
s.writeResponse(config, w, r)
}

func (s *Server) dispatch(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
s.logger.For(ctx).Info("HTTP request received", zap.String("method", r.Method), zap.Stringer("url", r.URL))
Expand All @@ -97,9 +108,13 @@ func (s *Server) dispatch(w http.ResponseWriter, r *http.Request) {
return
}

s.writeResponse(response, w, r)
}

func (s *Server) writeResponse(response interface{}, w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(response)
if httperr.HandleError(w, err, http.StatusInternalServerError) {
s.logger.For(ctx).Error("cannot marshal response", zap.Error(err))
s.logger.For(r.Context()).Error("cannot marshal response", zap.Error(err))
return
}

Expand Down
20 changes: 18 additions & 2 deletions examples/hotrod/services/frontend/web_assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ <h4><em>Rides On Demand</em></h4>
var clientUUID = Math.round(Math.random() * 10000);
var lastRequestID = 0;

$(".uuid").html("Your web client's id: <strong>" + clientUUID + "</strong>");
$(".uuid").html(`Your web client's id: <strong>${clientUUID}</strong>`);

$(".hotrod-button").click(function(evt) {
lastRequestID++;
Expand All @@ -78,14 +78,30 @@ <h4><em>Rides On Demand</em></h4>
var pathPrefix = window.location.pathname;
pathPrefix = pathPrefix != "/" ? pathPrefix : '';

var config = {};
$.ajax(pathPrefix + '/config?nonse=' + Math.random(), {
method: 'GET',
success: function(data, textStatus) {
var after = Date.now();
console.log(data);
config = data;
},
});

$.ajax(pathPrefix + '/dispatch?customer=' + customer + '&nonse=' + Math.random(), {
headers: headers,
method: 'GET',
success: function(data, textStatus) {
var after = Date.now();
console.log(data);
var duration = formatDuration(data.ETA);
freshCar.html('HotROD <b>' + data.Driver + '</b> arriving in ' + duration + ' [req: ' + requestID + ', latency: ' + (after-before) + 'ms]');
var traceLink = '';
if (config && config['jaeger']) {
var jaeger = config['jaeger'];
var trace = `${jaeger}/search?limit=20&lookback=1h&service=frontend&tags=%7B%22driver%22%3A%22${data.Driver}%22%7D`;
traceLink = ` [<a href="${trace}" target="_blank">find trace</a>]`;
}
freshCar.html(`HotROD <b>${data.Driver}</b> arriving in ${duration} [req: ${requestID}, latency: ${after-before}ms] ${traceLink}`);
},
});
});
Expand Down