Adds option to disable Stackdriver Export (#293)

This commit is contained in:
Megan O'Keefe 2020-02-20 15:26:44 -05:00 committed by GitHub
parent 595bd21d38
commit 90f9287f3a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 267 additions and 75 deletions

2
.gitignore vendored
View file

@ -9,3 +9,5 @@ pkg/
.idea .idea
.skaffold-*.yaml .skaffold-*.yaml
.kubernetes-manifests-*/ .kubernetes-manifests-*/
.project
.eclipse.buildship.core.prefs

View file

@ -34,6 +34,10 @@ spec:
env: env:
- name: PORT - name: PORT
value: "9555" value: "9555"
# - name: DISABLE_STATS
# value: "1"
# - name: DISABLE_TRACING
# value: "1"
#- name: JAEGER_SERVICE_ADDR #- name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268" # value: "jaeger-collector:14268"
resources: resources:

View file

@ -51,6 +51,12 @@ spec:
value: "currencyservice:7000" value: "currencyservice:7000"
- name: CART_SERVICE_ADDR - name: CART_SERVICE_ADDR
value: "cartservice:7070" value: "cartservice:7070"
# - name: DISABLE_STATS
# value: "1"
# - name: DISABLE_TRACING
# value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: JAEGER_SERVICE_ADDR # - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268" # value: "jaeger-collector:14268"
resources: resources:

View file

@ -35,6 +35,12 @@ spec:
env: env:
- name: PORT - name: PORT
value: "7000" value: "7000"
# - name: DISABLE_TRACING
# value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: DISABLE_DEBUGGER
# value: "1"
readinessProbe: readinessProbe:
exec: exec:
command: ["/bin/grpc_health_probe", "-addr=:7000"] command: ["/bin/grpc_health_probe", "-addr=:7000"]

View file

@ -34,8 +34,10 @@ spec:
env: env:
- name: PORT - name: PORT
value: "8080" value: "8080"
- name: ENABLE_PROFILER # - name: DISABLE_TRACING
value: "0" # value: "1"
- name: DISABLE_PROFILER
value: "1"
readinessProbe: readinessProbe:
periodSeconds: 5 periodSeconds: 5
exec: exec:

View file

@ -65,6 +65,10 @@ spec:
value: "checkoutservice:5050" value: "checkoutservice:5050"
- name: AD_SERVICE_ADDR - name: AD_SERVICE_ADDR
value: "adservice:9555" value: "adservice:9555"
# - name: DISABLE_TRACING
# value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: JAEGER_SERVICE_ADDR # - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268" # value: "jaeger-collector:14268"
resources: resources:

View file

@ -34,15 +34,20 @@ spec:
env: env:
- name: PORT - name: PORT
value: "3550" value: "3550"
# - name: DISABLE_STATS
# value: "1"
# - name: DISABLE_TRACING
# value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268"
readinessProbe: readinessProbe:
exec: exec:
command: ["/bin/grpc_health_probe", "-addr=:3550"] command: ["/bin/grpc_health_probe", "-addr=:3550"]
livenessProbe: livenessProbe:
exec: exec:
command: ["/bin/grpc_health_probe", "-addr=:3550"] command: ["/bin/grpc_health_probe", "-addr=:3550"]
# env:
# - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268"
resources: resources:
requests: requests:
cpu: 100m cpu: 100m

View file

@ -44,8 +44,12 @@ spec:
value: "8080" value: "8080"
- name: PRODUCT_CATALOG_SERVICE_ADDR - name: PRODUCT_CATALOG_SERVICE_ADDR
value: "productcatalogservice:3550" value: "productcatalogservice:3550"
- name: ENABLE_PROFILER # - name: DISABLE_TRACING
value: "0" # value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: DISABLE_DEBUGGER
# value: "1"
resources: resources:
requests: requests:
cpu: 100m cpu: 100m

View file

@ -33,6 +33,14 @@ spec:
env: env:
- name: PORT - name: PORT
value: "50051" value: "50051"
# - name: DISABLE_STATS
# value: "1"
# - name: DISABLE_TRACING
# value: "1"
# - name: DISABLE_PROFILER
# value: "1"
# - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268"
readinessProbe: readinessProbe:
periodSeconds: 5 periodSeconds: 5
exec: exec:
@ -40,9 +48,6 @@ spec:
livenessProbe: livenessProbe:
exec: exec:
command: ["/bin/grpc_health_probe", "-addr=:50051"] command: ["/bin/grpc_health_probe", "-addr=:50051"]
# env:
# - name: JAEGER_SERVICE_ADDR
# value: "jaeger-collector:14268"
resources: resources:
requests: requests:
cpu: 100m cpu: 100m

View file

@ -213,21 +213,18 @@ public final class AdService {
.build(); .build();
} }
private static void initStackdriver() { private static void initStats() {
logger.info("Initialize Stackdriver"); if (System.getenv("DISABLE_STATS") != null) {
logger.info("Stats disabled.");
return;
}
logger.info("Stats enabled");
long sleepTime = 10; /* seconds */ long sleepTime = 10; /* seconds */
int maxAttempts = 5; int maxAttempts = 5;
boolean statsExporterRegistered = false; boolean statsExporterRegistered = false;
boolean traceExporterRegistered = false;
for (int i = 0; i < maxAttempts; i++) { for (int i = 0; i < maxAttempts; i++) {
try { try {
if (!traceExporterRegistered) {
StackdriverTraceExporter.createAndRegister(
StackdriverTraceConfiguration.builder().build());
traceExporterRegistered = true;
}
if (!statsExporterRegistered) { if (!statsExporterRegistered) {
StackdriverStatsExporter.createAndRegister( StackdriverStatsExporter.createAndRegister(
StackdriverStatsConfiguration.builder() StackdriverStatsConfiguration.builder()
@ -240,7 +237,7 @@ public final class AdService {
logger.log( logger.log(
Level.WARN, Level.WARN,
"Failed to register Stackdriver Exporter." "Failed to register Stackdriver Exporter."
+ " Tracing and Stats data will not reported to Stackdriver. Error message: " + " Stats data will not reported to Stackdriver. Error message: "
+ e.toString()); + e.toString());
} else { } else {
logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds "); logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds ");
@ -252,9 +249,50 @@ public final class AdService {
} }
} }
} }
logger.info("Stackdriver initialization complete."); logger.info("Stats enabled - Stackdriver Exporter initialized.");
} }
private static void initTracing() {
if (System.getenv("DISABLE_TRACING") != null) {
logger.info("Tracing disabled.");
return;
}
logger.info("Tracing enabled");
long sleepTime = 10; /* seconds */
int maxAttempts = 5;
boolean traceExporterRegistered = false;
for (int i = 0; i < maxAttempts; i++) {
try {
if (!traceExporterRegistered) {
StackdriverTraceExporter.createAndRegister(
StackdriverTraceConfiguration.builder().build());
traceExporterRegistered = true;
}
} catch (Exception e) {
if (i == (maxAttempts - 1)) {
logger.log(
Level.WARN,
"Failed to register Stackdriver Exporter."
+ " Tracing data will not reported to Stackdriver. Error message: "
+ e.toString());
} else {
logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds ");
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(sleepTime));
} catch (Exception se) {
logger.log(Level.WARN, "Exception while sleeping" + se.toString());
}
}
}
}
logger.info("Tracing enabled - Stackdriver exporter initialized.");
}
private static void initJaeger() { private static void initJaeger() {
String jaegerAddr = System.getenv("JAEGER_SERVICE_ADDR"); String jaegerAddr = System.getenv("JAEGER_SERVICE_ADDR");
if (jaegerAddr != null && !jaegerAddr.isEmpty()) { if (jaegerAddr != null && !jaegerAddr.isEmpty()) {
@ -282,7 +320,8 @@ public final class AdService {
new Thread( new Thread(
new Runnable() { new Runnable() {
public void run() { public void run() {
initStackdriver(); initStats();
initTracing();
} }
}) })
.start(); .start();

View file

@ -69,8 +69,19 @@ type checkoutService struct {
} }
func main() { func main() {
go initTracing() if os.Getenv("DISABLE_TRACING") == "" {
go initProfiling("checkoutservice", "1.0.0") log.Info("Tracing enabled.")
go initTracing()
} else {
log.Info("Tracing disabled.")
}
if os.Getenv("DISABLE_PROFILER") == "" {
log.Info("Profiling enabled.")
go initProfiling("checkoutservice", "1.0.0")
} else {
log.Info("Profiling disabled.")
}
port := listenPort port := listenPort
if os.Getenv("PORT") != "" { if os.Getenv("PORT") != "" {
@ -91,7 +102,15 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
srv := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
var srv *grpc.Server
if os.Getenv("DISABLE_STATS") == "" {
log.Info("Stats enabled.")
srv = grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
} else {
log.Info("Stats disabled.")
srv = grpc.NewServer()
}
pb.RegisterCheckoutServiceServer(srv, svc) pb.RegisterCheckoutServiceServer(srv, svc)
healthpb.RegisterHealthServer(srv, svc) healthpb.RegisterHealthServer(srv, svc)
log.Infof("starting to listen on tcp: %q", lis.Addr().String()) log.Infof("starting to listen on tcp: %q", lis.Addr().String())

View file

@ -14,19 +14,40 @@
* limitations under the License. * limitations under the License.
*/ */
require('@google-cloud/profiler').start({ if(process.env.DISABLE_PROFILER) {
serviceContext: { console.log("Profiler disabled.")
service: 'currencyservice', }
version: '1.0.0' else {
} console.log("Profiler enabled.")
}); require('@google-cloud/profiler').start({
require('@google-cloud/trace-agent').start(); serviceContext: {
require('@google-cloud/debug-agent').start({ service: 'currencyservice',
serviceContext: { version: '1.0.0'
service: 'currencyservice', }
version: 'VERSION' });
} }
});
if(process.env.DISABLE_TRACING) {
console.log("Tracing disabled.")
}
else {
console.log("Tracing enabled.")
require('@google-cloud/trace-agent').start();
}
if(process.env.DISABLE_DEBUGGER) {
console.log("Debugger disabled.")
}
else {
console.log("Debugger enabled.")
require('@google-cloud/debug-agent').start({
serviceContext: {
service: 'currencyservice',
version: 'VERSION'
}
});
}
const path = require('path'); const path = require('path');
const grpc = require('grpc'); const grpc = require('grpc');

View file

@ -29,20 +29,16 @@ from grpc_health.v1 import health_pb2
from grpc_health.v1 import health_pb2_grpc from grpc_health.v1 import health_pb2_grpc
from opencensus.trace.exporters import stackdriver_exporter from opencensus.trace.exporters import stackdriver_exporter
from opencensus.trace.exporters import print_exporter
from opencensus.trace.ext.grpc import server_interceptor from opencensus.trace.ext.grpc import server_interceptor
from opencensus.common.transports.async_ import AsyncTransport
from opencensus.trace.samplers import always_on from opencensus.trace.samplers import always_on
# import googleclouddebugger # import googleclouddebugger
import googlecloudprofiler import googlecloudprofiler
try: from logger import getJSONLogger
sampler = always_on.AlwaysOnSampler() logger = getJSONLogger('emailservice-server')
exporter = stackdriver_exporter.StackdriverExporter(
project_id=os.environ.get('GCP_PROJECT_ID'),
transport=AsyncTransport)
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(sampler, exporter)
except:
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor()
# try: # try:
# googleclouddebugger.enable( # googleclouddebugger.enable(
@ -52,9 +48,6 @@ except:
# except: # except:
# pass # pass
from logger import getJSONLogger
logger = getJSONLogger('emailservice-server')
# Loads confirmation email template from file # Loads confirmation email template from file
env = Environment( env = Environment(
loader=FileSystemLoader('templates'), loader=FileSystemLoader('templates'),
@ -171,16 +164,33 @@ def initStackdriverProfiling():
logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up") logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
return return
if __name__ == '__main__': if __name__ == '__main__':
logger.info('starting the email service in dummy mode.') logger.info('starting the email service in dummy mode.')
# Profiler
try: try:
enable_profiler = os.environ["ENABLE_PROFILER"] if "DISABLE_PROFILER" in os.environ:
if enable_profiler != "1":
raise KeyError() raise KeyError()
else: else:
logger.info("Profiler enabled.")
initStackdriverProfiling() initStackdriverProfiling()
except KeyError: except KeyError:
logger.info("Skipping Stackdriver Profiler Python agent initialization. Set environment variable ENABLE_PROFILER=1 to enable.") logger.info("Profiler disabled.")
# Tracing
try:
if "DISABLE_TRACING" in os.environ:
raise KeyError()
else:
logger.info("Tracing enabled.")
sampler = always_on.AlwaysOnSampler()
exporter = stackdriver_exporter.StackdriverExporter(
project_id=os.environ.get('GCP_PROJECT_ID'),
transport=AsyncTransport)
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(sampler, exporter)
except KeyError:
logger.info("Tracing disabled.")
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor()
start(dummy_mode = True) start(dummy_mode = True)

View file

@ -94,8 +94,19 @@ func main() {
} }
log.Out = os.Stdout log.Out = os.Stdout
go initProfiling(log, "frontend", "1.0.0") if os.Getenv("DISABLE_TRACING") == "" {
go initTracing(log) log.Info("Tracing enabled.")
go initTracing(log)
} else {
log.Info("Tracing disabled.")
}
if os.Getenv("DISABLE_PROFILER") == "" {
log.Info("Profiling enabled.")
go initProfiling(log, "frontend", "1.0.0")
} else {
log.Info("Profiling disabled.")
}
srvPort := port srvPort := port
if os.Getenv("PORT") != "" { if os.Getenv("PORT") != "" {

View file

@ -74,8 +74,20 @@ func init() {
} }
func main() { func main() {
go initTracing() if os.Getenv("DISABLE_TRACING") == "" {
go initProfiling("productcatalogservice", "1.0.0") log.Info("Tracing enabled.")
go initTracing()
} else {
log.Info("Tracing disabled.")
}
if os.Getenv("DISABLE_PROFILER") == "" {
log.Info("Profiling enabled.")
go initProfiling("productcatalogservice", "1.0.0")
} else {
log.Info("Profiling disabled.")
}
flag.Parse() flag.Parse()
// set injected latency // set injected latency
@ -119,8 +131,17 @@ func run(port string) string {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
srv := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{})) var srv *grpc.Server
if os.Getenv("DISABLE_STATS") == "" {
log.Info("Stats enabled.")
srv = grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
} else {
log.Info("Stats disabled.")
srv = grpc.NewServer()
}
svc := &productCatalog{} svc := &productCatalog{}
pb.RegisterProductCatalogServiceServer(srv, svc) pb.RegisterProductCatalogServiceServer(srv, svc)
healthpb.RegisterHealthServer(srv, svc) healthpb.RegisterHealthServer(srv, svc)
go srv.Serve(l) go srv.Serve(l)

View file

@ -26,6 +26,7 @@ import grpc
from opencensus.trace.exporters import print_exporter from opencensus.trace.exporters import print_exporter
from opencensus.trace.exporters import stackdriver_exporter from opencensus.trace.exporters import stackdriver_exporter
from opencensus.trace.ext.grpc import server_interceptor from opencensus.trace.ext.grpc import server_interceptor
from opencensus.common.transports.async_ import AsyncTransport
from opencensus.trace.samplers import always_on from opencensus.trace.samplers import always_on
import demo_pb2 import demo_pb2
@ -89,32 +90,45 @@ if __name__ == "__main__":
logger.info("initializing recommendationservice") logger.info("initializing recommendationservice")
try: try:
enable_profiler = os.environ["ENABLE_PROFILER"] if "DISABLE_PROFILER" in os.environ:
if enable_profiler != "1":
raise KeyError() raise KeyError()
else: else:
logger.info("Profiler enabled.")
initStackdriverProfiling() initStackdriverProfiling()
except KeyError: except KeyError:
logger.info("Skipping Stackdriver Profiler Python agent initialization. Set environment variable ENABLE_PROFILER=1 to enable.") logger.info("Profiler disabled.")
try: try:
if "DISABLE_TRACING" in os.environ:
raise KeyError()
else:
logger.info("Tracing enabled.")
sampler = always_on.AlwaysOnSampler() sampler = always_on.AlwaysOnSampler()
exporter = stackdriver_exporter.StackdriverExporter( exporter = stackdriver_exporter.StackdriverExporter(
project_id=os.environ.get('GCP_PROJECT_ID'), project_id=os.environ.get('GCP_PROJECT_ID'),
transport=AsyncTransport) transport=AsyncTransport)
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(sampler, exporter) tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(sampler, exporter)
except: except KeyError:
logger.info("Tracing disabled.")
tracer_interceptor = server_interceptor.OpenCensusServerInterceptor() tracer_interceptor = server_interceptor.OpenCensusServerInterceptor()
try: try:
googleclouddebugger.enable( if "DISABLE_DEBUGGER" in os.environ:
module='recommendationserver', raise KeyError()
version='1.0.0' else:
) logger.info("Debugger enabled.")
except Exception, err: try:
logger.error("could not enable debugger") googleclouddebugger.enable(
logger.error(traceback.print_exc()) module='recommendationserver',
pass version='1.0.0'
)
except Exception, err:
logger.error("Could not enable debugger")
logger.error(traceback.print_exc())
pass
except KeyError:
logger.info("Debugger disabled.")
port = os.environ.get('PORT', "8080") port = os.environ.get('PORT', "8080")
catalog_addr = os.environ.get('PRODUCT_CATALOG_SERVICE_ADDR', '') catalog_addr = os.environ.get('PRODUCT_CATALOG_SERVICE_ADDR', '')

View file

@ -58,8 +58,19 @@ func init() {
} }
func main() { func main() {
go initTracing() if os.Getenv("DISABLE_TRACING") == "" {
go initProfiling("shippingservice", "1.0.0") log.Info("Tracing enabled.")
go initTracing()
} else {
log.Info("Tracing disabled.")
}
if os.Getenv("DISABLE_PROFILER") == "" {
log.Info("Profiling enabled.")
go initProfiling("shippingservice", "1.0.0")
} else {
log.Info("Profiling disabled.")
}
port := defaultPort port := defaultPort
if value, ok := os.LookupEnv("PORT"); ok { if value, ok := os.LookupEnv("PORT"); ok {
@ -71,7 +82,15 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
srv := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
var srv *grpc.Server
if os.Getenv("DISABLE_STATS") == "" {
log.Info("Stats enabled.")
srv = grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
} else {
log.Info("Stats disabled.")
srv = grpc.NewServer()
}
svc := &server{} svc := &server{}
pb.RegisterShippingServiceServer(srv, svc) pb.RegisterShippingServiceServer(srv, svc)
healthpb.RegisterHealthServer(srv, svc) healthpb.RegisterHealthServer(srv, svc)