From e58a9b4baf485810c4f561e95e7f589dde26cf9b Mon Sep 17 00:00:00 2001 From: Aurelien DARRAGON Date: Thu, 14 Sep 2023 11:35:27 +0200 Subject: [PATCH] MINOR: sink: add sink_new_from_srv() function This helper function can be used to create a new sink from an existing server struct (and thus existing proxy as well), in order to spare some resources when possible. --- include/haproxy/sink.h | 1 + src/sink.c | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/include/haproxy/sink.h b/include/haproxy/sink.h index e88208de8c..3b428a154f 100644 --- a/include/haproxy/sink.h +++ b/include/haproxy/sink.h @@ -84,6 +84,7 @@ static inline ssize_t sink_write(struct sink *sink, struct log_header hdr, return sent; } +struct sink *sink_new_from_srv(struct server *srv, const char *from); int sink_resolve_logger_buffer(struct logger *logger, char **msg); #endif /* _HAPROXY_SINK_H */ diff --git a/src/sink.c b/src/sink.c index ef9e3b1586..bb086e458d 100644 --- a/src/sink.c +++ b/src/sink.c @@ -1247,6 +1247,59 @@ struct sink *sink_new_from_logger(struct logger *logger) return NULL; } +/* This function is pretty similar to sink_from_logger(): + * But instead of creating a forward proxy and server from a logger struct + * it uses already existing srv to create the forwarding sink, so most of + * the initialization is bypassed. + * + * The function returns a pointer on the + * allocated struct sink if allocate + * and initialize succeed, else if it fails + * it returns NULL. + * + * allows to specify a string that will be inserted into the sink + * description to describe where it was created from. + + * Note: the sink is created using the name + * specified into srv->id + */ +struct sink *sink_new_from_srv(struct server *srv, const char *from) +{ + struct sink *sink = NULL; + + /* prepare description for the sink */ + chunk_reset(&trash); + chunk_printf(&trash, "created from %s declared into '%s' at line %d", from, srv->conf.file, srv->conf.line); + + /* directly create a sink of BUF type, and use UNSPEC log format to + * inherit from caller fmt in sink_write() + */ + sink = sink_new_buf(srv->id, trash.area, LOG_FORMAT_UNSPEC, BUFSIZE); + if (!sink) { + ha_alert("unable to create a new sink buffer for server '%s'.\n", srv->id); + goto error; + } + + /* we disable sink->maxlen to inherit from caller + * maxlen in sink_write() + */ + sink->maxlen = 0; + + /* add server to sink */ + if (!sink_add_srv(sink, srv)) + goto error; + + if (sink_finalize(sink) & ERR_CODE) + goto error; + + return sink; + + error: + sink_free(sink); + + return NULL; +} + /* * Post parsing "ring" section. * -- 2.39.5