APIゲートウェイとしてHAProxy使用して、パート1 [はじめに]

転送:https://www.haproxy.com/blog/using-haproxy-as-an-api-gateway-part-1/

APIゲートウェイは、負荷分散、セキュリティ、レート制限、監視、およびAPIサービスのための他の横断的関心事を扱います。HAProxy EnterpriseはAPIゲートウェイとして優れ方法を学ぶために読んでください。

"危険!雪崩エリアは、」あなたはコロラド州のいくつかの部分をドライブしたときに表示されますサインです。冬の周囲の山々を見ると、あなたがいつでも雪のサージを注ぐかもしれない巨人を眠っていることにより、クリーピングしている感覚を得ます。それが十分でなかった場合は、埋葬されるならば、そのような場所を通してのみ駆動することは誰もが今まで知っているだろう、などのように見えることができますか?

IT事業者として、あなたの仕事では、現代のITシステムの管理の重量は、あなたと同じ、切望感を与えることができます。インフラに蓄積複雑さは雪が山の斜面に形成のようなものです。あなたが埋もれている場合、人々が知っている前に、どのくらいの時間がかかりますか?あなたはどこのことができます複雑さの負荷を軽減するために持っています!

私たちはここに対処するだろう複雑の具体的な形は、外の世界に内部microservicesを接続するのです。認証などの内部機能、、、顧客データを取得し、製品の詳細情報を取得し、支払いを取るには、あなたのフロントエンドクライアントに公開する必要があります。これは、これらの関数シグネチャを発現するアプリケーション・プログラミング・インターフェース(API)を定義することによって達成されます。

チャレンジは、クライアントが、バックエンドAPIへの直接接続有する管理およびスケールすることは困難であるフロントエンドとバックエンドの構成要素間の密結合を作成することです。これを処理し、さらに外部クライアントがあなたのAPIにアクセスする方法を統合することが何であるかを、呼び出している人の上にいくつかの観測を取得する方法。単一、統一URLの後ろに異種のAPIを組み合わせることで、APIゲートウェイの範囲です。このように、クライアントがゲートウェイに単一の参照を維持することができ、それが正しい場所へのルートそれらをでしょう。また、インターネットに公開する必要のある小さな領域を取得します。

オープンソースAPIゲートウェイ

APIゲートウェイは、インテリジェントルーティング要求クライアントとバックエンドサービス間のソフトウェアの層です。HAProxy、世界最速かつ最も広く使われているソフトウェアロードバランサは、非常によくAPIゲートウェイとしての役割を満たします。以下のためのAPIコールのルーティングに加えて  /カート  または  /カタログを  適切なバックエンドサービスに、それはまた、負荷分散、セキュリティ、レート制限、監視、およびその他の横断的関心事を扱います。本質的には、共有HAProxyインスタンスの後ろにあなたのAPIのすべてを置くことによって、これらの要件をオフロードすることができます。

APIゲートウェイは、フロントエンドコードとバックエンドAPIエンドポイントが密結合されないように要求を転送するオーケストレーション層となります。すべてのデバイスは、単一のドメインを指すことができますし、HAProxyは、ルーティングを処理します。

 

haproxy APIゲートウェイ

Due to its speed, high availability and reliability, HAProxy can be used as a API gateway

 

Here are some of the functions that an HAProxy API gateway will handle for you:

  • High Performance
  • Load balancing
  • HTTP routing
  • Security
  • Rate limiting
  • Observability
  • Connection queuing
  • Circuit-breaking
  • Authentication
  • Device Detection

Let’s explore some of these features in more detail.

HTTP Routing

The primary role of the API gateway is to route an incoming client request to the appropriate internal service. HAProxy can route based on any information found in the HTTP request, including portions of the URL path, query string, and HTTP headers.

In the following example, our HAProxy configuration sets up a frontend that accepts incoming requests on port 443, checks their URL paths for /cart and /catalog, and then forwards them to the correct backend.

  frontend api_gateway
  bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
  acl PATH_cart path_beg -i /cart
  acl PATH_catalog path_beg -i /catalog
  use_backend be_cart if PATH_cart
  use_backend be_catalog if PATH_catalog
   
  backend be_cart
  server s1 10.0.0.3:80
   
  backend be_catalog
  server s1 10.0.0.5:80


