From 7a62cf9950a6bf6318cb177ba627d4d6ace82226 Mon Sep 17 00:00:00 2001 From: yaqiangz Date: Tue, 19 Dec 2023 02:59:13 +0000 Subject: [PATCH] [counter] Clear counter table when init --- src/relay.cpp | 21 ++++++++++++++++++++- src/relay.h | 10 ++++++++++ test/mock_relay.cpp | 11 +++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/relay.cpp b/src/relay.cpp index eccb62e..105d2d0 100644 --- a/src/relay.cpp +++ b/src/relay.cpp @@ -322,7 +322,6 @@ void initialize_counter(std::shared_ptr state_db, std::string std::string table_name = counter_table + ifname; auto init_value = gen_counter_json_str(DHCPv6_MESSAGE_TYPE_UNKNOWN, 0); - state_db->del(table_name); state_db->hset(table_name, "RX", init_value); state_db->hset(table_name, "TX", init_value); } @@ -1484,6 +1483,24 @@ void prepare_socket_callback(event_base *base, int socket, void (*cb)(evutil_soc event_add(event, NULL); } +/** + * @code clear_counter(std::shared_ptr state_db); + * + * @brief Clear all counter + * + * @param state_db state_db connector pointer + * + */ +void clear_counter(std::shared_ptr state_db) { + std::string match_pattern = counter_table + std::string("*"); + auto keys = state_db->keys(match_pattern); + + for (auto &itr : keys) { + state_db->del(itr); + } + syslog(LOG_INFO, "Counter cleared\n"); +} + /** * @code loop_relay(std::unordered_map &vlans); * @@ -1513,6 +1530,8 @@ void loop_relay(std::unordered_map &vlans) { prepare_socket_callback(base, out_filter, outbound_callback, reinterpret_cast(state_db.get())); sockets.push_back(out_filter); + clear_counter(state_db); + int lo_sock = -1; if (dual_tor_sock) { std::string lo_string(loopback); diff --git a/src/relay.h b/src/relay.h index 4b06ca8..29fffb5 100644 --- a/src/relay.h +++ b/src/relay.h @@ -559,3 +559,13 @@ void packet_counting_handler(uint8_t *buffer, ssize_t length, std::string &ifnam * */ void prepare_socket_callback(event_base *base, int socket, void (*cb)(evutil_socket_t, short, void *), void *arg); + +/** + * @code clear_counter(std::shared_ptr state_db); + * + * @brief Clear all counter + * + * @param state_db state_db connector pointer + * + */ +void clear_counter(std::shared_ptr state_db); diff --git a/test/mock_relay.cpp b/test/mock_relay.cpp index 91f50ea..68195c1 100644 --- a/test/mock_relay.cpp +++ b/test/mock_relay.cpp @@ -325,6 +325,17 @@ TEST(counter, initialize_counter) EXPECT_TRUE(state_db->hexists("DHCPv6_COUNTER_TABLE|Vlan1000", "TX")); } +TEST(counter, clear_counter) +{ + std::shared_ptr state_db = std::make_shared ("STATE_DB", 0); + std::string ifname = "Vlan1000"; + initialize_counter(state_db, ifname); + EXPECT_TRUE(state_db->hexists("DHCPv6_COUNTER_TABLE|Vlan1000", "RX")); + EXPECT_TRUE(state_db->hexists("DHCPv6_COUNTER_TABLE|Vlan1000", "TX")); + clear_counter(state_db); + EXPECT_FALSE(state_db->exists("DHCPv6_COUNTER_TABLE|Vlan1000")); +} + TEST(counter, increase_counter) { std::shared_ptr state_db = std::make_shared ("STATE_DB", 0);