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