If you are managing multiple website domains, then you can check the Host header when determining how to route requests. Here’s an example that will segregate API requests depending on the domain. When accessing, for example, api.haproxy.com, it will only route requests for /catalog and /cart. B2B partners that access partner.haproxy.com can access the /inventory API.

  frontend api_gateway
  bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
   
  acl VHOST_publicapi req.hdr(Host) -i -m dom api.haproxy.com api.haproxy.fr
  acl VHOST_partnersapi req.hdr(Host) -i -m dom partner.haproxy.com partner.haproxy.fr
   
  acl PATH_catalog path_beg -i /catalog
  acl PATH_cart path_beg -i /cart
  acl PATH_inventory path_beg -i /inventory
   
  use_backend be_cart if VHOST_publicapi PATH_cart
  use_backend be_catalog if VHOST_publicapi PATH_catalog
  use_backend be_inventory if VHOST_partnersapi PATH_inventory
   
  backend be_cart
  server s1 10.0.0.3:80
   
  backend be_catalog
  server s1 10.0.0.5:80
   
  backend be_inventory
  server s1 10.0.0.7


Note that HAProxy is extremely flexible and powerful and the examples provided are just simple use cases. HAProxy can apply more complex logic for HTTP routing and request handling.

 

If an application requires tens, hundreds, or even thousands of paths in a single ACL, then it is better to manage them through a map file. A map file stores key/value associations in memory. In our example, the key would be the “host/path” string and the value would be the name of the backend to route the request to. The map file routing.map would contain:

  # endpoint backend name
  api.haproxy.com/catalog/ be_catalog
  api.haproxy.fr/catalog/ be_catalog
  api.haproxy.com/cart/ be_cart
  api.haproxy.fr/cart/ be_cart
  partner.haproxy.com/inventory/ be_inventory
  partner.haproxy.fr/inventory/ be_inventory


Our HAProxy configuration would contain:

  frontend api_gateway
  # …
  use_backend %[base,map_beg(“/etc/hapee-1.8/routing.map”)]

 

DID YOU KNOW?The  base fetch method returns the concatenation of the Host header and the path part of the request, which starts at the first slash and ends before the question mark.

To simplify the process of adding or removing path-to-backend associations, you can enable the HAProxy Enterprise “lb-update” module. This module can read the contents of the map file and refresh the ACLs during runtime, without the need to reload HAProxy.

Load Balancing

 

haproxy負荷分散アルゴリズム

With HAProxy, the load balancing algorithm can be adjusted to suit the type of service and protocol

 

In order to improve the performance and resilience of each API endpoint, it’s recommended to replicate the service over several nodes. Then, the API gateway will balance incoming client requests among them. You can adjust the load balancing algorithm to suit the type of service and protocol.

  • For quick and short API calls, use the roundrobin algorithm
  • For longer-lived websockets, use the leastconn algorithm
  • For services that have backend servers optimized to process particular functions, use the uri algorithm

In the following example, the mobile API backend is balanced across two nodes using the roundrobin algorithm.

  backend mobile_api
  balance roundrobin
  server s1 10.0.0.3:80
  server s2 10.0.0.4:80


Load balancing your API endpoints improves performance and creates redundancy. Note that you can choose the most appropriate balancing algorithm on a per-backend basis.

 

You can also define active and passive health checks for your servers so that HAProxy automatically reroutes traffic if there’s a problem. In the following example, we monitor the health of our servers by sending GET requests to the /health URL and expecting a successful response.

  backend mobile_api
  balance roundrobin
  option httpchk GET /health
  server s1 10.0.0.3:80 check
  server s2 10.0.0.4:80 check


The option httpchk directive sets the method and URL to monitor. If you append \r\nyou can add additional HTTP headers to this request. A check parameter is added to each server to enable the feature. Being able to watch a URL endpoint works well with tools like Prometheus that already expose a /metrics web page used for scraping metrics.

 

HAProxy maxconn

The HAProxy load balancer stands in a strategic position, between your clients and services, ensuring that no backend nodes are saturated by spikes in traffic. Without this, all requests would be forwarded to the backend servers, risking high wait times and timeouts.

HAProxy implements queuing mechanisms to prevent sending too many requests at once to a service. Add the maxconn argument to a server directive to queue additional requests within the gateway, as shown:

  backend mobile_api
  balance roundrobin
  server s1 10.0.0.3:80 maxconn 100
  server s2 10.0.0.4:80 maxconn 100


