• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2014 Tatsuhiro Tsujikawa
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 #ifndef H2LOAD_H
26 #define H2LOAD_H
27 
28 #include "nghttp2_config.h"
29 
30 #include <sys/types.h>
31 #ifdef HAVE_SYS_SOCKET_H
32 #  include <sys/socket.h>
33 #endif // HAVE_SYS_SOCKET_H
34 #ifdef HAVE_NETDB_H
35 #  include <netdb.h>
36 #endif // HAVE_NETDB_H
37 #include <sys/un.h>
38 
39 #include <vector>
40 #include <string>
41 #include <unordered_map>
42 #include <memory>
43 #include <chrono>
44 #include <array>
45 
46 #define NGHTTP2_NO_SSIZE_T
47 #include <nghttp2/nghttp2.h>
48 
49 #ifdef ENABLE_HTTP3
50 #  include <ngtcp2/ngtcp2.h>
51 #  include <ngtcp2/ngtcp2_crypto.h>
52 #endif // ENABLE_HTTP3
53 
54 #include <ev.h>
55 
56 #include "ssl_compat.h"
57 
58 #ifdef NGHTTP2_OPENSSL_IS_WOLFSSL
59 #  include <wolfssl/options.h>
60 #  include <wolfssl/openssl/ssl.h>
61 #else // !NGHTTP2_OPENSSL_IS_WOLFSSL
62 #  include <openssl/ssl.h>
63 #endif // !NGHTTP2_OPENSSL_IS_WOLFSSL
64 
65 #include "http2.h"
66 #ifdef ENABLE_HTTP3
67 #  include "quic.h"
68 #endif // ENABLE_HTTP3
69 #include "memchunk.h"
70 #include "template.h"
71 
72 using namespace nghttp2;
73 
74 namespace h2load {
75 
76 constexpr auto BACKOFF_WRITE_BUFFER_THRES = 16_k;
77 
78 class Session;
79 struct Worker;
80 
81 struct Config {
82   std::vector<std::vector<nghttp2_nv>> nva;
83   std::vector<std::string> h1reqs;
84   std::vector<std::chrono::steady_clock::duration> timings;
85   nghttp2::Headers custom_headers;
86   std::string scheme;
87   std::string host;
88   std::string connect_to_host;
89   std::string ifile;
90   std::string ciphers;
91   std::string tls13_ciphers;
92   // supported groups (or curves).
93   std::string groups;
94   // length of upload data
95   int64_t data_length;
96   // memory mapped upload data
97   uint8_t *data;
98   addrinfo *addrs;
99   size_t nreqs;
100   size_t nclients;
101   size_t nthreads;
102   // The maximum number of concurrent streams per session.
103   size_t max_concurrent_streams;
104   size_t window_bits;
105   size_t connection_window_bits;
106   size_t max_frame_size;
107   // rate at which connections should be made
108   size_t rate;
109   ev_tstamp rate_period;
110   // amount of time for main measurements in timing-based test
111   ev_tstamp duration;
112   // amount of time to wait before starting measurements in timing-based test
113   ev_tstamp warm_up_time;
114   // amount of time to wait for activity on a given connection
115   ev_tstamp conn_active_timeout;
116   // amount of time to wait after the last request is made on a connection
117   ev_tstamp conn_inactivity_timeout;
118   enum { PROTO_HTTP2, PROTO_HTTP1_1 } no_tls_proto;
119   uint32_t header_table_size;
120   uint32_t encoder_header_table_size;
121   // file descriptor for upload data
122   int data_fd;
123   // file descriptor to write per-request stats to.
124   int log_fd;
125   // base file name of qlog output files
126   std::string qlog_file_base;
127   uint16_t port;
128   uint16_t default_port;
129   uint16_t connect_to_port;
130   bool verbose;
131   bool timing_script;
132   std::string base_uri;
133   // true if UNIX domain socket is used.  In this case, base_uri is
134   // not used in usual way.
135   bool base_uri_unix;
136   // used when UNIX domain socket is used (base_uri_unix is true).
137   sockaddr_un unix_addr;
138   // list of supported ALPN protocol strings in the order of
139   // preference.
140   std::vector<std::string> alpn_list;
141   // The number of request per second for each client.
142   double rps;
143   // Disables GSO for UDP connections.
144   bool no_udp_gso;
145   // The maximum UDP datagram payload size to send.
146   size_t max_udp_payload_size;
147   // Enable ktls.
148   bool ktls;
149   // sni is the value sent in TLS SNI, overriding DNS name of the
150   // remote host.
151   std::string sni;
152 
153   Config();
154   ~Config();
155 
156   bool is_rate_mode() const;
157   bool is_timing_based_mode() const;
158   bool has_base_uri() const;
159   bool rps_enabled() const;
160   bool is_quic() const;
161 };
162 
163 struct RequestStat {
164   // time point when request was sent
165   std::chrono::steady_clock::time_point request_time;
166   // same, but in wall clock reference frame
167   std::chrono::system_clock::time_point request_wall_time;
168   // time point when stream was closed
169   std::chrono::steady_clock::time_point stream_close_time;
170   // upload data length sent so far
171   int64_t data_offset;
172   // HTTP status code
173   int status;
174   // true if stream was successfully closed.  This means stream was
175   // not reset, but it does not mean HTTP level error (e.g., 404).
176   bool completed;
177 };
178 
179 struct ClientStat {
180   // time client started (i.e., first connect starts)
181   std::chrono::steady_clock::time_point client_start_time;
182   // time client end (i.e., client somehow processed all requests it
183   // is responsible for, and disconnected)
184   std::chrono::steady_clock::time_point client_end_time;
185   // The number of requests completed successful, but not necessarily
186   // means successful HTTP status code.
187   size_t req_success;
188 
189   // The following 3 numbers are overwritten each time when connection
190   // is made.
191 
192   // time connect starts
193   std::chrono::steady_clock::time_point connect_start_time;
194   // time to connect
195   std::chrono::steady_clock::time_point connect_time;
196   // time to first byte (TTFB)
197   std::chrono::steady_clock::time_point ttfb;
198 };
199 
200 struct SDStat {
201   // min, max, mean and sd (standard deviation)
202   double min, max, mean, sd;
203   // percentage of samples inside mean -/+ sd
204   double within_sd;
205 };
206 
207 struct SDStats {
208   // time for request
209   SDStat request;
210   // time for connect
211   SDStat connect;
212   // time to first byte (TTFB)
213   SDStat ttfb;
214   // request per second for each client
215   SDStat rps;
216 };
217 
218 struct Stats {
219   Stats(size_t req_todo, size_t nclients);
220   // The total number of requests
221   size_t req_todo;
222   // The number of requests issued so far
223   size_t req_started;
224   // The number of requests finished
225   size_t req_done;
226   // The number of requests completed successful, but not necessarily
227   // means successful HTTP status code.
228   size_t req_success;
229   // The number of requests marked as success.  HTTP status code is
230   // also considered as success. This is subset of req_done.
231   size_t req_status_success;
232   // The number of requests failed. This is subset of req_done.
233   size_t req_failed;
234   // The number of requests failed due to network errors. This is
235   // subset of req_failed.
236   size_t req_error;
237   // The number of requests that failed due to timeout.
238   size_t req_timedout;
239   // The number of bytes received on the "wire". If SSL/TLS is used,
240   // this is the number of decrypted bytes the application received.
241   int64_t bytes_total;
242   // The number of bytes received for header fields.  This is
243   // compressed version.
244   int64_t bytes_head;
245   // The number of bytes received for header fields after they are
246   // decompressed.
247   int64_t bytes_head_decomp;
248   // The number of bytes received in DATA frame.
249   int64_t bytes_body;
250   // The number of each HTTP status category, status[i] is status code
251   // in the range [i*100, (i+1)*100).
252   std::array<size_t, 6> status;
253   // The statistics per request
254   std::vector<RequestStat> req_stats;
255   // The statistics per client
256   std::vector<ClientStat> client_stats;
257   // The number of UDP datagrams received.
258   size_t udp_dgram_recv;
259   // The number of UDP datagrams sent.
260   size_t udp_dgram_sent;
261 };
262 
263 enum ClientState { CLIENT_IDLE, CLIENT_CONNECTED };
264 
265 // This type tells whether the client is in warmup phase or not or is over
266 enum class Phase {
267   INITIAL_IDLE,  // Initial idle state before warm-up phase
268   WARM_UP,       // Warm up phase when no measurements are done
269   MAIN_DURATION, // Main measurement phase; if timing-based
270                  // test is not run, this is the default phase
271   DURATION_OVER  // This phase occurs after the measurements are over
272 };
273 
274 struct Client;
275 
276 // We use reservoir sampling method
277 struct Sampling {
278   // maximum number of samples
279   size_t max_samples;
280   // number of samples seen, including discarded samples.
281   size_t n;
282 };
283 
284 struct Worker {
285   MemchunkPool mcpool;
286   std::mt19937 randgen;
287   Stats stats;
288   Sampling request_times_smp;
289   Sampling client_smp;
290   struct ev_loop *loop;
291   SSL_CTX *ssl_ctx;
292   Config *config;
293   size_t progress_interval;
294   uint32_t id;
295   bool tls_info_report_done;
296   bool app_info_report_done;
297   size_t nconns_made;
298   // number of clients this worker handles
299   size_t nclients;
300   // number of requests each client issues
301   size_t nreqs_per_client;
302   // at most nreqs_rem clients get an extra request
303   size_t nreqs_rem;
304   size_t rate;
305   // maximum number of samples in this worker thread
306   size_t max_samples;
307   ev_timer timeout_watcher;
308   // The next client ID this worker assigns
309   uint32_t next_client_id;
310   // Keeps track of the current phase (for timing-based experiment) for the
311   // worker
312   Phase current_phase;
313   // We need to keep track of the clients in order to stop them when needed
314   std::vector<Client *> clients;
315   // This is only active when there is not a bounded number of requests
316   // specified
317   ev_timer duration_watcher;
318   ev_timer warmup_watcher;
319 
320   Worker(uint32_t id, SSL_CTX *ssl_ctx, size_t nreq_todo, size_t nclients,
321          size_t rate, size_t max_samples, Config *config);
322   ~Worker();
323   Worker(Worker &&o) = default;
324   void run();
325   void sample_req_stat(RequestStat *req_stat);
326   void sample_client_stat(ClientStat *cstat);
327   void report_progress();
328   void report_rate_progress();
329   // This function calls the destructors of all the clients.
330   void stop_all_clients();
331   // This function frees a client from the list of clients for this Worker.
332   void free_client(Client *);
333 };
334 
335 struct Stream {
336   RequestStat req_stat;
337   int status_success;
338   Stream();
339 };
340 
341 struct Client {
342   DefaultMemchunks wb;
343   std::unordered_map<int32_t, Stream> streams;
344   ClientStat cstat;
345   std::unique_ptr<Session> session;
346   ev_io wev;
347   ev_io rev;
348   std::function<int(Client &)> readfn, writefn;
349   Worker *worker;
350   SSL *ssl;
351 #ifdef ENABLE_HTTP3
352   struct {
353     ngtcp2_crypto_conn_ref conn_ref;
354     ev_timer pkt_timer;
355     ngtcp2_conn *conn;
356     ngtcp2_ccerr last_error;
357     bool close_requested;
358     FILE *qlog_file;
359 
360     struct {
361       bool send_blocked;
362       size_t num_blocked;
363       size_t num_blocked_sent;
364       struct {
365         Address remote_addr;
366         const uint8_t *data;
367         size_t datalen;
368         size_t gso_size;
369       } blocked[2];
370       std::unique_ptr<uint8_t[]> data;
371     } tx;
372   } quic;
373 #endif // ENABLE_HTTP3
374   ev_timer request_timeout_watcher;
375   addrinfo *next_addr;
376   // Address for the current address.  When try_new_connection() is
377   // used and current_addr is not nullptr, it is used instead of
378   // trying next address though next_addr.  To try new address, set
379   // nullptr to current_addr before calling connect().
380   addrinfo *current_addr;
381   size_t reqidx;
382   ClientState state;
383   // The number of requests this client has to issue.
384   size_t req_todo;
385   // The number of requests left to issue
386   size_t req_left;
387   // The number of requests currently have started, but not abandoned
388   // or finished.
389   size_t req_inflight;
390   // The number of requests this client has issued so far.
391   size_t req_started;
392   // The number of requests this client has done so far.
393   size_t req_done;
394   // The client id per worker
395   uint32_t id;
396   int fd;
397   Address local_addr;
398   ev_timer conn_active_watcher;
399   ev_timer conn_inactivity_watcher;
400   std::string selected_proto;
401   bool new_connection_requested;
402   // true if the current connection will be closed, and no more new
403   // request cannot be processed.
404   bool final;
405   // rps_watcher is a timer to invoke callback periodically to
406   // generate a new request.
407   ev_timer rps_watcher;
408   // The timestamp that starts the period which contributes to the
409   // next request generation.
410   std::chrono::steady_clock::time_point rps_duration_started;
411   // The number of requests allowed by rps, but limited by stream
412   // concurrency.
413   size_t rps_req_pending;
414   // The number of in-flight streams.  req_inflight has similar value
415   // but it only measures requests made during Phase::MAIN_DURATION.
416   // rps_req_inflight measures the number of requests in all phases,
417   // and it is only used if --rps is given.
418   size_t rps_req_inflight;
419 
420   enum { ERR_CONNECT_FAIL = -100 };
421 
422   Client(uint32_t id, Worker *worker, size_t req_todo);
423   ~Client();
424   int make_socket(addrinfo *addr);
425   int connect();
426   void disconnect();
427   void fail();
428   // Call this function when do_read() returns -1.  This function
429   // tries to connect to the remote host again if it is requested.  If
430   // so, this function returns 0, and this object should be retained.
431   // Otherwise, this function returns -1, and this object should be
432   // deleted.
433   int try_again_or_fail();
434   void timeout();
435   void restart_timeout();
436   int submit_request();
437   void process_request_failure();
438   void process_timedout_streams();
439   void process_abandoned_streams();
440   void report_tls_info();
441   void report_app_info();
442   void terminate_session();
443   // Asks client to create new connection, instead of just fail.
444   void try_new_connection();
445 
446   int do_read();
447   int do_write();
448 
449   // low-level I/O callback functions called by do_read/do_write
450   int connected();
451   int read_clear();
452   int write_clear();
453   int tls_handshake();
454   int read_tls();
455   int write_tls();
456 
457   int on_read(const uint8_t *data, size_t len);
458   int on_write();
459 
460   int connection_made();
461 
462   void on_request(int32_t stream_id);
463   void on_header(int32_t stream_id, const uint8_t *name, size_t namelen,
464                  const uint8_t *value, size_t valuelen);
465   void on_status_code(int32_t stream_id, uint16_t status);
466   // |success| == true means that the request/response was exchanged
467   // |successfully, but it does not mean response carried successful
468   // |HTTP status code.
469   void on_stream_close(int32_t stream_id, bool success, bool final = false);
470   // Returns RequestStat for |stream_id|.  This function must be
471   // called after on_request(stream_id), and before
472   // on_stream_close(stream_id, ...).  Otherwise, this will return
473   // nullptr.
474   RequestStat *get_req_stat(int32_t stream_id);
475 
476   void record_request_time(RequestStat *req_stat);
477   void record_connect_start_time();
478   void record_connect_time();
479   void record_ttfb();
480   void clear_connect_times();
481   void record_client_start_time();
482   void record_client_end_time();
483 
484   void signal_write();
485 
486 #ifdef ENABLE_HTTP3
487   // QUIC
488   int quic_init(const sockaddr *local_addr, socklen_t local_addrlen,
489                 const sockaddr *remote_addr, socklen_t remote_addrlen);
490   void quic_free();
491   int read_quic();
492   int write_quic();
493   int write_udp(const sockaddr *addr, socklen_t addrlen, const uint8_t *data,
494                 size_t datalen, size_t gso_size);
495   void on_send_blocked(const ngtcp2_addr &remote_addr, const uint8_t *data,
496                        size_t datalen, size_t gso_size);
497   int send_blocked_packet();
498   void quic_close_connection();
499 
500   int quic_handshake_completed();
501   int quic_recv_stream_data(uint32_t flags, int64_t stream_id,
502                             const uint8_t *data, size_t datalen);
503   int quic_acked_stream_data_offset(int64_t stream_id, size_t datalen);
504   int quic_stream_close(int64_t stream_id, uint64_t app_error_code);
505   int quic_stream_reset(int64_t stream_id, uint64_t app_error_code);
506   int quic_stream_stop_sending(int64_t stream_id, uint64_t app_error_code);
507   int quic_extend_max_local_streams();
508   int quic_extend_max_stream_data(int64_t stream_id);
509 
510   int quic_write_client_handshake(ngtcp2_encryption_level level,
511                                   const uint8_t *data, size_t datalen);
512   int quic_pkt_timeout();
513   void quic_restart_pkt_timer();
514   void quic_write_qlog(const void *data, size_t datalen);
515   int quic_make_http3_session();
516 #endif // ENABLE_HTTP3
517 };
518 
519 } // namespace h2load
520 
521 #endif // H2LOAD_H
522