diff --git a/src/adservice/build.gradle b/src/adservice/build.gradle index 7450826..dde9248 100644 --- a/src/adservice/build.gradle +++ b/src/adservice/build.gradle @@ -10,12 +10,14 @@ buildscript { } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.3' + classpath "gradle.plugin.com.github.sherter.google-java-format:google-java-format-gradle-plugin:0.7.1" } } apply plugin: 'idea' apply plugin: 'java' apply plugin: 'com.google.protobuf' +apply plugin: 'com.github.sherter.google-java-format' repositories { mavenCentral() @@ -23,10 +25,10 @@ repositories { } group = "adservice" -version = "0.1.0-SNAPSHOT" // CURRENT_OPENCENSUS_VERSION +version = "0.1.0-SNAPSHOT" -def opencensusVersion = "0.17.0" // LATEST_OPENCENSUS_RELEASE_VERSION -def grpcVersion = "1.15.0" // CURRENT_GRPC_VERSION +def opencensusVersion = "0.18.0" +def grpcVersion = "1.17.0" def jacksonVersion = "2.9.6" tasks.withType(JavaCompile) { @@ -43,7 +45,9 @@ dependencies { if (speed) { compile fileTree(dir: offlineCompile, include: '*.jar') } else { - compile "com.google.api.grpc:proto-google-common-protos:1.11.0", + compile "com.google.api.grpc:proto-google-common-protos:1.12.0", + "io.opencensus:opencensus-api:${opencensusVersion}", + "io.opencensus:opencensus-contrib-grpc-util:${opencensusVersion}", "io.opencensus:opencensus-exporter-trace-jaeger:${opencensusVersion}", "io.opencensus:opencensus-exporter-stats-stackdriver:${opencensusVersion}", "io.opencensus:opencensus-exporter-trace-stackdriver:${opencensusVersion}", @@ -79,6 +83,10 @@ protobuf { } } +googleJavaFormat { + toolVersion '1.7' +} + // Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code. sourceSets { main { diff --git a/src/adservice/src/main/java/hipstershop/AdService.java b/src/adservice/src/main/java/hipstershop/AdService.java index 7320764..1c04f60 100644 --- a/src/adservice/src/main/java/hipstershop/AdService.java +++ b/src/adservice/src/main/java/hipstershop/AdService.java @@ -16,8 +16,8 @@ package hipstershop; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableListMultimap; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import hipstershop.Demo.Ad; import hipstershop.Demo.AdRequest; @@ -26,49 +26,50 @@ import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.StatusRuntimeException; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; -import io.grpc.stub.StreamObserver; import io.grpc.services.*; +import io.grpc.stub.StreamObserver; import io.opencensus.common.Duration; -import io.opencensus.common.Scope; import io.opencensus.contrib.grpc.metrics.RpcViews; -import io.opencensus.exporter.trace.jaeger.JaegerTraceExporter; -import io.opencensus.exporter.trace.logging.LoggingTraceExporter; 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.AttributeValue; import io.opencensus.trace.Span; -import io.opencensus.trace.SpanBuilder; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; -import io.opencensus.trace.samplers.Samplers; import java.io.IOException; -import java.util.Collection; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public final class AdService { -public class AdService { private static final Logger logger = LogManager.getLogger(AdService.class); - private static final Tracer tracer = Tracing.getTracer(); - private int MAX_ADS_TO_SERVE = 2; + private static int MAX_ADS_TO_SERVE = 2; private Server server; private HealthStatusManager healthMgr; - static final AdService service = new AdService(); + private static final AdService service = new AdService(); + private void start() throws IOException { int port = Integer.parseInt(System.getenv("PORT")); healthMgr = new HealthStatusManager(); - server = ServerBuilder.forPort(port).addService(new AdServiceImpl()) - .addService(healthMgr.getHealthService()).build().start(); + server = + ServerBuilder.forPort(port) + .addService(new AdServiceImpl()) + .addService(healthMgr.getHealthService()) + .build() + .start(); logger.info("Ad Service started, listening on " + port); Runtime.getRuntime() .addShutdownHook( @@ -91,26 +92,20 @@ public class AdService { } } - static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase { + private static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase { /** * Retrieves ads based on context provided in the request {@code AdRequest}. * * @param req the request containing context. - * @param responseObserver the stream observer which gets notified with the value of - * {@code AdResponse} + * @param responseObserver the stream observer which gets notified with the value of {@code + * AdResponse} */ @Override public void getAds(AdRequest req, StreamObserver responseObserver) { AdService service = AdService.getInstance(); - Span parentSpan = tracer.getCurrentSpan(); - SpanBuilder spanBuilder = - tracer - .spanBuilderWithExplicitParent("Retrieve Ads", parentSpan) - .setRecordEvents(true) - .setSampler(Samplers.alwaysSample()); - try (Scope scope = spanBuilder.startScopedSpan()) { - Span span = tracer.getCurrentSpan(); + Span span = tracer.getCurrentSpan(); + try { span.putAttribute("method", AttributeValue.stringAttributeValue("getAds")); List allAds = new ArrayList<>(); logger.info("received ad request (context_words=" + req.getContextKeysList() + ")"); @@ -140,29 +135,29 @@ public class AdService { responseObserver.onCompleted(); } catch (StatusRuntimeException e) { logger.log(Level.WARN, "GetAds Failed", e.getStatus()); - return; + responseObserver.onError(e); } } } - static final ImmutableListMultimap adsMap = createAdsMap(); + private static final ImmutableListMultimap adsMap = createAdsMap(); - Collection getAdsByCategory(String category) { + private Collection getAdsByCategory(String category) { return adsMap.get(category); } private static final Random random = new Random(); - public List getRandomAds() { + private List getRandomAds() { List ads = new ArrayList<>(MAX_ADS_TO_SERVE); Collection allAds = adsMap.values(); - for (int i=0; i createAdsMap() { - Ad camera = Ad.newBuilder().setRedirectUrl("/product/2ZYFJ3GM2N") - .setText("Film camera for sale. 50% off.").build(); - Ad lens = Ad.newBuilder().setRedirectUrl("/product/66VCHSJNUP") - .setText("Vintage camera lens for sale. 20% off.").build(); - Ad recordPlayer = Ad.newBuilder().setRedirectUrl("/product/0PUK6V6EV0") - .setText("Vintage record player for sale. 30% off.").build(); - Ad bike = Ad.newBuilder().setRedirectUrl("/product/9SIQT8TOJO") - .setText("City Bike for sale. 10% off.").build(); - Ad baristaKit = Ad.newBuilder().setRedirectUrl("/product/1YMWWN1N4O") - .setText("Home Barista kitchen kit for sale. Buy one, get second kit for free").build(); - Ad airPlant = Ad.newBuilder().setRedirectUrl("/product/6E92ZMYYFZ") - .setText("Air plants for sale. Buy two, get third one for free").build(); - Ad terrarium = Ad.newBuilder().setRedirectUrl("/product/L9ECAV7KIM") - .setText("Terrarium for sale. Buy one, get second one for free").build(); + private static ImmutableListMultimap createAdsMap() { + Ad camera = + Ad.newBuilder() + .setRedirectUrl("/product/2ZYFJ3GM2N") + .setText("Film camera for sale. 50% off.") + .build(); + Ad lens = + Ad.newBuilder() + .setRedirectUrl("/product/66VCHSJNUP") + .setText("Vintage camera lens for sale. 20% off.") + .build(); + Ad recordPlayer = + Ad.newBuilder() + .setRedirectUrl("/product/0PUK6V6EV0") + .setText("Vintage record player for sale. 30% off.") + .build(); + Ad bike = + Ad.newBuilder() + .setRedirectUrl("/product/9SIQT8TOJO") + .setText("City Bike for sale. 10% off.") + .build(); + Ad baristaKit = + Ad.newBuilder() + .setRedirectUrl("/product/1YMWWN1N4O") + .setText("Home Barista kitchen kit for sale. Buy one, get second kit for free") + .build(); + Ad airPlant = + Ad.newBuilder() + .setRedirectUrl("/product/6E92ZMYYFZ") + .setText("Air plants for sale. Buy two, get third one for free") + .build(); + Ad terrarium = + Ad.newBuilder() + .setRedirectUrl("/product/L9ECAV7KIM") + .setText("Terrarium for sale. Buy one, get second one for free") + .build(); return ImmutableListMultimap.builder() .putAll("photography", camera, lens) .putAll("vintage", camera, lens, recordPlayer) @@ -197,7 +213,7 @@ public class AdService { .build(); } - public static void initStackdriver() { + private static void initStackdriver() { logger.info("Initialize StackDriver"); long sleepTime = 10; /* seconds */ @@ -205,7 +221,7 @@ public class AdService { boolean statsExporterRegistered = false; boolean traceExporterRegistered = false; - for (int i=0; i