Skip to content

Commit

Permalink
Wait up to 100 seconds for hostname lookup
Browse files Browse the repository at this point in the history
In case networking takes as long as a minute to come up, give hostname
lookup up to 100 seconds to complete. Give initial HTTP request up to 120
seconds _from when we started_ to succeed, so even if we spent all our
time waiting on DNS, we still give 20 more seconds for the HTTP server.
  • Loading branch information
bwarden authored and bryteise committed Oct 21, 2022
1 parent 1ac420e commit 69103d6
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions src/ucd-data-fetch.c
Original file line number Diff line number Diff line change
Expand Up @@ -266,22 +266,40 @@ int main(int argc, char *argv[]) {
server.sin_addr.s_addr = inet_addr(config[conf].ip);
server.sin_port = htons(config[conf].port);

struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 50000000;

/* Do we need to look up a hostname? */
if ((int) server.sin_addr.s_addr == -1) {
struct hostent *hp = gethostbyname(config[conf].ip);
if (!hp || hp->h_length <= 0) {
FAIL("gethostbyname()");
}
n = 0;
for (;;) {
struct hostent *hp = gethostbyname(config[conf].ip);
if (hp != NULL) {
if (hp->h_length > 0) {
/* Got it; use the resulting IP address */
server.sin_family = (short unsigned int) (hp->h_addrtype & 0xFFFF);
memcpy(&(server.sin_addr.s_addr), hp->h_addr, (size_t) hp->h_length);
break;
}
else {
fprintf(stderr, "gethostbyname(): empty response");
exit(EXIT_FAILURE);
}
}

/* Got it; use the resulting IP address */
server.sin_family = (short unsigned int) (hp->h_addrtype & 0xFFFF);
memcpy(&(server.sin_addr.s_addr), hp->h_addr, (size_t) hp->h_length);
if ((h_errno != TRY_AGAIN) && (h_errno != NO_RECOVERY)) {
herror("gethostbyname()");
exit(EXIT_FAILURE);
}
nanosleep(&ts, NULL);
if (++n > 2000) { /* 100 secs */
herror("gethostbyname()");
exit(EXIT_FAILURE);
}
}
}

struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 50000000;

for (;;) {
int r = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
if (r == 0) {
Expand All @@ -291,7 +309,7 @@ int main(int argc, char *argv[]) {
FAIL("connect()");
}
nanosleep(&ts, NULL);
if (++n > 200) { /* 10 secs */
if (++n > 2400) { /* 120 secs - any used up in gethostbyname */
FAIL("timeout in connect()");
}
}
Expand Down

0 comments on commit 69103d6

Please sign in to comment.