File: event_and_thread.pp

package info (click to toggle)
fpc 3.2.0%2Bdfsg-12
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, bullseye-backports
  • size: 338,552 kB
  • sloc: pascal: 3,794,737; xml: 191,997; ansic: 9,637; asm: 8,482; java: 5,346; sh: 4,664; yacc: 3,751; makefile: 2,688; lex: 2,538; javascript: 2,375; sql: 929; php: 473; cpp: 145; perl: 134; sed: 132; csh: 34; tcl: 7
file content (267 lines) | stat: -rw-r--r-- 6,542 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
(*

  @Example: `event_and_thread`.
  @Description: Use event-driven for usual requests and threads to slowly requests.
  @Authors: Silvio Clecio and Gilson Nunes

*)

program event_and_thread;

// Shows `event_and_thread` details on Linux:
//
//   $ ps axo pid,ppid,rss,vsz,nlwp,cmd | grep 'event_and_thread'
//
// But if you prefer to see only the number of thread of `event_and_thread`:
//
//   $ ps axo nlwp,cmd | grep 'event_and_thread'

{$mode objfpc}{$H+}
{$MACRO ON}
{$DEFINE DEBUG}
{.$DEFINE WAIT_CLIENTS_DISCONNECT}
{$DEFINE TIMEOUT := 10}
{.$DEFINE CONTINGENCY_CONTROL}
{$IF DEFINED(CONTINGENCY_CONTROL)}
  {$DEFINE MAX_THREAD_COUNT := 2}
{$ENDIF}

uses
{$IFDEF UNIX}
  cthreads, BaseUnix,
{$ELSE}
  Sockets,
{$ENDIF}
  Classes, SysUtils, cutils, libmicrohttpd;

  procedure MHD_socket_close(fd: cint);
  begin
{$IFDEF UNIX}
    FpClose(fd);
{$ELSE}
    CloseSocket(fd);
{$ENDIF}
  end;

const
  PORT = 8888;

var
  _threads: TFPList;
  _mutex: TRTLCriticalSection;

