Add datacenter tag to entry-spans

This will add a random "datacenter" tag on the entries where
supported to improve showcasing geo capabilities.
This commit is contained in:
Cedric Ziel
2020-11-02 12:08:31 +01:00
parent a11b90275c
commit 4745f2393c
10 changed files with 201 additions and 7 deletions

View File

@@ -48,6 +48,24 @@ app.use((req, res, next) => {
next();
});
app.use((req, res, next) => {
let dcs = [
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
];
let span = instana.currentSpan();
span.annotate('custom.sdk.tags.datacenter', dcs[Math.floor(Math.random() * dcs.length)]);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

View File

@@ -38,6 +38,24 @@ app.use((req, res, next) => {
next();
});
app.use((req, res, next) => {
let dcs = [
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
];
let span = instana.currentSpan();
span.annotate('custom.sdk.tags.datacenter', dcs[Math.floor(Math.random() * dcs.length)]);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

View File

@@ -26,6 +26,18 @@ var (
rabbitCloseError chan *amqp.Error
rabbitReady chan bool
errorPercent int
dataCenters = []string{
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4",
}
)
func connectToRabbitMQ(uri string) *amqp.Connection {
@@ -115,6 +127,9 @@ func createSpan(headers map[string]interface{}, order string) {
log.Println("Creating child span")
// create child span
span = tracer.StartSpan("getOrder", ot.ChildOf(spanContext))
fakeDataCenter := dataCenters[rand.Intn(len(dataCenters))]
span.SetTag("datacenter", fakeDataCenter)
} else {
log.Println(err)
log.Println("Failed to get context from headers")
@@ -154,6 +169,8 @@ func processSale(parentSpan ot.Span) {
}
func main() {
rand.Seed(time.Now().Unix())
// Instana tracing
ot.InitGlobalTracer(instana.NewTracerWithOptions(&instana.Options{
Service: Service,

View File

@@ -1,3 +1,5 @@
import random
import instana
import os
import sys
@@ -171,6 +173,29 @@ def countItems(items):
return count
class InstanaDataCenterMiddleware():
data_centers = [
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
]
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
span = ot.tracer.active_span
span.log_kv({'datacenter': random.choice(self.data_centers)})
return self.app(environ, start_response)
# RabbitMQ
publisher = Publisher(app.logger)
@@ -182,4 +207,5 @@ if __name__ == "__main__":
app.logger.info('Payment gateway {}'.format(PAYMENT_GATEWAY))
port = int(os.getenv("SHOP_PAYMENT_PORT", "8080"))
app.logger.info('Starting on port {}'.format(port))
app.wsgi_app = InstanaDataCenterMiddleware(app.wsgi_app)
app.run(host='0.0.0.0', port=port)

View File

@@ -13,7 +13,8 @@
"symfony/dependency-injection": "^5.0",
"symfony/framework-bundle": "^5.0",
"doctrine/annotations": "^1.10",
"symfony/monolog-bundle": "^3.5"
"symfony/monolog-bundle": "^3.5",
"instana/instana-php-sdk": "^1.10"
},
"autoload": {
"psr-4": {

View File

@@ -0,0 +1,46 @@
<?php
namespace Instana\RobotShop\Ratings\EventListener;
use Instana\InstanaRuntimeException;
use Instana\Tracer;
use Psr\Log\LoggerInterface;
class InstanaDataCenterListener
{
private static $dataCenters = [
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
];
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function __invoke()
{
try {
$entry = Tracer::getEntrySpan();
$dataCenter = self::$dataCenters[array_rand(self::$dataCenters)];
$entry->annotate('datacenter', $dataCenter);
$this->logger->info(sprintf('Annotated DataCenter %s', $dataCenter));
} catch (InstanaRuntimeException $exception) {
$this->logger->error('Unable to annotate entry span: %s', $exception->getMessage());
}
}
}

View File

@@ -6,6 +6,7 @@ namespace Instana\RobotShop\Ratings;
use Instana\RobotShop\Ratings\Controller\HealthController;
use Instana\RobotShop\Ratings\Controller\RatingsApiController;
use Instana\RobotShop\Ratings\EventListener\InstanaDataCenterListener;
use Instana\RobotShop\Ratings\Integration\InstanaHeadersLoggingProcessor;
use Instana\RobotShop\Ratings\Service\CatalogueService;
use Instana\RobotShop\Ratings\Service\HealthCheckService;
@@ -120,6 +121,12 @@ class Kernel extends BaseKernel implements EventSubscriberInterface
->addMethodCall('setLogger', [new Reference('logger')])
->addTag('controller.service_arguments')
->setAutowired(true);
$c->register(InstanaDataCenterListener::class)
->addTag('kernel.event_listener', [
'event' => 'kernel.request'
])
->setAutowired(true);
}
protected function configureRoutes(RouteCollectionBuilder $routes)

View File

@@ -36,6 +36,12 @@
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.instana</groupId>
<artifactId>instana-java-sdk</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
@@ -46,7 +52,7 @@
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@@ -1,7 +1,10 @@
package com.instana.robotshop.shipping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import com.instana.sdk.support.SpanSupport;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -11,14 +14,33 @@ import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import java.util.Random;
@SpringBootApplication
@EnableRetry
public class ShippingServiceApplication {
@EnableWebMvc
public class ShippingServiceApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(ShippingServiceApplication.class, args);
}
private static final String[] DATA_CENTERS = {
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
};
public static void main(String[] args) {
SpringApplication.run(ShippingServiceApplication.class, args);
}
@Bean
public BeanPostProcessor dataSourceWrapper() {
@@ -26,7 +48,7 @@ public class ShippingServiceApplication {
}
@Order(Ordered.HIGHEST_PRECEDENCE)
private class DataSourcePostProcessor implements BeanPostProcessor {
private static class DataSourcePostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof DataSource) {
@@ -40,4 +62,19 @@ public class ShippingServiceApplication {
return bean;
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InstanaDatacenterTagInterceptor());
}
private static class InstanaDatacenterTagInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
SpanSupport.annotate("datacenter", DATA_CENTERS[new Random().nextInt(DATA_CENTERS.length)]);
return super.preHandle(request, response, handler);
}
}
}

View File

@@ -41,6 +41,24 @@ app.use((req, res, next) => {
next();
});
app.use((req, res, next) => {
let dcs = [
"us-east1",
"us-east2",
"us-east3",
"us-east4",
"us-central1",
"us-west1",
"us-west2",
"eu-west3",
"eu-west4"
];
let span = instana.currentSpan();
span.annotate('custom.sdk.tags.datacenter', dcs[Math.floor(Math.random() * dcs.length)]);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());