Skip to content

Commit

Permalink
initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
brharrington committed Jul 18, 2014
1 parent 54a2675 commit 15e3d13
Show file tree
Hide file tree
Showing 104 changed files with 7,951 additions and 3 deletions.
106 changes: 103 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,104 @@
spectator
=========

tbd
# Spectator

Simple library for instrumenting code to record dimensional time series.

## Requirements

* Java 7 or higher.

## Dependencies

To instrument your code you need to depend on the api library. This provides the minimal interfaces
for you to code against and build test cases. The only dependency is slf4j.

```
com.netflix.spectator:spectator-api:latest.release
```

If running at Netflix with the standard platform, use the spectator-nflx library to automatically
setup and initalize with the correct bindings to report data to internal tools like Atlas and
Chronos.

```
com.netflix.spectator:spectator-nflx:latest.release
```

## Instrumenting Code

Suppose we have a server and we want to keep track of:

* Number of requests received with dimensions for breaking down by status code, country, and
the exception type if the request fails in an unexpected way.
* Latency for handling requests.
* Summary of the response sizes.
* Current number of active connections on the server.

Here is some sample code that does that:

```java
// The Spectator class provides a static lookup for the default registry
Server s = new Server(Spectator.registry());

public class Server {
private final ExtendedRegistry registry;
private final Id requestCountId;
private final Timer requestLatency;
private final DistributionSummary responseSizes;

// We can pass in the registry to make unit testing easier
public Server(ExtendedRegistry registry) {
this.registry = registry;

// Create a base id for the request count. The id will get refined with additional dimensions
// when we receive a request.
requestCountId = registry.createId("server.requestCount");

// Create a timer for tracking the latency. The reference can be held onto to avoid
// additional lookup cost in critical paths.
requestLatency = registry.timer("server.requestLatency");

// Create a distribution summary meter for tracking the response sizes.
responseSizes = registry.distributionSummary("server.responseSizes");

// Gauge type that can be sampled. In this case it will invoke the specified method via
// reflection to get the value. The registry will keep a weak reference to the object passed
// in so that registration will not prevent garbage collection of the server object.
registry.methodValue("server.numConnections", this, "getNumConnections");
}

public Response handle(Request req) {
final long s = System.nanoTime();
try {
Response res = doSomething(req);

// Update the counter id with dimensions based on the request. The counter will then
// be looked up in the registry which should be fairly cheap, such as lookup of id object
// in a ConcurrentHashMap, it is more expensive than having a local variable set to the
// counter.
final Id cntId = requestCountId
.withTag("country", req.country())
.withTag("status", res.status());
registry.counter(cntId).increment();

responseSizes.record(res.body().size());

return res;
} catch (Exception e) {
final Id cntId = requestCountId
.withTag("country", req.country())
.withTag("status", "exception")
.withTag("error", e.getClass().getSimpleName());
registry.counter(cntId).increment();
throw e;
} finally {
// Update the latency timer. This should typically be done in a finally block.
requestLatency.record(System.nanoTime() - s, TimeUnit.NANOSECONDS);
}
}

public int getNumConnections() {
// however we determine the current number of connections on the server
}
}
```
139 changes: 139 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@

// Establish version and status
ext.githubProjectName = 'spectator'

buildscript {
repositories {
mavenLocal()
mavenCentral()
}
apply from: file('gradle/buildscript.gradle'), to: buildscript
}

allprojects {
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'idea'

repositories {
mavenLocal()
mavenCentral()
}

jacoco {
toolVersion = "0.7.1.201405082137"
}
}

apply from: file('gradle/convention.gradle')
apply from: file('gradle/maven.gradle')
apply from: file('gradle/check.gradle')
apply from: file('gradle/license.gradle')
apply from: file('gradle/release.gradle')

subprojects {
group = "com.netflix.${githubProjectName}"

sourceCompatibility = 1.7
targetCompatibility = 1.7

tasks.withType(Compile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}

javadoc {
options {
links = ['http://docs.oracle.com/javase/7/docs/api/']
}
}

dependencies {
compile 'org.slf4j:slf4j-api:1.7.6'
testCompile 'junit:junit:4.10'
testCompile 'nl.jqno.equalsverifier:equalsverifier:1.4.1'
}

jacocoTestReport {
additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
reports {
xml.enabled false
csv.enabled false
html.destination "${buildDir}/reports/jacoco"
}
}

task copyDepsToBuild << {
['compile', 'runtime', 'testCompile', 'testRuntime'].each { conf ->
delete "${buildDir}/dependencies/${conf}"
copy {
from configurations[conf]
into "${buildDir}/dependencies/${conf}"
}
}
}
}

project(':spectator-api') {

javadoc {
options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
title "Spectator"
}

task(checkCompatibility, dependsOn: 'jar', type: JavaExec) {
// There is probably a better way, but we remove "-SNAPSHOT" from the name if the archive
// doesn't exist because release plugin changes the name.
main = 'com.googlecode.japi.checker.cli.Main'
classpath = files("$projectDir/../codequality/japi-checker-cli-0.2.0-SNAPSHOT.jar")
args = [
"$projectDir/../codequality/spectator-api-BASELINE.jar",
(jar.archivePath.exists())
? jar.archivePath.path
: jar.archivePath.path.replace("-SNAPSHOT", "")
]
}

build {
it.dependsOn checkCompatibility
}
}

project(':spectator-nflx') {
dependencies {
compile project(':spectator-api')
compile project(':spectator-ext-gc')
compile project(':spectator-reg-servo')
compile 'com.netflix.archaius:archaius-core:latest.release'
compile 'com.netflix.governator:governator:latest.release'
compile 'com.netflix.ribbon:ribbon-core:0.3.+'
compile 'com.netflix.ribbon:ribbon-eureka:0.3.+'
compile 'com.netflix.ribbon:ribbon-httpclient:0.3.+'
}
}

project(':spectator-ext-gc') {
dependencies {
compile project(':spectator-api')
}
}

project(':spectator-reg-servo') {
dependencies {
compile project(':spectator-api')
compile 'com.netflix.servo:servo-core:latest.release'
}
}

project(':spectator-reg-metrics2') {
dependencies {
compile project(':spectator-api')
compile 'com.yammer.metrics:metrics-core:2.2.0'
}
}

project(':spectator-reg-metrics3') {
dependencies {
compile project(':spectator-api')
compile 'com.codahale.metrics:metrics-core:3.0.2'
}
}
13 changes: 13 additions & 0 deletions codequality/HEADER
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright ${year} Netflix, Inc.

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.
Loading

0 comments on commit 15e3d13

Please sign in to comment.