Add facility to track total connections in use
[pazpar2-moved-to-github.git] / src / connection.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2010 Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 /** \file connection.c
21     \brief Z39.50 connection (low-level client)
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #if HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #include <signal.h>
39 #include <assert.h>
40
41 #include <yaz/log.h>
42 #include <yaz/comstack.h>
43 #include <yaz/tcpip.h>
44 #include "connection.h"
45 #include "session.h"
46 #include "host.h"
47 #include "client.h"
48 #include "settings.h"
49
50 /* connection counting (1) , disable connection counting (0) */
51 #if 0
52 static YAZ_MUTEX g_mutex = 0;
53 static int no_connections = 0;
54
55 static void connection_use(int delta)
56 {
57     if (!g_mutex)
58         yaz_mutex_create(&g_mutex);
59     yaz_mutex_enter(g_mutex);
60     no_connections += delta;
61     yaz_mutex_leave(g_mutex);
62     yaz_log(YLOG_LOG, "%s connections=%d", delta > 0 ? "INC" : "DEC",
63             no_connections);
64 }
65 #else
66 #define connection_use(x)
67 #endif
68
69
70 /** \brief Represents a physical, reusable  connection to a remote Z39.50 host
71  */
72 struct connection {
73     IOCHAN iochan;
74     ZOOM_connection link;
75     struct host *host;
76     struct client *client;
77     char *zproxy;
78     enum {
79         Conn_Resolving,
80         Conn_Connecting,
81         Conn_Open
82     } state;
83     int operation_timeout;
84     int session_timeout;
85     struct connection *next; // next for same host or next in free list
86 };
87
88 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
89
90 static int connection_is_idle(struct connection *co)
91 {
92     ZOOM_connection link = co->link;
93     int event;
94
95     if (co->state != Conn_Open || !link)
96         return 0;
97
98     if (!ZOOM_connection_is_idle(link))
99         return 0;
100     event = ZOOM_connection_peek_event(link);
101     if (event == ZOOM_EVENT_NONE)
102         return 1;
103     else
104         return 0;
105 }
106
107 ZOOM_connection connection_get_link(struct connection *co)
108 {
109     return co->link;
110 }
111
112 static void remove_connection_from_host(struct connection *con)
113 {
114     struct connection **conp = &con->host->connections;
115     assert(con);
116     while (*conp)
117     {
118         if (*conp == con)
119         {
120             *conp = (*conp)->next;
121             break;
122         }
123         conp = &(*conp)->next;
124     }
125 }
126
127 // Close connection and recycle structure
128 static void connection_destroy(struct connection *co)
129 {
130     if (co->link)
131     {
132         ZOOM_connection_destroy(co->link);
133         iochan_destroy(co->iochan);
134     }
135     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
136
137     if (co->client)
138     {
139         client_disconnect(co->client);
140     }
141
142     remove_connection_from_host(co);
143     xfree(co->zproxy);
144     xfree(co);
145     connection_use(-1);
146 }
147
148 // Creates a new connection for client, associated with the host of 
149 // client's database
150 static struct connection *connection_create(struct client *cl,
151                                             int operation_timeout,
152                                             int session_timeout,
153                                             iochan_man_t iochan_man)
154 {
155     struct connection *co;
156     struct host *host = client_get_host(cl);
157
158     co = xmalloc(sizeof(*co));
159     co->host = host;
160
161     co->client = cl;
162     co->zproxy = 0;
163     client_set_connection(cl, co);
164     co->link = 0;
165     co->state = Conn_Resolving;
166     co->operation_timeout = operation_timeout;
167     co->session_timeout = session_timeout;
168     if (host->ipport)
169         connection_connect(co, iochan_man);
170
171     yaz_mutex_enter(host->mutex);
172     co->next = co->host->connections;
173     co->host->connections = co;
174     yaz_mutex_leave(host->mutex);
175
176     connection_use(1);
177     return co;
178 }
179
180 static void non_block_events(struct connection *co)
181 {
182     int got_records = 0;
183     IOCHAN iochan = co->iochan;
184     ZOOM_connection link = co->link;
185     while (1)
186     {
187         struct client *cl = co->client;
188         int ev;
189         int r = ZOOM_event_nonblock(1, &link);
190         if (!r)
191             break;
192         if (!cl)
193             continue;
194         ev = ZOOM_connection_last_event(link);
195         
196 #if 0
197         yaz_log(YLOG_LOG, "ZOOM_EVENT_%s", ZOOM_get_event_str(ev));
198 #endif
199         switch (ev) 
200         {
201         case ZOOM_EVENT_END:
202             {
203                 const char *error, *addinfo;
204                 int err;
205                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
206                 {
207                     yaz_log(YLOG_LOG, "Error %s from %s",
208                             error, client_get_url(cl));
209                 }
210                 iochan_settimeout(iochan, co->session_timeout);
211                 client_set_diagnostic(cl, err);
212                 client_set_state(cl, Client_Idle);
213             }
214             break;
215         case ZOOM_EVENT_SEND_DATA:
216             break;
217         case ZOOM_EVENT_RECV_DATA:
218             break;
219         case ZOOM_EVENT_UNKNOWN:
220             break;
221         case ZOOM_EVENT_SEND_APDU:
222             client_set_state(co->client, Client_Working);
223             iochan_settimeout(iochan, co->operation_timeout);
224             break;
225         case ZOOM_EVENT_RECV_APDU:
226             break;
227         case ZOOM_EVENT_CONNECT:
228             yaz_log(YLOG_LOG, "Connected to %s", client_get_url(cl));
229             co->state = Conn_Open;
230             break;
231         case ZOOM_EVENT_RECV_SEARCH:
232             client_search_response(cl);
233             break;
234         case ZOOM_EVENT_RECV_RECORD:
235             client_record_response(cl);
236             got_records = 1;
237             break;
238         default:
239             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
240                     ev, client_get_url(cl));
241         }
242     }
243     if (got_records)
244     {
245         struct client *cl = co->client;
246         if (cl)
247         {
248             client_got_records(cl);
249         }
250     }
251 }
252
253 void connection_continue(struct connection *co)
254 {
255     int r = ZOOM_connection_exec_task(co->link);
256     if (!r)
257         yaz_log(YLOG_WARN, "No task was executed for connection");
258 }
259
260 static void connection_handler(IOCHAN iochan, int event)
261 {
262     struct connection *co = iochan_getdata(iochan);
263     struct client *cl;
264     struct host *host = co->host;
265
266     yaz_mutex_enter(host->mutex);
267     cl = co->client;
268     if (!cl) 
269     {
270         /* no client associated with it.. We are probably getting
271            a closed connection from the target.. Or, perhaps, an unexpected
272            package.. We will just close the connection */
273         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
274         connection_destroy(co);
275         yaz_mutex_leave(host->mutex);
276     }
277     else if (event & EVENT_TIMEOUT)
278     {
279         if (co->state == Conn_Connecting)
280         {
281             yaz_log(YLOG_WARN,  "connect timeout %s", client_get_url(cl));
282
283             client_set_state(cl, Client_Error);
284             connection_destroy(co);
285         }
286         else if (client_get_state(co->client) == Client_Idle)
287         {
288             yaz_log(YLOG_LOG,  "idle timeout %s", client_get_url(cl));
289             connection_destroy(co);
290         }
291         else
292         {
293             yaz_log(YLOG_LOG,  "ignore timeout %s", client_get_url(cl));
294         }
295         yaz_mutex_leave(host->mutex);
296     }
297     else
298     {
299         yaz_mutex_leave(host->mutex);
300
301         client_lock(cl);
302         non_block_events(co);
303
304         ZOOM_connection_fire_event_socket(co->link, event);
305         
306         non_block_events(co);
307         client_unlock(cl);
308     }
309 }
310
311
312 // Disassociate connection from client
313 static void connection_release(struct connection *co)
314 {
315     struct client *cl = co->client;
316
317     if (!cl)
318         return;
319     client_set_connection(cl, 0);
320     co->client = 0;
321 }
322
323 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
324 {
325     struct connection *con;
326
327 start:
328     yaz_mutex_enter(host->mutex);
329     con = host->connections;
330     while (con)
331     {
332         if (con->state == Conn_Resolving)
333         {
334             if (!host->ipport) /* unresolved */
335             {
336                 yaz_mutex_leave(host->mutex);
337                 connection_destroy(con);
338                 goto start;
339                 /* start all over .. at some point it will be NULL */
340             }
341             else if (!con->client)
342             {
343                 yaz_mutex_leave(host->mutex);
344                 connection_destroy(con);
345                 /* start all over .. at some point it will be NULL */
346                 goto start;
347             }
348             else
349             {
350                 yaz_mutex_leave(host->mutex);
351                 connection_connect(con, iochan_man);
352                 client_start_search(con->client);
353                 goto start;
354             }
355         }
356         else
357         {
358             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
359             con = con->next;
360         }
361     }
362     yaz_mutex_leave(host->mutex);
363 }
364
365 static struct host *connection_get_host(struct connection *con)
366 {
367     return con->host;
368 }
369
370 // Callback for use by event loop
371 // We do this because ZOOM connections don't always have (the same) sockets
372 static int socketfun(IOCHAN c)
373 {
374     struct connection *co = iochan_getdata(c);
375     if (!co->link)
376         return -1;
377     return ZOOM_connection_get_socket(co->link);
378 }
379
380 // Because ZOOM always knows what events it is interested in; we may not
381 static int maskfun(IOCHAN c)
382 {
383     struct connection *co = iochan_getdata(c);
384     if (!co->link)
385         return 0;
386
387     // This is cheating a little, and assuming that eventl mask IDs are always
388     // the same as ZOOM-C's.
389     return ZOOM_connection_get_mask(co->link);
390 }
391
392 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
393 {
394     ZOOM_connection link = 0;
395     struct host *host = connection_get_host(con);
396     ZOOM_options zoptions = ZOOM_options_create();
397     const char *auth;
398     const char *charset;
399     const char *sru;
400     const char *sru_version = 0;
401
402     struct session_database *sdb = client_get_database(con->client);
403     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
404     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
405
406     assert(host->ipport);
407     assert(con);
408
409     ZOOM_options_set(zoptions, "async", "1");
410     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
411     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
412         
413     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
414         ZOOM_options_set(zoptions, "charset", charset);
415     
416     if (zproxy && *zproxy)
417     {
418         con->zproxy = xstrdup(zproxy);
419         ZOOM_options_set(zoptions, "proxy", zproxy);
420     }
421     if (apdulog && *apdulog)
422         ZOOM_options_set(zoptions, "apdulog", apdulog);
423
424     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
425         ZOOM_options_set(zoptions, "user", auth);
426     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
427         ZOOM_options_set(zoptions, "sru", sru);
428     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
429         && *sru_version)
430         ZOOM_options_set(zoptions, "sru_version", sru_version);
431
432     if (!(link = ZOOM_connection_create(zoptions)))
433     {
434         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
435         ZOOM_options_destroy(zoptions);
436         return -1;
437     }
438
439     if (sru && *sru)
440     {
441         char http_hostport[512];
442         strcpy(http_hostport, "http://");
443         strcat(http_hostport, host->hostport);
444         ZOOM_connection_connect(link, http_hostport, 0);
445     }
446     else
447         ZOOM_connection_connect(link, host->ipport, 0);
448     
449     con->link = link;
450     con->iochan = iochan_create(0, connection_handler, 0, "connection_socket");
451     con->state = Conn_Connecting;
452     iochan_settimeout(con->iochan, con->operation_timeout);
453     iochan_setdata(con->iochan, con);
454     iochan_setsocketfun(con->iochan, socketfun);
455     iochan_setmaskfun(con->iochan, maskfun);
456     iochan_add(iochan_man, con->iochan);
457
458     /* this fragment is bad DRY: from client_prep_connection */
459     client_set_state(con->client, Client_Connecting);
460     ZOOM_options_destroy(zoptions);
461     return 0;
462 }
463
464 // Ensure that client has a connection associated
465 int client_prep_connection(struct client *cl,
466                            int operation_timeout, int session_timeout,
467                            iochan_man_t iochan_man)
468 {
469     struct connection *co;
470     struct host *host = client_get_host(cl);
471     struct session_database *sdb = client_get_database(cl);
472     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
473
474     if (zproxy && zproxy[0] == '\0')
475         zproxy = 0;
476
477     if (!host)
478         return 0;
479
480     co = client_get_connection(cl);
481
482     yaz_log(YLOG_DEBUG, "Client prep %s", client_get_url(cl));
483
484     if (!co)
485     {
486         // See if someone else has an idle connection
487         // We should look at timestamps here to select the longest-idle connection
488         yaz_mutex_enter(host->mutex);
489         for (co = host->connections; co; co = co->next)
490             if (connection_is_idle(co) &&
491                 (!co->client || client_get_state(co->client) == Client_Idle) &&
492                 !strcmp(ZOOM_connection_option_get(co->link, "user"),
493                         session_setting_oneval(client_get_database(cl),
494                                                PZ_AUTHENTICATION)))
495             {
496                 if (zproxy == 0 && co->zproxy == 0)
497                     break;
498                 if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
499                     break;
500             }
501         if (co)
502         {
503             connection_release(co);
504             client_set_connection(cl, co);
505             co->client = cl;
506             /* ensure that connection is only assigned to this client
507                by marking the client non Idle */
508             client_set_state(cl, Client_Working);
509             yaz_mutex_leave(host->mutex);
510             co->operation_timeout = operation_timeout;
511             co->session_timeout = session_timeout;
512             /* tells ZOOM to reconnect if necessary. Disabled becuase
513                the ZOOM_connection_connect flushes the task queue */
514             ZOOM_connection_connect(co->link, 0, 0);
515         }
516         else
517         {
518             yaz_mutex_leave(host->mutex);
519             co = connection_create(cl, operation_timeout, session_timeout,
520                                    iochan_man);
521         }
522     }
523
524     if (co && co->link)
525         return 1;
526     else
527         return 0;
528 }
529
530 /*
531  * Local variables:
532  * c-basic-offset: 4
533  * c-file-style: "Stroustrup"
534  * indent-tabs-mode: nil
535  * End:
536  * vim: shiftwidth=4 tabstop=8 expandtab
537  */
538