@@ -52,6 +52,16 @@ static int matches_vhost(const struct ns_str *host, const char *vhost) {
52
52
return host -> len == vhost_len && memcmp (host -> p , vhost , vhost_len ) == 0 ;
53
53
}
54
54
55
+ static void write_log (const char * fmt , ...) {
56
+ va_list ap ;
57
+ if (s_log_file != NULL ) {
58
+ va_start (ap , fmt );
59
+ vfprintf (s_log_file , fmt , ap );
60
+ fflush (s_log_file );
61
+ va_end (ap );
62
+ }
63
+ }
64
+
55
65
/*
56
66
* choose_backend parses incoming HTTP request and routes it to the appropriate
57
67
* backend. It assumes that clients don't do HTTP pipelining, handling only
@@ -88,18 +98,17 @@ static void choose_backend(struct ns_connection *nc) {
88
98
/* Prefer most specific URI prefixes */
89
99
strlen (s_http_backends [i ].uri_prefix ) >
90
100
strlen (s_http_backends [chosen ].uri_prefix ) ||
91
- /* Prefer least used backends */
92
- s_http_backends [i ].usage_counter <
93
- s_http_backends [chosen ].usage_counter )) {
101
+ /* Among prefixes of the same length chose the least used. */
102
+ (strlen (s_http_backends [i ].uri_prefix ) ==
103
+ strlen (s_http_backends [chosen ].uri_prefix ) &&
104
+ s_http_backends [i ].usage_counter <
105
+ s_http_backends [chosen ].usage_counter ))) {
94
106
chosen = i ;
95
107
}
96
108
}
97
109
98
- if (s_log_file != NULL ) {
99
- fprintf (s_log_file , "%.*s %.*s backend=%d\n" , (int ) hm .method .len ,
100
- hm .method .p , (int ) hm .uri .len , hm .uri .p , chosen );
101
- fflush (s_log_file );
102
- }
110
+ write_log ("%.*s %.*s backend=%d\n" , (int ) hm .method .len , hm .method .p ,
111
+ (int ) hm .uri .len , hm .uri .p , chosen );
103
112
104
113
if (chosen == -1 ) {
105
114
/* No backend with given uri_prefix found, bail out */
@@ -113,6 +122,8 @@ static void choose_backend(struct ns_connection *nc) {
113
122
nc -> mgr , s_http_backends [chosen ].host_port , ev_handler )) ==
114
123
NULL ) {
115
124
/* Connection to backend failed */
125
+ write_log ("Connection to [%s] failed\n" ,
126
+ s_http_backends [chosen ].host_port );
116
127
ns_printf (nc , "%s%s%s\r\n" , s_error_500 , s_content_len_0 ,
117
128
s_connection_close );
118
129
} else {
@@ -206,8 +217,8 @@ static void ev_handler(struct ns_connection *nc, int ev, void *ev_data) {
206
217
case NS_CONNECT :
207
218
if (* (int * ) ev_data != 0 ) {
208
219
/* TODO(lsm): mark backend as defunct, try it later on */
209
- fprintf ( stderr , "connect(%s) failed\n" ,
210
- s_http_backends [(int ) nc -> user_data ].host_port );
220
+ write_log ( "connect(%s) failed\n" ,
221
+ s_http_backends [(int ) nc -> user_data ].host_port );
211
222
ns_printf (nc -> proto_data , "%s%s%s\r\n" , s_error_500 , s_content_len_0 ,
212
223
s_connection_close );
213
224
}
0 commit comments