In this case, up to 100 connections can be established at once to a server. Any more than that will be queued. This relieves strain on your servers, allowing them to process requests more efficiently. HAProxy is highly proficient at managing queues of this sort.

 

Rate Limiting

 

haproxyレート制限します

HAProxy’s Stick Tables can be used to limit the number of requests sent to the API by one client

 

You may want to limit the number of requests a client can send to your APIs within a period of time. This might be a to enforce a quota for various tiers of customers. To be allowed to send more requests, clients could subscribe to a higher-priced tier.

In HAProxy, stick tables can be used for such a purpose. You can track clients by IP address, cookie or other means such as API tokens passed in the URL or headers. In this example, the client is expected to pass a URL parameter called apitoken and is limited to 1000 requests within 24 hours. The period is set with the expire parameter on the stick-table directive.

  frontend api_gateway
  bind :443 ssl crt /etc/hapee-1.8/certs/cert.pem
  stick-table type string size 1m expire 24h store http_req_cnt
   
  acl exceeds_limit url_param(apitoken),table_http_req_cnt(api_gateway) gt 1000
   
  http-request track-sc0 url_param(apitoken) unless exceeds_limit
  http-request deny deny_status 429 if exceeds_limit


Now, as I make requests to the site, passing the URL parameter, apitoken=abcdefg, the count of HTTP requests is incremented. I can see this by logging into the server via SSH and querying the Runtime API. In the following example, I’ve made 12 requests using my API token.

 

  root@server1:~$ echo "show table api_gateway" | socat UNIX-CONNECT:/var/run/haproxy.sock stdio
  # table: api_gateway, type: string, size:1048576, used:1
  0x55bd73392fa4: key=abcdefg use=0 exp=86396974 http_req_cnt=12

When clients go past their limit, they’ll receive a 429 Too Many Requests response. Check out our blog post Introduction to HAProxy Stick Tables for more information about defining stick tables and other examples of rate limiting.

DID YOU KNOW?Adding  deny_status to the  http-request deny directive allows you to set a custom response code when rejecting requests. Possible values are 200, 400, 403, 405, 408, 425, 429, 500, 502, 503, 504

Optionally, instead of a daily limit as used above, you can also do it based on the rate of the requests. This acts as a security feature to prevent abuse or clients with runaway processes. The following example allows a client to make no more than one request per second.
(Note: While the above and below are separate examples they could also be combined to provide extra control)

Detailed monitoring and statistics

HAProxy is very famous for the level of details it provides on the traffic it processes. There are two main features: the statistic dashboard and the logs.

Statistics Dashboard

You can enable an HTML statistics page within HAProxy and HAProxy Enterprise, which comes as a set of tabular data with many metrics for each frontendbackend, backend server and frontend bind line. The image below shows an example of the HAProxy Enterprise Real Time dashboard:

 

haproxyリアルタイムダッシュボード

HAProxy’s Real-Time Dashboard

 

This data is also available by querying the HAProxy Runtime API. JSON (within the Runtime API) and CSV (within both the dashboard and the Runtime API) are also available for easy integration with third party tools like Prometheus, Grafana, and SNMP. The image below shows an integration of HAProxy with Grafana, via the Prometheus exporter:

 

haproxy統合grafana

Integration of HAProxy with Grafana, via the Prometheus exporter

 

Logs

The HAProxy logs are a gold mine of information, since HAProxy can report the following information for each API call:

  • Client IP, port
  • Routing within HAProxy: frontend, backend, server
  • URL endpoint with query string
  • Timers: time for the client to send the request, server connection time, response time, total session duration, etc…
  • Termination status: did the session finished properly or not, if not what happened and at what phase of the session (connection time, header time, data streaming time, etc…)
  • Any custom header or cookie you want to capture
  • Any SSL / TLS information

Based on all the information provided above, it is possible to build reports and to figure out when and where problems are occurring (e.g. Is it networking? The application? A particular server?).

 

Conclusion

この記事では、APIゲートウェイとは何か、それは外部のクライアントに接続microservicesを簡素化する方法を学びました。また、ロードバランサは、APIゲートウェイとしてどのように機能するかをHAProxy見た:ルーティング、ロードバランシング、レート制限やその他の複雑さを管理します。

おすすめ

転載: www.cnblogs.com/rongfengliang/p/11118337.html