type

  { TConnectionHandler }

  TConnectionHandler = packed record
    Connection: PMHD_Connection;
    Url: Pcchar;
  end;

  { TSlothThread }

  TSlothThread = class(TThread)
  private
    FHandler: TConnectionHandler;
  protected
    procedure Execute; override;
  public
    constructor Create(AHandler: TConnectionHandler);
    destructor Destroy; override;
  end;

  { TSlothThread }

  constructor TSlothThread.Create(AHandler: TConnectionHandler);
  begin
    inherited Create(True);
    FreeOnTerminate := True;
    FHandler := AHandler;
  end;

  destructor TSlothThread.Destroy;
  begin
    _threads.Remove(Self);
    inherited Destroy;
  end;

  procedure TSlothThread.Execute;
  const
    page: AnsiString =
      '<html><body>I''m a sloth, and my URL is "%s". T: %s</body></html>';
  var
    i: Byte;
    s: AnsiString;
    response: PMHD_Response;
  begin
    for i := 1 to TIMEOUT do
    begin
      if Terminated then
        Break;
      Sleep(1000);
    end;
    if not Terminated then
    begin
      s := Format(page, [FHandler.Url, DateTimeToStr(Now)]);
      response := MHD_create_response_from_buffer(Length(s), Pointer(s),
        MHD_RESPMEM_MUST_COPY);
      MHD_queue_response(FHandler.Connection, MHD_HTTP_OK, response);
      MHD_resume_connection(FHandler.Connection);
      MHD_destroy_response(response);
    end;
  end;

  { daemon }

  function RequestHandler(cls: Pointer; connection: PMHD_Connection;
    url: Pcchar; method: Pcchar; version: Pcchar; upload_data: Pcchar;
    upload_data_size: Psize_t; ptr: PPointer): cint; cdecl;
  const
    page = '<html><body>Hello world! T: %s</body></html>';
{$IF DEFINED(CONTINGENCY_CONTROL)}
    busy_page: Pcchar = '<html><body>The server is busy. :-(</body></html>';
{$ENDIF}
  var
    s: string;
    ret: cint;
    thr: TThread;
    response: PMHD_Response;
    handler: TConnectionHandler;
  begin
    if method <> 'GET' then
      Exit(MHD_NO);

    { By Gilson Nunes:
      "The connection state for first call is `MHD_CONNECTION_HEADERS_PROCESSED`
       and `MHD_CONNECTION_FOOTERS_RECEIVED` for the next, so the flag below
       ensures that the response will be delivered to the client after `MHD`
       finish all the request processing." }
    if not Assigned(ptr^) then
    begin
      ptr^ := Pointer(1);
      Exit(MHD_YES);
    end;
    ptr^ := nil;

    if (strcomp(url, '/sloth1') = 0) or (strcomp(url, '/sloth2') = 0) then
    begin
{$IF DEFINED(CONTINGENCY_CONTROL)}
      if _threads.Count = MAX_THREAD_COUNT then
      begin
        response := MHD_create_response_from_buffer(Length(busy_page),
          busy_page, MHD_RESPMEM_PERSISTENT);
        ret := MHD_queue_response(connection, MHD_HTTP_OK, response);
        MHD_destroy_response(response);
        Exit(ret);
      end;
{$ENDIF}
      MHD_suspend_connection(connection);
      handler.Connection := connection;
      handler.Url := url;
      thr := TSlothThread.Create(handler);
      EnterCriticalsection(_mutex);
      try
        _threads.Add(thr);
      finally
        LeaveCriticalsection(_mutex);
      end;
      thr.Start;
      Result := MHD_YES;
    end
    else
    begin
      s := Format(page, [DateTimeToStr(Now)]);
      response := MHD_create_response_from_buffer(Length(s), Pointer(s),
        MHD_RESPMEM_MUST_COPY);
      ret := MHD_queue_response(connection, MHD_HTTP_OK, response);
      MHD_destroy_response(response);
      Result := ret;
    end;
  end;

var
  _daemon: PMHD_Daemon;

  procedure StopServer;
  var
    i: Integer;
    thr: TThread;
    sckt: MHD_socket;
    connections: PMHD_DaemonInfo;
  begin
    sckt := MHD_quiesce_daemon(_daemon);
{$IFDEF MSWINDOWS}
    if LongWord(sckt) <> MHD_INVALID_SOCKET then
{$ELSE}
    if sckt <> MHD_INVALID_SOCKET then
{$ENDIF}
      MHD_socket_close(sckt);
    EnterCriticalsection(_mutex);
    try
      WriteLn('Threads: ', _threads.Count);
      for i := Pred(_threads.Count) downto 0 do
      begin
        thr := TThread(_threads[i]);
        WriteLn('Finishing thread $', HexStr(thr), ' ...');
        if Assigned(thr) then
          thr.Terminate;
      end;
      while _threads.Count > 0 do
        Sleep(500);
    finally
      LeaveCriticalsection(_mutex);
    end;
    connections := MHD_get_daemon_info(_daemon, MHD_DAEMON_INFO_CURRENT_CONNECTIONS);
    if Assigned(connections) then
    begin
      WriteLn('Connections: ', connections^.num_connections);
{$IFDEF WAIT_CLIENTS_DISCONNECT}
      while True do
      begin
        if connections^.num_connections = 0 then
          Break;
        Sleep(500);
      end;
{$ENDIF}
    end;
    MHD_stop_daemon(_daemon);
    WriteLn('Bye!');
  end;

  procedure SigProc(sig: cint); cdecl;
  begin
    WriteLn;
    StopServer;
    FreeAndNil(_threads);
    Halt;
  end;

begin
  InitCriticalSection(_mutex);
  _threads := TFPList.Create;
  try
    _daemon := MHD_start_daemon(MHD_USE_SELECT_INTERNALLY or
      MHD_USE_SUSPEND_RESUME or MHD_USE_DEBUG,
      PORT, nil, nil, @RequestHandler, nil,
{$IF DEFINED(CONTINGENCY_CONTROL)}
      MHD_OPTION_THREAD_POOL_SIZE, cuint(MAX_THREAD_COUNT),
{$ENDIF}
      MHD_OPTION_CONNECTION_TIMEOUT, cuint(TIMEOUT + 1),
      MHD_OPTION_END);
    if not Assigned(_daemon) then
      Halt(1);
    signal(SIGINT, @SigProc);
{$IFDEF MSWINDOWS}
    signal(SIGBREAK, @SigProc);
{$ELSE}
    signal(SIGTERM, @SigProc);
{$ENDIF}
    WriteLn('HTTP server running. Press [Ctrl+C] to stop the server ...');
    while Assigned(_daemon) do
      Sleep(100);
  finally
    FreeAndNil(_threads);
    DoneCriticalsection(_mutex);
  end;
end.