~ When file descriptors are exhausted, we might be better to try to * free an existing connection, rather than ignoring new ones. */
| 620 | /*~ When file descriptors are exhausted, we might be better to try to |
| 621 | * free an existing connection, rather than ignoring new ones. */ |
| 622 | void close_random_connection(struct daemon *daemon) |
| 623 | { |
| 624 | struct peer *peer, *best_peer = NULL; |
| 625 | size_t best_peer_score = PEER_SCORE_MAX + 1; |
| 626 | struct peer_htable_iter it; |
| 627 | struct connecting *c; |
| 628 | struct connecting_htable_iter cit; |
| 629 | bool closed_connect_attempt = false; |
| 630 | struct pending_in *pin; |
| 631 | |
| 632 | /* Cheapest to lose: the oldest incoming connection without init. */ |
| 633 | pin = list_top(&daemon->pending_in, struct pending_in, list); |
| 634 | if (pin) { |
| 635 | status_debug("due to stress, closing incoming connection from %s" |
| 636 | " which has not sent init", |
| 637 | fmt_wireaddr_internal(tmpctx, &pin->addr)); |
| 638 | io_close(pin->conn); |
| 639 | return; |
| 640 | } |
| 641 | |
| 642 | /* First, close all transient connection attempts in-flight */ |
| 643 | for (c = connecting_htable_first(daemon->connecting, &cit); |
| 644 | c; |
| 645 | c = connecting_htable_next(daemon->connecting, &cit)) { |
| 646 | if (important_id_htable_get(daemon->important_ids, &c->id)) |
| 647 | continue; |
| 648 | |
| 649 | /* This could be the one caller is trying right now */ |
| 650 | if (!c->conn) |
| 651 | continue; |
| 652 | |
| 653 | status_debug("due to stress, closing transient connect attempt to %s", |
| 654 | fmt_node_id(tmpctx, &c->id)); |
| 655 | /* This tells destructor why it was closed */ |
| 656 | errno = EMFILE; |
| 657 | tal_free(c); |
| 658 | closed_connect_attempt = true; |
| 659 | } |
| 660 | |
| 661 | /* Prefer ones with no subds (just chatting), or failing that, |
| 662 | * ones we didn't deliberately connect to. */ |
| 663 | peer = peer_htable_pick(daemon->peers, pseudorand_u64(), &it); |
| 664 | |
| 665 | for (size_t i = 0; i < peer_htable_count(daemon->peers); i++) { |
| 666 | size_t score = peer_score(daemon, &peer->id, peer->subds); |
| 667 | if (score < best_peer_score) { |
| 668 | best_peer = peer; |
| 669 | best_peer_score = score; |
| 670 | /* Don't continue if we can't improve! */ |
| 671 | if (best_peer_score == 0) |
| 672 | break; |
| 673 | } |
| 674 | peer = peer_htable_next(daemon->peers, &it); |
| 675 | if (!peer) |
| 676 | peer = peer_htable_first(daemon->peers, &it); |
| 677 | } |
| 678 | |
| 679 | if (!best_peer) |
no test coverage detected