Skip to content

Instantly share code, notes, and snippets.

@odeke-em
Created May 30, 2018 21:39
Show Gist options
  • Save odeke-em/69f750885095ce50cbc409a2386495d9 to your computer and use it in GitHub Desktop.
Save odeke-em/69f750885095ce50cbc409a2386495d9 to your computer and use it in GitHub Desktop.
// Copyright 2018, OpenCensus 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
//
// 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 io.ocgrpc.capitalize;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import io.ocgrpc.capitalize.Defs.Payload;
import io.ocgrpc.capitalize.FetchGrpc;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.InterruptedException;
import io.opencensus.common.Duration;
import io.opencensus.contrib.grpc.metrics.RpcViews;
import io.opencensus.exporter.stats.prometheus.PrometheusStatsCollector;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.exporter.trace.jaeger.JaegerTraceExporter;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
import io.opencensus.trace.config.TraceConfig;
import io.opencensus.trace.config.TraceParams;
import io.opencensus.trace.samplers.Samplers;
import io.opencensus.trace.Span;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.prometheus.client.exporter.HTTPServer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Observability;
public class CapitalizeServer {
private final int serverPort;
private Server server;
private static final Tracer tracer = Tracing.getTracer();
private static Jedis jedis = new Jedis("localhost");
public CapitalizeServer(int serverPort) {
this.serverPort = serverPort;
}
static class FetchImpl extends FetchGrpc.FetchImplBase {
@Override
public void capitalize(Payload req, StreamObserver<Payload> responseObserver) {
// For compatibility with earlier than Java 8, instead of Scoped spans
// we'll use the finally construct to end spans.
Span span = CapitalizeServer.tracer.spanBuilder("(*FetchImpl).capitalize").setRecordEvents(true).startSpan();
try {
String orig = req.getData().toString("UTF8");
String capitalized = jedis.get(orig);
if (capitalized == null || capitalized == "") {
span.addAnnotation("Cache miss");
capitalized = orig.toUpperCase();
jedis.set(orig, capitalized);
}
ByteString bs = ByteString.copyFrom(capitalized.getBytes("UTF8"));
Payload resp = Payload.newBuilder().setData(bs).build();
responseObserver.onNext(resp);
} catch(UnsupportedEncodingException e) {
} finally {
span.end();
responseObserver.onCompleted();
}
}
}
public void listenAndServe() throws IOException, InterruptedException {
this.start();
this.server.awaitTermination();
}
private void start() throws IOException {
this.server = ServerBuilder.forPort(this.serverPort).addService(new FetchImpl()).build().start();
System.out.println("Server listening on " + this.serverPort);
Server theServer = this.server;
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
public void run() {
theServer.shutdown();
}
});
}
public static void main(String []args) {
int port = 9876;
CapitalizeServer csrv = new CapitalizeServer(port);
// Next step is to setup OpenCensus and its exporters
try {
setupOpenCensusAndExporters();
} catch (IOException e) {
System.err.println("Failed to setup OpenCensus exporters: " + e + " so proceeding without it");
}
try {
csrv.listenAndServe();
} catch (IOException e) {
System.err.println("Exception encountered while serving: " + e);
} catch(InterruptedException e) {
System.out.println("Caught an interrupt: " + e);
} catch(Exception e) {
System.err.println("Unhandled exception: " + e);
} finally {
}
}
private static void setupOpenCensusAndExporters() throws IOException {
// Register the Redis views
if (true)
Observability.registerAllViews();
// Change the sampling rate
TraceConfig traceConfig = Tracing.getTraceConfig();
traceConfig.updateActiveTraceParams(
traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());
// Register all the gRPC views and enable stats
RpcViews.registerAllViews();
String gcpProjectId = System.getenv().get("OCGRPC_GCP_PROJECTID");
if (gcpProjectId == "") {
gcpProjectId = "census-demos";
}
// Create the Stackdriver stats exporter
StackdriverStatsExporter.createAndRegister(
StackdriverStatsConfiguration.builder()
.setProjectId(gcpProjectId)
.setExportInterval(Duration.create(10, 0))
.build());
// Next create the Stackdriver tracing exporter
StackdriverTraceExporter.createAndRegister(
StackdriverTraceConfiguration.builder()
.setProjectId(gcpProjectId)
.build());
if (false) {
// And then the Prometheus exporter too
PrometheusStatsCollector.createAndRegister();
// Start the Prometheus server
HTTPServer prometheusServer = new HTTPServer(9821, true);
}
// Create the Jaeger exporter
if (false) {
JaegerTraceExporter.createAndRegister("http://localhost:14268/api/traces", "java_capitalize");
}
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.ocgrpc</groupId>
<artifactId>ocgrpc</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>ocgrpc</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<opencensus.version>0.14.0-SNAPSHOT</opencensus.version> <!-- The OpenCensus version to use -->
<grpc.version>1.10.1</grpc.version> <!-- The gRPC version to use with the version of OpenCensus -->
<jedis.jarPath>/Users/emmanuelodeke/Desktop/CloudMemoryStore/redis/java/jedis/target/jedis-3.0.0-SNAPSHOT.jar</jedis.jarPath>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-exporter-stats-prometheus</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_httpserver</artifactId>
<version>0.4.0</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-exporter-trace-jaeger</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-exporter-stats-stackdriver</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-api</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-contrib-grpc-metrics</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-impl</artifactId>
<version>${opencensus.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-exporter-trace-stackdriver</artifactId>
<version>${opencensus.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<programs>
<program>
<id>CapitalizeServer</id>
<mainClass>io.ocgrpc.capitalize.CapitalizeServer</mainClass>
</program>
</programs>
</configuration>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment