Flask應用示例6 - 集成微服務調(diào)用鏈Zipkin

1. 前言

傳統(tǒng)單體服務少數(shù)微服務架構中蒙具,debug相對簡單,微服務之間的依賴關系也比較容易梳理芜果。
但是融师,在較大的微服務架構中旱爆,如何更好地解決上述問題窘茁,需要引入微服務調(diào)用鏈,來記錄和排查問題房待,比如Zipkin驼抹。
主要解決的問題:

  • 微服務系統(tǒng)瓶頸分析,通過分析API調(diào)用鏈流椒,了解哪個是核心service(需提高健壯性)宣虾,那個service的耗時較長(需拆分或代碼優(yōu)化),等
  • Debug绣硝,troubleshoot latency problems鹉胖,or find Exception in a data flow.
  • 微服務依賴關系,zipkin提供服務依賴關系分析功能


    微服務架構

2. zipkin架構

zipkin架構

2.1. components

collector

Once the trace data arrives at the Zipkin collector daemon, it is validated, stored, and indexed for lookups by the Zipkin collector.

storage

Zipkin was initially built to store data on Cassandra since Cassandra is scalable, has a flexible schema, and is heavily used within Twitter. However, we made this component pluggable. In addition to Cassandra, we natively support ElasticSearch and MySQL. Other back-ends might be offered as third party extensions.

search

Once the data is stored and indexed, we need a way to extract it. The query daemon provides a simple JSON API for finding and retrieving traces. The primary consumer of this API is the Web UI.
https://zipkin.io/zipkin-api/

web UI

We created a GUI that presents a nice interface for viewing traces. The web UI provides a method for viewing traces based on service, time, and annotations.
Note: there is no built-in authentication in the UI!

2.2. Terms

transport

Spans sent by the instrumented library must be transported from the services being traced to Zipkin collectors. There are three primary transports: HTTP, Kafka and Scribe.

trace

trace表示一個api調(diào)用鏈,即經(jīng)過哪些service市殷,每個service消耗的時間刹衫,等

span

span表示每次調(diào)用带迟,即參與api調(diào)用鏈的一個service。主要包含三個基本元素仓犬,span_id, parenet_id, trace_id搀继,其他信息還包含,name财边、duration点骑、tags、localEndpoint等

{
      "traceId": "5982fe77008310cc80f1da5e10147517",
      "name": "query",
      "id": "be2d01e33cc78d97",
      "parentId": "ebf33e1a81dc6f71",
      "timestamp": 1458702548786000,
      "duration": 13000,
      "localEndpoint": {
        "serviceName": "zipkin-query",
        "ipv4": "192.168.1.2",
        "port": 9411
      },
      "remoteEndpoint": {
        "serviceName": "spanstore-jdbc",
        "ipv4": "127.0.0.1",
        "port": 3306
      },
      "annotations": [
        {
          "timestamp": 1458702548786000,
          "value": "cs"
        },
        {
          "timestamp": 1458702548799000,
          "value": "cr"
        }
      ],
      "tags": {
        "jdbc.query": "select distinct `zipkin_spans`.`trace_id` from `zipkin_spans` join `zipkin_annotations` on (`zipkin_spans`.`trace_id` = `zipkin_annotations`.`trace_id` and `zipkin_spans`.`id` = `zipkin_annotations`.`span_id`) where (`zipkin_annotations`.`endpoint_service_name` = ? and `zipkin_spans`.`start_ts` between ? and ?) order by `zipkin_spans`.`start_ts` desc limit ?",
        "sa": "true"
      }
    }

2.3. 工作原理

如何使用zipkin

3. 啟動zipkin

  • zipkin提供了多種啟動方式吵瞻,java甘磨、docker济舆、docker-compose等
docker run -d -p 9411:9411 openzipkin/zipkin

4. flask+zipkin

  • start multiple service
$ SERVICE_NAME=app3 SERVICE_PORT=6002 \
python app.py
$ SERVICE_NAME=app2 SERVICE_PORT=6001 NEXT_SERVICE_API=http://localhost:6002 \
python app.py
$ SERVICE_NAME=app1 SERVICE_PORT=6000 NEXT_SERVICE_API=http://localhost:6001 \
python app.py
  • call api portal
$ http :6000/hello
HTTP/1.0 200 OK
Content-Length: 5
Content-Type: text/html; charset=utf-8
Date: Sun, 14 Jun 2020 05:14:33 GMT
Server: Werkzeug/1.0.1 Python/3.6.9

hello

5. code

  • app.py
from flask import Flask, request, abort, g
from py_zipkin.zipkin import create_http_headers_for_new_span
import requests
from time import sleep
from random import randint

import config as global_config
from logging_helper import logger
from zipkin import flask_start_zipkin, flask_stop_zipkin, set_tags


def create_app(config=None):
    app = Flask(__name__)

    config_app(app, config)
    init_controller(app)

    @app.before_request
    def before():
        flask_start_zipkin()

    @app.teardown_request
    def teardown(e):
        flask_stop_zipkin()

    return app


def init_controller(app):
    @app.route('/<string:name>', methods=['GET'])
    def do_stuff(name):
        logger.info(f'{global_config.SERVICE_NAME} - {name}')
        sleep(randint(100, 1000)/1000)
        if global_config.NEXT_SERVICE_API:
            headers = create_http_headers_for_new_span()
            requests.get(f'{global_config.NEXT_SERVICE_API}/{name}', headers=headers)
            set_tags(dict(api_name=name))
        return name, 200


def config_app(app, config):
    app.config.from_object(global_config)

    if config is not None and isinstance(config, dict):
        app.config.update(config)


if __name__ == '__main__':
    app = create_app()
    app.run(host="0.0.0.0", port=global_config.SERVICE_PORT, debug=True)
  • config.py
import os

env = os.environ.get
SERVICE_NAME = env('SERVICE_NAME', 'try_zipkin')
SERVICE_PORT = env('SERVICE_PORT', 6000)
NEXT_SERVICE_API = env('NEXT_SERVICE_API')

# ===== Zipkin ========
ZIPKIN_HOST = env('ZIPKIN_HOST', '127.0.0.1')
ZIPKIN_PORT = env('ZIPKIN_PORT', 9411)
ZIPKIN_SAMPLE_RATE = env('ZIPKIN_SAMPLE_RATE', 100.0)
ZIPKIN_DISABLE = env("ZIPKIN_DISABLE", False)
ZIPKIN_SERVICE_NAME = SERVICE_NAME
  • zipkin.py
import random
import functools
from flask import request, g
import requests
from py_zipkin.zipkin import zipkin_span, ZipkinAttrs
from py_zipkin.transport import BaseTransportHandler

import config as config
from logging_helper import logger


def gen_hex_str(length=16):
    charset = (
        'abcdef'
        '0123456789'
    )
    return ''.join([random.choice(charset) for _ in range(length)])


class HttpTransport(BaseTransportHandler):
    def get_max_payload_bytes(self):
        return None

    def send(self, encoded_span):
        # The collector expects a thrift-encoded list of spans.
        try:
            requests.post(
                f'http://{config.ZIPKIN_HOST}:{config.ZIPKIN_PORT}/api/v1/spans',
                data=encoded_span,
                headers={'Content-Type': 'application/x-thrift'},
                timeout=(1, 5),
            )
        except Exception as e:
            logger.exception("Failed to send to zipkin: %s", str(e))


class KafkaTransport(BaseTransportHandler):

    def get_max_payload_bytes(self):
        # By default Kafka rejects messages bigger than 1000012 bytes.
        return 1000012

    def send(self, message):
        from kafka import SimpleProducer, KafkaClient
        kafka_client = KafkaClient('{}:{}'.format('localhost', 9092))
        producer = SimpleProducer(kafka_client)
        producer.send_messages('kafka_topic_name', message)


def with_zipkin_span(span_name, **kwargs):
    """https://github.com/Yelp/py_zipkin/issues/96
    """
    def decorate(f):
        @functools.wraps(f)
        def inner(*args, **kw):
            zipkin_kwargs = dict(
                span_name=span_name,
                service_name=config.ZIPKIN_SERVICE_NAME
            )
            zipkin_kwargs.update(**kwargs)
            with zipkin_span(**zipkin_kwargs):
                return f(*args, **kw)
        return inner
    return decorate


def set_tags(extra_annotations):
    if getattr(g, '_zipkin_span', None):
        logger.info("Set tags")
        try:
            span = g._zipkin_span
            if span:
                logger.info("update: %s", extra_annotations)
                span.update_binary_annotations(extra_annotations)
        except Exception as e:
            logger.log_critical_error("Failed to set zipkin: %s", str(e))


def get_zipkin_attrs(headers):
    trace_id = headers.get('X-B3-TraceID') or gen_hex_str()
    span_id = headers.get('X-B3-SpanID') or gen_hex_str()
    parent_span_id = headers.get('X-B3-ParentSpanID')
    flags = headers.get('X-B3-Flags')
    is_sampled = headers.get('X-B3-Sampled') == '1'

    return ZipkinAttrs(
        trace_id=trace_id,
        span_id=span_id,
        parent_span_id=parent_span_id,
        flags=flags,
        is_sampled=is_sampled,
    )


def flask_start_zipkin():
    """
    Put it to before_request event.
    :return:
    """
    if config.ZIPKIN_DISABLE:
        return
    zipkin_attrs = get_zipkin_attrs(request.headers)
    if request.headers.get('X-B3-TraceID') or request.headers.get('X-B3-SpanID'):
        logger.info(f'Zipkin Debug: received header: {request.headers}')
    span = zipkin_span(
        service_name=config.ZIPKIN_SERVICE_NAME,
        span_name=f'{request.endpoint}.{request.method}',
        transport_handler=HttpTransport(),
        host=config.ZIPKIN_HOST,
        port=config.ZIPKIN_PORT,
        sample_rate=config.ZIPKIN_SAMPLE_RATE,
        zipkin_attrs=zipkin_attrs,
    )
    g._zipkin_span = span
    g._zipkin_span.start()


def flask_stop_zipkin():
    """
    Put it to tear_request event.
    :return:
    """
    if config.ZIPKIN_DISABLE:
        return

    if getattr(g, '_zipkin_span', None):
        print(f'stop zipkin span {g._zipkin_span}')
        g._zipkin_span.stop()
  • logging_helper.py
import logging
import types
import sys

import config as config


def init_logger_handler():
    logger_ = logging.getLogger(config.SERVICE_NAME)  # type: logging.Logger

    logger_.setLevel(logging.INFO)

    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)
    logger_.addHandler(handler)
    return logger_


def log_response_error(self, resp):
    if sys.exc_info() != (None, None, None):
        self.exception('request failed')

    if resp is None:
        self.error('request hasn\'t been sent out')
    else:
        try:
            self.error(resp.json())
        except Exception:
            try:
                self.error(resp.text)
            except Exception:
                self.error(f'unknown resp content (status code {resp.status_code})')


logger = init_logger_handler()
logger.log_response_error = types.MethodType(log_response_error, logger)
  • requirements.txt
-i https://mirrors.aliyun.com/pypi/simple
flask
requests
py_zipkin

6. references

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末措拇,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子浅悉,更是在濱河造成了極大的恐慌券犁,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件荞估,死亡現(xiàn)場離奇詭異泼舱,居然都是意外死亡枷莉,警方通過查閱死者的電腦和手機尺迂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蹲盘,“玉大人膳音,你說我怎么就攤上這事〔粤荩” “怎么了?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵宣肚,是天一觀的道長悠栓。 經(jīng)常有香客問我,道長笙瑟,這世上最難降的妖魔是什么癞志? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮师溅,結(jié)果婚禮上盾舌,老公的妹妹穿的比我還像新娘。我一直安慰自己窿锉,他們只是感情好膝舅,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著洼滚,像睡著了一般技潘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上铲掐,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天值桩,我揣著相機與錄音,去河邊找鬼携栋。 笑死,一個胖子當著我的面吹牛增蹭,可吹牛的內(nèi)容都是我干的磅摹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼饼灿,長吁一口氣:“原來是場噩夢啊……” “哼帝美!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起庇忌,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤舰褪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后略就,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體晃酒,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡贝次,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了恼布。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搁宾。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡倔幼,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出翩腐,到底是詐尸還是另有隱情,我是刑警寧澤何什,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布等龙,位于F島的核電站,受9級特大地震影響罐栈,放射性物質(zhì)發(fā)生泄漏泥畅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一位仁、第九天 我趴在偏房一處隱蔽的房頂上張望柑贞。 院中可真熱鬧,春花似錦聂抢、人聲如沸钧嘶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽康辑。三九已至,卻和暖如春轿亮,著一層夾襖步出監(jiān)牢的瞬間疮薇,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工我注, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留按咒,地道東北人但骨。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓励七,卻偏偏與公主長得像,于是被迫代替她去往敵國和親奔缠。 傳聞我的和親對象是個殘疾皇子掠抬,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354