├── .gitignore ├── tests ├── bootstrap.php └── TracerTest.php ├── .travis.yml ├── README.md ├── phpunit.xml.dist ├── src ├── config │ └── zipkin.php ├── LaravelRequestHeaders.php ├── Provider.php ├── RedisReporter.php ├── Commands │ ├── ExportWatches.php │ ├── ImportWatches.php │ └── ZipkinReporter.php ├── HttpClient.php ├── Middleware.php └── Tracer.php ├── composer.json └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ 2 | /composer.lock 3 | /.idea 4 | /.phpunit* -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | ./tests 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/config/zipkin.php: -------------------------------------------------------------------------------- 1 | env('ZIPKIN_SERVICE_NAME', 'laravel-zipkin'), 5 | 'endpoint_url' => env('ZIPKIN_ENDPOINT_URL', 'http://localhost:9411/api/v2/spans'), 6 | 'sample_rate' => doubleval(env('ZIPKIN_SAMPLE_RATE', 0)), 7 | 'body_size' => intval(env('ZIPKIN_BODY_SIZE', 5000)), //记录http body长度,单位字节 8 | 'curl_timeout' => intval(env('ZIPKIN_CURL_TIMEOUT', 1)), //超时时间,单位秒 9 | 'redis_options' => [ 10 | 'queue_name' => env('ZIPKIN_QUEUE_NAME', 'queue:zipkin:span'), 11 | 'connection' => env('ZIPKIN_REDIS_CONNECTION', 'zipkin'), 12 | ], 13 | 'es_options' => [ 14 | 'connection' => env('ZIPKIN_ES_CONNECTION', 'zipkin'), 15 | ], 16 | 'report_type' => env('ZIPKIN_REPORT_TYPE', 'http'), 17 | ]; 18 | -------------------------------------------------------------------------------- /src/LaravelRequestHeaders.php: -------------------------------------------------------------------------------- 1 | hasHeader($lKey) ? $carrier->header($lKey) : null; 20 | } 21 | 22 | /** 23 | * {@inheritdoc} 24 | * 25 | * @param Request $carrier 26 | * @throws \InvalidArgumentException for invalid header names or values. 27 | */ 28 | public function put(&$carrier, $key, $value) 29 | { 30 | $lKey = strtolower($key); 31 | $carrier = $carrier->headers->set($lKey, $value, false); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "luoxiaojun/laravel-zipkin", 3 | "description": "Zipkin in Laravel", 4 | "keywords": ["zipkin", "laravel"], 5 | "type": "library", 6 | "require": { 7 | "openzipkin/zipkin": "1.3.2", 8 | "psr/http-message": "^1.0", 9 | "guzzlehttp/guzzle": "^6.3", 10 | "cviebrock/laravel-elasticsearch": "~3.4" 11 | }, 12 | "require-dev": { 13 | "phpunit/phpunit": "~7.5", 14 | "mockery/mockery": "~1.2" 15 | }, 16 | "license": "apache-2.0", 17 | "authors": [ 18 | { 19 | "name": "luoxiaojun", 20 | "email": "luoxiaojun1992@sina.cn" 21 | } 22 | ], 23 | "autoload": { 24 | "psr-4": {"Lxj\\Laravel\\Zipkin\\": "src/"} 25 | }, 26 | "extra": { 27 | "laravel": { 28 | "providers": [ 29 | "Lxj\\Laravel\\Zipkin\\Provider" 30 | ] 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Provider.php: -------------------------------------------------------------------------------- 1 | app->singleton(Tracer::class, function(){ 17 | return new Tracer(config('zipkin')); 18 | }); 19 | } 20 | 21 | /** 22 | * Bootstrap the application services. 23 | */ 24 | public function boot() 25 | { 26 | $this->publishes([__DIR__ . '/config/zipkin.php' => config_path('zipkin.php')], 'config'); 27 | 28 | $this->commands([ 29 | ZipkinReporter::class, 30 | ExportWatches::class, 31 | ImportWatches::class, 32 | ]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/RedisReporter.php: -------------------------------------------------------------------------------- 1 | 'queue:zipkin:span', 15 | 'connection' => 'zipkin', 16 | ]; 17 | 18 | /** 19 | * @var array 20 | */ 21 | private $options; 22 | 23 | public function __construct( 24 | array $options = [] 25 | ) { 26 | $this->options = array_merge(self::DEFAULT_OPTIONS, $options); 27 | } 28 | 29 | /** 30 | * @param Span[] $spans 31 | * @return void 32 | */ 33 | public function report(array $spans) 34 | { 35 | if (!$spans) { 36 | return; 37 | } 38 | 39 | $payload = json_encode(array_map(function (Span $span) { 40 | return $span->toArray(); 41 | }, $spans)); 42 | 43 | try { 44 | $this->enqueue($payload); 45 | } catch (RuntimeException $e) { 46 | // 47 | } 48 | } 49 | 50 | private function enqueue($payload) 51 | { 52 | $redisClient = $this->getRedisClient(); 53 | if (is_null($redisClient)) { 54 | Log::error('Zipkin report error: redis client is null'); 55 | return; 56 | } 57 | 58 | if (empty($this->options['queue_name'])) { 59 | Log::error('Zipkin report error: redis queue name is empty'); 60 | return; 61 | } 62 | 63 | $redisClient->lpush($this->options['queue_name'], $payload); 64 | } 65 | 66 | private function getRedisClient() 67 | { 68 | if (!empty($this->options['connection'])) { 69 | return Redis::connection($this->options['connection']); 70 | } 71 | 72 | return null; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/Commands/ExportWatches.php: -------------------------------------------------------------------------------- 1 | 'zipkin', 28 | ]; 29 | 30 | /** @var Client */ 31 | private $esClient; 32 | 33 | /** 34 | * Create a new command instance. 35 | * 36 | * @return void 37 | */ 38 | public function __construct() 39 | { 40 | parent::__construct(); 41 | 42 | $this->esOptions = array_merge($this->esOptions, config('zipkin.es_options', [])); 43 | } 44 | 45 | protected function configure() 46 | { 47 | $this->addOption( 48 | 'offset', 49 | null, 50 | InputOption::VALUE_OPTIONAL, 51 | 'Query Offset', 52 | 0 53 | )->addOption( 54 | 'limit', 55 | null, 56 | InputOption::VALUE_OPTIONAL, 57 | 'Query Limit', 58 | 100 59 | ); 60 | } 61 | 62 | /** 63 | * Execute the console command. 64 | * 65 | * @return mixed 66 | */ 67 | public function handle() 68 | { 69 | $esClient = $this->getEsClient(); 70 | $res = $esClient->search([ 71 | 'index' => '.watches', 72 | 'from' => intval($this->option('offset')), 73 | 'size' => intval($this->option('limit')), 74 | ]); 75 | 76 | $watches = []; 77 | if ($res['hits']['total'] > 0) { 78 | foreach ($res['hits']['hits'] as $hit) { 79 | if ($hit['_source']['metadata']['xpack']['type'] === 'json') { 80 | array_push($watches, $hit); 81 | } 82 | } 83 | } 84 | 85 | File::put(storage_path('watches.json'), json_encode($watches)); 86 | } 87 | 88 | private function getEsClient() 89 | { 90 | if (is_null($this->esClient)) { 91 | if (!empty($this->esOptions['connection'])) { 92 | $this->esClient = \Elasticsearch::connection($this->esOptions['connection']); 93 | } 94 | } 95 | 96 | return $this->esClient; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /tests/TracerTest.php: -------------------------------------------------------------------------------- 1 | shouldReceive('listen')->with( 20 | 'Illuminate\\Database\\Events\\QueryExecuted', 21 | M::type('\\Closure') 22 | ); 23 | $event->shouldReceive('listen')->with( 24 | 'Illuminate\\Redis\\Events\\CommandExecuted', 25 | M::type('\\Closure') 26 | ); 27 | 28 | //Mock App 29 | $app = M::mock('alias:\\App'); 30 | $app->shouldReceive('runningInConsole')->andReturnFalse(); 31 | $app->shouldReceive('version') 32 | ->andReturn('5.5.44'); 33 | 34 | //Mock Request 35 | $request = M::mock('\\Illuminate\\Http\\Request'); 36 | $request->shouldReceive('hasHeader')->with('x-b3-sampled') 37 | ->andReturnFalse(); 38 | $request->shouldReceive('hasHeader')->with('x-b3-flags') 39 | ->andReturnFalse(); 40 | $request->shouldReceive('hasHeader')->with('x-b3-traceid') 41 | ->andReturnFalse(); 42 | $request->shouldReceive('hasHeader')->with('x-b3-spanid') 43 | ->andReturnFalse(); 44 | $request->shouldReceive('hasHeader')->with('x-b3-parentspanid') 45 | ->andReturnFalse(); 46 | $request->shouldReceive('server')->with('REMOTE_PORT') 47 | ->andReturnNull(); 48 | 49 | //Mock Request Facade 50 | $requestFacade = M::mock('alias:\\Illuminate\\Support\\Facades\\Request'); 51 | $requestFacade->shouldReceive('instance')->andReturn($request); 52 | $requestFacade->shouldReceive('ip')->andReturnNull(); 53 | 54 | $tracer = new \Lxj\Laravel\Zipkin\Tracer([ 55 | 'sample_rate' => 1, 56 | ]); 57 | 58 | $this->assertTrue($tracer->serverSpan('unit-test', function (\Zipkin\Span $span) use ($tracer) { 59 | $this->assertTrue($tracer->clientSpan('unit-test-sub', function (\Zipkin\Span $span) { 60 | return true; 61 | })); 62 | 63 | return true; 64 | }, true)); 65 | } 66 | 67 | /** 68 | * Testing in console environment 69 | * 70 | * @throws Exception 71 | */ 72 | public function testConsoleTrace() 73 | { 74 | //Mock QueryExecuted 75 | M::mock('alias:\Illuminate\Database\Events\QueryExecuted'); 76 | 77 | //Mock Event 78 | $event = M::mock('alias:\\Event'); 79 | $event->shouldReceive('listen')->with( 80 | 'Illuminate\\Database\\Events\\QueryExecuted', 81 | M::type('\\Closure') 82 | ); 83 | $event->shouldReceive('listen')->with( 84 | 'Illuminate\\Redis\\Events\\CommandExecuted', 85 | M::type('\\Closure') 86 | ); 87 | 88 | //Mock App 89 | $app = M::mock('alias:\\App'); 90 | $app->shouldReceive('runningInConsole')->andReturnTrue(); 91 | $app->shouldReceive('version') 92 | ->andReturn('5.5.44'); 93 | 94 | $tracer = new \Lxj\Laravel\Zipkin\Tracer([ 95 | 'sample_rate' => 1, 96 | ]); 97 | 98 | $this->assertTrue($tracer->serverSpan('unit-test', function (\Zipkin\Span $span) use ($tracer) { 99 | $this->assertTrue($tracer->clientSpan('unit-test-sub', function (\Zipkin\Span $span) { 100 | return true; 101 | })); 102 | 103 | return true; 104 | }, true)); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/Commands/ImportWatches.php: -------------------------------------------------------------------------------- 1 | 'zipkin', 28 | ]; 29 | 30 | /** @var Client */ 31 | private $esClient; 32 | 33 | /** 34 | * Create a new command instance. 35 | * 36 | * @return void 37 | */ 38 | public function __construct() 39 | { 40 | parent::__construct(); 41 | 42 | $this->esOptions = array_merge($this->esOptions, config('zipkin.es_options', [])); 43 | } 44 | 45 | protected function configure() 46 | { 47 | $this->addOption( 48 | 'override', 49 | null, 50 | InputOption::VALUE_OPTIONAL, 51 | 'Override all watches', 52 | 0 53 | )->addOption( 54 | 'offset', 55 | null, 56 | InputOption::VALUE_OPTIONAL, 57 | 'Query Offset', 58 | 0 59 | )->addOption( 60 | 'limit', 61 | null, 62 | InputOption::VALUE_OPTIONAL, 63 | 'Query Limit', 64 | 100 65 | )->addOption( 66 | 'file', 67 | null, 68 | InputOption::VALUE_OPTIONAL, 69 | 'Watches json file', 70 | null 71 | ); 72 | } 73 | 74 | /** 75 | * Execute the console command. 76 | * 77 | * @return mixed 78 | */ 79 | public function handle() 80 | { 81 | $fileOption = $this->option('file'); 82 | $watchesJson = File::get(isset($fileOption) ? $fileOption : storage_path('watches.json')); 83 | $watches = json_decode($watchesJson, true); 84 | if (!json_last_error()) { 85 | 86 | if (!intval($this->option('override'))) { 87 | //Remove current watches 88 | $currentWatchIds = $this->getCurrentWatchIds(); 89 | foreach ($watches as $k => $hit) { 90 | if (in_array($hit['_id'], $currentWatchIds)) { 91 | unset($watches[$k]); 92 | } 93 | } 94 | } 95 | 96 | $this->output->progressStart(count($watches)); 97 | 98 | $esClient = $this->getEsClient(); 99 | 100 | foreach ($watches as $hit) { 101 | $esClient->index([ 102 | 'index' => '_watcher', 103 | 'type' => 'watch', 104 | 'id' => $hit['_id'], 105 | 'body' => $hit['_source'], 106 | ]); 107 | 108 | $this->output->progressAdvance(1); 109 | } 110 | 111 | $this->output->progressFinish(); 112 | } else { 113 | var_dump(json_last_error()); 114 | } 115 | } 116 | 117 | private function getCurrentWatchIds() 118 | { 119 | $esClient = $this->getEsClient(); 120 | $res = $esClient->search([ 121 | 'index' => '.watches', 122 | 'from' => intval($this->option('offset')), 123 | 'size' => intval($this->option('limit')), 124 | ]); 125 | $watchIds = []; 126 | if ($res['hits']['total'] > 0) { 127 | foreach ($res['hits']['hits'] as $hit) { 128 | array_push($watchIds, $hit['_id']); 129 | } 130 | } 131 | 132 | return $watchIds; 133 | } 134 | 135 | private function getEsClient() 136 | { 137 | if (is_null($this->esClient)) { 138 | if (!empty($this->esOptions['connection'])) { 139 | $this->esClient = \Elasticsearch::connection($this->esOptions['connection']); 140 | } 141 | } 142 | 143 | return $this->esClient; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/HttpClient.php: -------------------------------------------------------------------------------- 1 | getMessage()); 47 | throw new \Exception('CURL ERROR ' . $e->getMessage()); 48 | } 49 | }; 50 | 51 | if (\App::runningInConsole() && !$traceInConsole) { 52 | return call_user_func($sendRequest); 53 | } 54 | 55 | /** @var Tracer $laravelTracer */ 56 | $laravelTracer = app(Tracer::class); 57 | $path = $request->getUri()->getPath(); 58 | 59 | return $laravelTracer->clientSpan( 60 | isset($spanName) ? $spanName : $laravelTracer->formatHttpPath($path), 61 | function (Span $span) use (&$request, $sendRequest, $laravelTracer, $path, $injectSpanCtx) { 62 | //Inject trace context to api psr request 63 | if ($injectSpanCtx) { 64 | $laravelTracer->injectContextToRequest($span->getContext(), $request); 65 | } 66 | 67 | if ($span->getContext()->isSampled()) { 68 | $laravelTracer->addTag($span, HTTP_HOST, $request->getUri()->getHost()); 69 | $laravelTracer->addTag($span, HTTP_PATH, $path); 70 | $laravelTracer->addTag($span, Tracer::HTTP_QUERY_STRING, (string)$request->getUri()->getQuery()); 71 | $laravelTracer->addTag($span, HTTP_METHOD, $request->getMethod()); 72 | $httpRequestBodyLen = $request->getBody()->getSize(); 73 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_BODY_SIZE, $httpRequestBodyLen); 74 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_BODY, $laravelTracer->formatHttpBody($request->getBody()->getContents(), $httpRequestBodyLen)); 75 | $request->getBody()->seek(0); 76 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_HEADERS, json_encode($request->getHeaders(), JSON_UNESCAPED_UNICODE)); 77 | $laravelTracer->addTag( 78 | $span, 79 | Tracer::HTTP_REQUEST_PROTOCOL_VERSION, 80 | $laravelTracer->formatHttpProtocolVersion($request->getProtocolVersion()) 81 | ); 82 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_SCHEME, $request->getUri()->getScheme()); 83 | } 84 | 85 | $response = null; 86 | try { 87 | $response = call_user_func($sendRequest); 88 | return $response; 89 | } catch (\Exception $e) { 90 | throw $e; 91 | } finally { 92 | if ($response) { 93 | if ($span->getContext()->isSampled()) { 94 | $laravelTracer->addTag($span, HTTP_STATUS_CODE, $response->getStatusCode()); 95 | $httpResponseBodyLen = $response->getBody()->getSize(); 96 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_BODY_SIZE, $httpResponseBodyLen); 97 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_BODY, $laravelTracer->formatHttpBody($response->getBody()->getContents(), $httpResponseBodyLen)); 98 | $response->getBody()->seek(0); 99 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_HEADERS, json_encode($response->getHeaders(), JSON_UNESCAPED_UNICODE)); 100 | $laravelTracer->addTag( 101 | $span, 102 | Tracer::HTTP_RESPONSE_PROTOCOL_VERSION, 103 | $laravelTracer->formatHttpProtocolVersion($response->getProtocolVersion()) 104 | ); 105 | } 106 | } 107 | } 108 | }, $flushTracing); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/Middleware.php: -------------------------------------------------------------------------------- 1 | getPathInfo(); 23 | $apiPrefix = explode(',', config('zipkin.api_prefix', '/')); 24 | foreach ($apiPrefix as $prefix) { 25 | if (stripos($path, $prefix) === 0) { 26 | return true; 27 | } 28 | } 29 | 30 | return false; 31 | } 32 | 33 | /** 34 | * Handle an incoming request. 35 | * 36 | * @param \Illuminate\Http\Request $request 37 | * @param \Closure $next 38 | * @return mixed 39 | * @throws \Exception 40 | */ 41 | public function handle($request, \Closure $next) 42 | { 43 | if (!$this->needSample($request)) { 44 | return $next($request); 45 | } 46 | 47 | /** @var Tracer $laravelTracer */ 48 | $laravelTracer = app(Tracer::class); 49 | $path = $request->getPathInfo(); 50 | 51 | return $laravelTracer->serverSpan($laravelTracer->formatHttpPath($path), function (Span $span) use ($next, $request, $laravelTracer, $path) { 52 | if ($span->getContext()->isSampled()) { 53 | $laravelTracer->addTag($span, HTTP_HOST, $request->getHttpHost()); 54 | $laravelTracer->addTag($span, HTTP_PATH, $path); 55 | $laravelTracer->addTag($span, Tracer::HTTP_QUERY_STRING, (string)$request->getQueryString()); 56 | $laravelTracer->addTag($span, HTTP_METHOD, $request->getMethod()); 57 | $httpRequestBody = $laravelTracer->convertToStr($request->getContent()); 58 | $httpRequestBodyLen = strlen($httpRequestBody); 59 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_BODY_SIZE, $httpRequestBodyLen); 60 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_BODY, $laravelTracer->formatHttpBody( 61 | $httpRequestBody, 62 | $httpRequestBodyLen 63 | )); 64 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_HEADERS, json_encode($request->headers->all(), JSON_UNESCAPED_UNICODE)); 65 | $laravelTracer->addTag( 66 | $span, 67 | Tracer::HTTP_REQUEST_PROTOCOL_VERSION, 68 | $laravelTracer->formatHttpProtocolVersion($request->getProtocolVersion()) 69 | ); 70 | $laravelTracer->addTag($span, Tracer::HTTP_REQUEST_SCHEME, $request->getScheme()); 71 | } 72 | 73 | /** @var Response $response */ 74 | $response = null; 75 | try { 76 | $response = $next($request); 77 | 78 | if ($span->getContext()->isSampled()) { 79 | if ($response->isServerError()) { 80 | $laravelTracer->addTag($span, ERROR, 'server error'); 81 | } elseif ($response->isClientError()) { 82 | $laravelTracer->addTag($span, ERROR, 'client error'); 83 | } 84 | } 85 | 86 | return $response; 87 | } catch (\Exception $e) { 88 | throw $e; 89 | } finally { 90 | $route = $request->route(); 91 | if ($route instanceof Route) { 92 | $span->setName($laravelTracer->formatRoutePath($request->route()->uri())); 93 | } elseif (is_string($route)) { 94 | $span->setName($laravelTracer->formatRoutePath($route)); 95 | } 96 | if ($response) { 97 | if ($span->getContext()->isSampled()) { 98 | $laravelTracer->addTag($span, HTTP_STATUS_CODE, $response->getStatusCode()); 99 | $httpResponseBody = $laravelTracer->convertToStr($response->getContent()); 100 | $httpResponseBodyLen = strlen($httpResponseBody); 101 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_BODY_SIZE, $httpResponseBodyLen); 102 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_BODY, $laravelTracer->formatHttpBody( 103 | $httpResponseBody, 104 | $httpResponseBodyLen 105 | )); 106 | $laravelTracer->addTag($span, Tracer::HTTP_RESPONSE_HEADERS, json_encode($response->headers->all(), JSON_UNESCAPED_UNICODE)); 107 | $laravelTracer->addTag( 108 | $span, 109 | Tracer::HTTP_RESPONSE_PROTOCOL_VERSION, 110 | $laravelTracer->formatHttpProtocolVersion($response->getProtocolVersion()) 111 | ); 112 | } 113 | } 114 | } 115 | }, true); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/Commands/ZipkinReporter.php: -------------------------------------------------------------------------------- 1 | 'queue:zipkin:span', 30 | 'connection' => 'zipkin', 31 | ]; 32 | 33 | private $esOptions = [ 34 | 'connection' => 'zipkin', 35 | ]; 36 | 37 | private $endpointUrl = 'http://localhost:9411/api/v2/spans'; 38 | 39 | private $curlTimeout = 1; 40 | 41 | /** @var Connection */ 42 | private $redis; 43 | 44 | private $curlClient; 45 | 46 | /** @var Elasticsearch\Client */ 47 | private $esClient; 48 | 49 | /** 50 | * Create a new command instance. 51 | * 52 | * @return void 53 | */ 54 | public function __construct() 55 | { 56 | parent::__construct(); 57 | 58 | $this->redisOptions = array_merge($this->redisOptions, config('zipkin.redis_options', [])); 59 | $this->esOptions = array_merge($this->esOptions, config('zipkin.es_options', [])); 60 | $this->endpointUrl = config('zipkin.endpoint_url', 'http://localhost:9411/api/v2/spans'); 61 | $this->curlTimeout = config('zipkin.curl_timeout', 1); 62 | } 63 | 64 | protected function configure() 65 | { 66 | $this->addOption( 67 | 'interval', 68 | null, 69 | InputOption::VALUE_OPTIONAL, 70 | 'Consumption interval(ms)', 71 | 5 72 | )->addOption( 73 | 'freq', 74 | null, 75 | InputOption::VALUE_OPTIONAL, 76 | 'Report frequency(int)', 77 | 100 //Local test: 5000 ok,if curl timeout,increase curl timeout config or number of consumer 78 | ); 79 | } 80 | 81 | /** 82 | * Execute the console command. 83 | * 84 | * @return mixed 85 | */ 86 | public function handle() 87 | { 88 | $redisClient = $this->getRedisClient(); 89 | if (is_null($redisClient)) { 90 | $this->output->error('Redis client is null'); 91 | return; 92 | } 93 | 94 | if (empty($this->redisOptions['queue_name'])) { 95 | $this->output->error('Redis queue name is empty'); 96 | return; 97 | } 98 | 99 | $counter = 0; 100 | $aggData = []; 101 | while (true) { 102 | $spanArr = json_decode($redisClient->rpop($this->redisOptions['queue_name']), true); 103 | if ((!json_last_error()) && count($spanArr) > 0) { 104 | $aggData = array_merge($aggData, $spanArr); 105 | } 106 | 107 | ++$counter; 108 | 109 | //每消费100次上报一次zipkin 110 | if ($counter == intval($this->option('freq'))) { 111 | if (count($aggData) > 0) { 112 | $this->report(json_encode($aggData)); 113 | 114 | $this->saveToEs($aggData); 115 | 116 | $aggData = []; 117 | } 118 | 119 | $counter = 0; 120 | } 121 | 122 | usleep(intval(doubleval($this->option('interval')) * 1000)); 123 | } 124 | 125 | return; 126 | } 127 | 128 | private function report($payload) 129 | { 130 | $client = $this->getCurlClient(); 131 | $client($payload); 132 | } 133 | 134 | private function saveToEs($spanArr) 135 | { 136 | $esClient = $this->getEsClient(); 137 | if (is_null($esClient)) { 138 | return; 139 | } 140 | try { 141 | $params = []; 142 | foreach ($spanArr as $span) { 143 | $createdTime = intval($span['timestamp'] / 1000000); 144 | $createdDate = date('Y-m-d', $createdTime); 145 | 146 | $index = 'zipkin:span:processed-' . $createdDate; 147 | 148 | $params['body'][] = [ 149 | 'index' => [ 150 | '_index' => $index, 151 | '_type' => $index, 152 | ] 153 | ]; 154 | 155 | $params['body'][] = $this->formatSpan($span); 156 | } 157 | 158 | $esClient->bulk($params); 159 | } catch (\Exception $e) { 160 | // 161 | } 162 | } 163 | 164 | private function formatSpan($span) 165 | { 166 | $createdTime = intval($span['timestamp'] / 1000000); 167 | $createdAt = date('c', $createdTime); 168 | $span['created_at'] = $createdAt; 169 | 170 | $span['is_success'] = !isset($span['tags']['error']); 171 | 172 | if (isset($span['tags'])) { 173 | $formattedTags = []; 174 | $tags = $span['tags']; 175 | unset($span['tags']); 176 | $dbQueryTimes = 0; 177 | $dbQueryDuration = 0; 178 | foreach ($tags as $key => $value) { 179 | $formattedKey = 'tag_' . str_replace('.', '_', $key); 180 | $formattedTags[$formattedKey] = $value; 181 | 182 | if (strpos($formattedKey, 'tag_db_query_times_') === 0) { 183 | $dbQueryTimes += intval($value); 184 | } 185 | if (strpos($formattedKey, 'tag_db_query_total_duration_') === 0) { 186 | $dbQueryDuration += doubleval(substr($value, 0, -2)); 187 | } 188 | } 189 | $span = array_merge($span, $formattedTags); 190 | $span['tag_db_query_times'] = $dbQueryTimes; 191 | $span['tag_db_query_total_duration'] = $dbQueryDuration; 192 | } 193 | 194 | if (isset($span['tag_http_status_code'])) { 195 | $span['tag_http_status_code'] = intval($span['tag_http_status_code']); 196 | } 197 | if (isset($span['tag_http_request_body_size'])) { 198 | $span['tag_http_request_body_size'] = intval($span['tag_http_request_body_size']); 199 | } 200 | if (isset($span['tag_http_response_body_size'])) { 201 | $span['tag_http_response_body_size'] = intval($span['tag_http_response_body_size']); 202 | } 203 | if (isset($span['tag_runtime_memory'])) { 204 | $runtimeMemory = substr($span['tag_runtime_memory'], 0, -2); 205 | $span['tag_runtime_memory_float'] = doubleval($runtimeMemory); 206 | } 207 | if (isset($span['tag_http_request_headers'])) { 208 | $requestHeaders = json_decode($span['tag_http_request_headers'], true); 209 | if (!json_last_error()) { 210 | foreach ($requestHeaders as $headerName => $headerValues) { 211 | if (strtolower($headerName) === 'content-type') { 212 | $span['tag_http_request_content_type'] = implode(',', $headerValues); 213 | break; 214 | } 215 | } 216 | } 217 | } 218 | if (isset($span['tag_http_response_headers'])) { 219 | $responseHeaders = json_decode($span['tag_http_response_headers'], true); 220 | if (!json_last_error()) { 221 | foreach ($responseHeaders as $headerName => $headerValues) { 222 | if (strtolower($headerName) === 'content-type') { 223 | $span['tag_http_response_content_type'] = implode(',', $headerValues); 224 | break; 225 | } 226 | } 227 | } 228 | } 229 | 230 | return $span; 231 | } 232 | 233 | private function getRedisClient() 234 | { 235 | if (is_null($this->redis)) { 236 | if (!empty($this->redisOptions['connection'])) { 237 | $this->redis = Redis::connection($this->redisOptions['connection']); 238 | } 239 | } 240 | 241 | return $this->redis; 242 | } 243 | 244 | private function getCurlClient() 245 | { 246 | if (is_null($this->curlClient)) { 247 | $this->curlClient = CurlFactory::create()->build([ 248 | 'endpoint_url' => $this->endpointUrl, 249 | 'timeout' => $this->curlTimeout, 250 | ]); 251 | } 252 | 253 | return $this->curlClient; 254 | } 255 | 256 | private function getEsClient() 257 | { 258 | if (is_null($this->esClient)) { 259 | if (!empty($this->esOptions['connection'])) { 260 | $this->esClient = Elasticsearch::connection($this->esOptions['connection']); 261 | } 262 | } 263 | 264 | return $this->esClient; 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/Tracer.php: -------------------------------------------------------------------------------- 1 | 'queue:zipkin:span', 57 | 'connection' => 'zipkin', 58 | ]; 59 | private $reportType = 'http'; 60 | 61 | /** @var \Zipkin\Tracer */ 62 | private $tracer; 63 | 64 | /** @var Tracing */ 65 | private $tracing; 66 | 67 | /** @var array TraceContext[] */ 68 | private $contextStack = []; 69 | 70 | //DB metrics 71 | private $dbQueryTimes = []; 72 | private $totalDbQueryDuration = []; 73 | 74 | //Redis metrics 75 | private $redisExecTimes = []; 76 | private $totalRedisExecDuration = []; 77 | 78 | /** 79 | * Tracer constructor. 80 | * @param $config 81 | */ 82 | public function __construct($config) 83 | { 84 | $this->serviceName = isset($config['service_name']) ? $config['service_name'] : 'laravel-zipkin'; 85 | $this->endpointUrl = isset($config['endpoint_url']) ? $config['endpoint_url'] : 'http://localhost:9411/api/v2/spans'; 86 | $this->sampleRate = isset($config['sample_rate']) ? $config['sample_rate'] : 0; 87 | $this->bodySize = isset($config['body_size']) ? $config['body_size'] : 5000; 88 | $this->curlTimeout = isset($config['curl_timeout']) ? $config['curl_timeout'] : 1; 89 | $redisOptions = isset($config['redis_options']) ? $config['redis_options'] : []; 90 | $this->redisOptions = array_merge($this->redisOptions, $redisOptions); 91 | $this->reportType = isset($config['report_type']) ? $config['report_type'] : 'http'; 92 | 93 | $this->createTracer(); 94 | 95 | if (!\App::runningInConsole()) { 96 | $this->listenDbQuery(); 97 | $this->listenRedisQuery(); 98 | } 99 | } 100 | 101 | /** 102 | * Create zipkin tracer 103 | */ 104 | private function createTracer() 105 | { 106 | if (!\App::runningInConsole()) { 107 | $realIp = \Illuminate\Support\Facades\Request::ip(); 108 | $isIpV6 = substr_count($realIp, ':') > 1; 109 | $remotePort = \Illuminate\Support\Facades\Request::instance()->server('REMOTE_PORT'); 110 | $endpoint = Endpoint::create( 111 | $this->serviceName, 112 | (!$isIpV6) ? $realIp : null, 113 | $isIpV6 ? $realIp : null, 114 | $remotePort ? (int)$remotePort : null 115 | ); 116 | } else { 117 | $endpoint = Endpoint::create($this->serviceName); 118 | } 119 | $sampler = BinarySampler::createAsAlwaysSample(); 120 | $this->tracing = TracingBuilder::create() 121 | ->havingLocalEndpoint($endpoint) 122 | ->havingSampler($sampler) 123 | ->havingReporter($this->getReporter()) 124 | ->build(); 125 | $this->tracer = $this->getTracing()->getTracer(); 126 | } 127 | 128 | private function getReporter() 129 | { 130 | if ($this->reportType === 'redis') { 131 | return new RedisReporter($this->redisOptions); 132 | } elseif ($this->reportType === 'http') { 133 | return new Http(null, ['endpoint_url' => $this->endpointUrl, 'timeout' => $this->curlTimeout]); 134 | } 135 | 136 | return new Http(null, ['endpoint_url' => $this->endpointUrl, 'timeout' => $this->curlTimeout]); 137 | } 138 | 139 | /** 140 | * Listen db query event 141 | */ 142 | private function listenDbQuery() 143 | { 144 | \Event::listen(QueryExecuted::class, function (QueryExecuted $event) { 145 | $identify = $event->connection->getDriverName() . '.' . $event->connectionName; 146 | if (isset($this->dbQueryTimes[$identify])) { 147 | $this->dbQueryTimes[$identify]++; 148 | } else { 149 | $this->dbQueryTimes[$identify] = 1; 150 | } 151 | if (isset($this->totalDbQueryDuration[$identify])) { 152 | $this->totalDbQueryDuration[$identify] += $event->time; 153 | } else { 154 | $this->totalDbQueryDuration[$identify] = $event->time; 155 | } 156 | }); 157 | } 158 | 159 | /** 160 | * Listen redis query event 161 | */ 162 | private function listenRedisQuery() 163 | { 164 | \Event::listen(CommandExecuted::class, function (CommandExecuted $event) { 165 | $identify = $event->connectionName; 166 | if (isset($this->redisExecTimes[$identify])) { 167 | $this->redisExecTimes[$identify]++; 168 | } else { 169 | $this->redisExecTimes[$identify] = 1; 170 | } 171 | if (isset($this->totalRedisExecDuration[$identify])) { 172 | $this->totalRedisExecDuration[$identify] += $event->time; 173 | } else { 174 | $this->totalRedisExecDuration[$identify] = $event->time; 175 | } 176 | }); 177 | } 178 | 179 | /** 180 | * @return Tracing 181 | */ 182 | public function getTracing() 183 | { 184 | return $this->tracing; 185 | } 186 | 187 | /** 188 | * @return \Zipkin\Tracer 189 | */ 190 | public function getTracer() 191 | { 192 | return $this->tracer; 193 | } 194 | 195 | /** 196 | * Create a server trace 197 | * 198 | * @param $name 199 | * @param $callback 200 | * @param bool $flush 201 | * @return mixed 202 | * @throws \Exception 203 | */ 204 | public function serverSpan($name, $callback, $flush = false) 205 | { 206 | return $this->span($name, $callback, SERVER, $flush); 207 | } 208 | 209 | /** 210 | * Create a client trace 211 | * 212 | * @param $name 213 | * @param $callback 214 | * @param bool $flush 215 | * @return mixed 216 | * @throws \Exception 217 | */ 218 | public function clientSpan($name, $callback, $flush = false) 219 | { 220 | return $this->span($name, $callback, CLIENT, $flush); 221 | } 222 | 223 | /** 224 | * Create a trace 225 | * 226 | * @param string $name 227 | * @param callable $callback 228 | * @param null|string $kind 229 | * @param bool $flush 230 | * @return mixed 231 | * @throws \Exception 232 | */ 233 | public function span($name, $callback, $kind = null, $flush = false) 234 | { 235 | $parentContext = $this->getParentContext(); 236 | $span = $this->getSpan($parentContext); 237 | $span->setName($name); 238 | if ($kind) { 239 | $span->setKind($kind); 240 | } 241 | 242 | $span->start(); 243 | 244 | $spanContext = $span->getContext(); 245 | array_push($this->contextStack, $spanContext); 246 | 247 | $startDbQueryTimes = $this->dbQueryTimes; 248 | $startDbQueryDuration = $this->totalDbQueryDuration; 249 | $startRedisExecTimes = $this->redisExecTimes; 250 | $startRedisExecDuration = $this->totalRedisExecDuration; 251 | $startMemory = 0; 252 | if ($span->getContext()->isSampled()) { 253 | $startMemory = memory_get_usage(); 254 | $this->beforeSpanTags($span); 255 | } 256 | 257 | try { 258 | return call_user_func_array($callback, ['span' => $span]); 259 | } catch (\Exception $e) { 260 | if ($span->getContext()->isSampled()) { 261 | $this->addTag($span, ERROR, $e->getMessage() . PHP_EOL . $e->getTraceAsString()); 262 | } 263 | throw $e; 264 | } finally { 265 | if ($span->getContext()->isSampled()) { 266 | foreach ($this->dbQueryTimes as $identify => $value) { 267 | $this->addTag($span, self::DB_QUERY_TIMES . '.' . $identify, $value - (isset($startDbQueryTimes[$identify]) ? $startDbQueryTimes[$identify] : 0)); 268 | } 269 | foreach ($this->totalDbQueryDuration as $identify => $value) { 270 | $this->addTag($span, self::DB_QUERY_TOTAL_DURATION . '.' . $identify, ($value - (isset($startDbQueryDuration[$identify]) ? $startDbQueryDuration[$identify] : 0)) . 'ms'); 271 | } 272 | foreach ($this->redisExecTimes as $identify => $value) { 273 | $this->addTag($span, self::REDIS_EXEC_TIMES . '.' . $identify, $value - (isset($startRedisExecTimes[$identify]) ? $startRedisExecTimes[$identify] : 0)); 274 | } 275 | foreach ($this->totalRedisExecDuration as $identify => $value) { 276 | $this->addTag($span, self::REDIS_EXEC_TOTAL_DURATION . '.' . $identify, ($value - (isset($startRedisExecDuration[$identify]) ? $startRedisExecDuration[$identify] : 0)) . 'ms'); 277 | } 278 | $this->addTag($span, static::RUNTIME_MEMORY, round((memory_get_usage() - $startMemory) / 1000000, 2) . 'MB'); 279 | $this->afterSpanTags($span); 280 | } 281 | 282 | $span->finish(); 283 | array_pop($this->contextStack); 284 | if (count($this->contextStack) === 0) { 285 | $this->clearDbStatistic(); 286 | $this->clearRedisStatistic(); 287 | } 288 | 289 | if ($flush) { 290 | $this->flushTracer(); 291 | } 292 | } 293 | } 294 | 295 | protected function clearDbStatistic() 296 | { 297 | $this->dbQueryTimes = []; 298 | $this->totalDbQueryDuration = []; 299 | } 300 | 301 | protected function clearRedisStatistic() 302 | { 303 | $this->redisExecTimes = []; 304 | $this->totalRedisExecDuration = []; 305 | } 306 | 307 | /** 308 | * Formatting http protocol version 309 | * 310 | * @param $protocolVersion 311 | * @return string 312 | */ 313 | public function formatHttpProtocolVersion($protocolVersion) 314 | { 315 | if (stripos($protocolVersion, 'HTTP/') !== 0) { 316 | return 'HTTP/' . $protocolVersion; 317 | } 318 | 319 | return strtoupper($protocolVersion); 320 | } 321 | 322 | /** 323 | * Formatting http body 324 | * 325 | * @param $httpBody 326 | * @param null $bodySize 327 | * @return string 328 | */ 329 | public function formatHttpBody($httpBody, $bodySize = null) 330 | { 331 | $httpBody = $this->convertToStr($httpBody); 332 | 333 | if (is_null($bodySize)) { 334 | $bodySize = strlen($httpBody); 335 | } 336 | 337 | if ($bodySize > $this->bodySize) { 338 | $httpBody = mb_substr($httpBody, 0, $this->bodySize, 'utf8') . ' ...'; 339 | } 340 | 341 | return $httpBody; 342 | } 343 | 344 | /** 345 | * Formatting http path 346 | * 347 | * @param $httpPath 348 | * @return string|string[]|null 349 | */ 350 | public function formatHttpPath($httpPath) 351 | { 352 | $httpPath = preg_replace('/\/\d+$/', '/{id}', $httpPath); 353 | $httpPath = preg_replace('/\/\d+\//', '/{id}/', $httpPath); 354 | 355 | return $httpPath; 356 | } 357 | 358 | /** 359 | * Formatting route path 360 | * 361 | * @param $route 362 | * @return string 363 | */ 364 | public function formatRoutePath($route) 365 | { 366 | if (strpos($route, '/') !== 0) { 367 | $route = '/' . $route; 368 | } 369 | 370 | return $route; 371 | } 372 | 373 | /** 374 | * Add span tag 375 | * 376 | * @param Span $span 377 | * @param $key 378 | * @param $value 379 | */ 380 | public function addTag($span, $key, $value) 381 | { 382 | $span->tag($key, $this->convertToStr($value)); 383 | } 384 | 385 | /** 386 | * Convert variable to string 387 | * 388 | * @param $value 389 | * @return string 390 | */ 391 | public function convertToStr($value) 392 | { 393 | if (!is_scalar($value)) { 394 | $value = ''; 395 | } else { 396 | $value = (string)$value; 397 | } 398 | 399 | return $value; 400 | } 401 | 402 | /** 403 | * Inject trace context to psr request 404 | * 405 | * @param TraceContext $context 406 | * @param RequestInterface $request 407 | */ 408 | public function injectContextToRequest($context, &$request) 409 | { 410 | $injector = $this->getTracing()->getPropagation()->getInjector(new RequestHeaders()); 411 | $injector($context, $request); 412 | } 413 | 414 | /** 415 | * Extract trace context from laravel request 416 | * 417 | * @param Request $request 418 | * @return TraceContext|DefaultSamplingFlags 419 | */ 420 | public function extractRequestToContext($request) 421 | { 422 | $extractor = $this->getTracing()->getPropagation()->getExtractor(new LaravelRequestHeaders()); 423 | return $extractor($request); 424 | } 425 | 426 | /** 427 | * @return TraceContext|DefaultSamplingFlags|null 428 | */ 429 | private function getParentContext() 430 | { 431 | $parentContext = null; 432 | $contextStackLen = count($this->contextStack); 433 | if ($contextStackLen > 0) { 434 | $parentContext = $this->contextStack[$contextStackLen - 1]; 435 | } else { 436 | if (!\App::runningInConsole()) { 437 | //Extract trace context from laravel request 438 | $parentContext = $this->extractRequestToContext(\Illuminate\Support\Facades\Request::instance()); 439 | } 440 | } 441 | 442 | return $parentContext; 443 | } 444 | 445 | /** 446 | * @param TraceContext|DefaultSamplingFlags $parentContext 447 | * @return \Zipkin\Span 448 | */ 449 | private function getSpan($parentContext) 450 | { 451 | $tracer = $this->getTracer(); 452 | 453 | if (!$parentContext) { 454 | $span = $tracer->newTrace($this->getDefaultSamplingFlags()); 455 | } else { 456 | if ($parentContext instanceof TraceContext) { 457 | $span = $tracer->newChild($parentContext); 458 | } else { 459 | if (is_null($parentContext->isSampled())) { 460 | $samplingFlags = $this->getDefaultSamplingFlags(); 461 | } else { 462 | $samplingFlags = $parentContext; 463 | } 464 | 465 | $span = $tracer->newTrace($samplingFlags); 466 | } 467 | } 468 | 469 | return $span; 470 | } 471 | 472 | /** 473 | * @return DefaultSamplingFlags 474 | */ 475 | private function getDefaultSamplingFlags() 476 | { 477 | $sampleRate = $this->sampleRate; 478 | if ($sampleRate >= 1) { 479 | $samplingFlags = DefaultSamplingFlags::createAsEmpty(); //Sample config determined by sampler 480 | } elseif ($sampleRate <= 0) { 481 | $samplingFlags = DefaultSamplingFlags::createAsNotSampled(); 482 | } else { 483 | mt_srand(time()); 484 | if (mt_rand() / mt_getrandmax() <= $sampleRate) { 485 | $samplingFlags = DefaultSamplingFlags::createAsEmpty(); //Sample config determined by sampler 486 | } else { 487 | $samplingFlags = DefaultSamplingFlags::createAsNotSampled(); 488 | } 489 | } 490 | 491 | return $samplingFlags; 492 | } 493 | 494 | /** 495 | * @param Span $span 496 | */ 497 | private function startSysLoadTag($span) 498 | { 499 | //Not supported in windows os 500 | if (!function_exists('sys_getloadavg')) { 501 | return; 502 | } 503 | 504 | $startSystemLoad = sys_getloadavg(); 505 | foreach ($startSystemLoad as $k => $v) { 506 | $startSystemLoad[$k] = round($v, 2); 507 | } 508 | $this->addTag($span, static::RUNTIME_START_SYSTEM_LOAD, implode(',', $startSystemLoad)); 509 | } 510 | 511 | /** 512 | * @param Span $span 513 | */ 514 | private function finishSysLoadTag($span) 515 | { 516 | //Not supported in windows os 517 | if (!function_exists('sys_getloadavg')) { 518 | return; 519 | } 520 | 521 | $finishSystemLoad = sys_getloadavg(); 522 | foreach ($finishSystemLoad as $k => $v) { 523 | $finishSystemLoad[$k] = round($v, 2); 524 | } 525 | $this->addTag($span, static::RUNTIME_FINISH_SYSTEM_LOAD, implode(',', $finishSystemLoad)); 526 | } 527 | 528 | /** 529 | * @param Span $span 530 | */ 531 | private function beforeSpanTags($span) 532 | { 533 | $this->addTag($span, self::FRAMEWORK_VERSION, 'Laravel-' . \App::version()); 534 | $this->addTag($span, self::RUNTIME_PHP_VERSION, PHP_VERSION); 535 | $this->addTag($span, self::RUNTIME_PHP_SAPI, php_sapi_name()); 536 | 537 | $this->startSysLoadTag($span); 538 | } 539 | 540 | /** 541 | * @param Span $span 542 | */ 543 | private function afterSpanTags($span) 544 | { 545 | $this->finishSysLoadTag($span); 546 | } 547 | 548 | private function flushTracer() 549 | { 550 | try { 551 | if ($tracer = $this->getTracer()) { 552 | $tracer->flush(); 553 | } 554 | } catch (\Exception $e) { 555 | Log::error('Zipkin report error ' . $e->getMessage()); 556 | } 557 | } 558 | 559 | public function __destruct() 560 | { 561 | $this->flushTracer(); 562 | } 563 | } 564 | --------------------------------------------------------------------------------