ywkaras commented on a change in pull request #6455: URL: https://github.com/apache/trafficserver/pull/6455#discussion_r569009935
########## File path: plugins/regex_revalidate/regex_revalidate.cc ########## @@ -0,0 +1,729 @@ +/** @file + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include "ts/ts.h" +#include "ts/remap.h" +#include "ts/experimental.h" +#include "regex.h" + +#include <cinttypes> +#include <cstring> +#include <ctime> +#include <getopt.h> +#include <limits.h> +#include <sys/types.h> +#include <sys/stat.h> + +#include <algorithm> +#include <iostream> +#include <map> +#include <memory> +#include <set> +#include <string> +#include <string_view> +#include <vector> + +#ifdef HAVE_PCRE_PCRE_H +#include <pcre/pcre.h> +#else +#include <pcre.h> +#endif + +namespace +{ +constexpr char const *const PLUGIN_NAME = "regex_revalidate"; +constexpr char const *const RELOAD_TAG = "config_reload"; +constexpr char const *const PRINT_TAG = "config_print"; + +#define DEBUG_LOG(fmt, ...) TSDebug(PLUGIN_NAME, "%s:%d " fmt, __func__, __LINE__, ##__VA_ARGS__) + +#define ERROR_LOG(fmt, ...) \ + TSError("(%s) " fmt, PLUGIN_NAME, ##__VA_ARGS__); \ + DEBUG_LOG(fmt, ##__VA_ARGS__) + +constexpr TSHRTime const CONFIG_TMOUT = 60000; // ms, 60s +// constexpr TSHRTime const CONFIG_TMOUT = 5000; // ms, 5 +constexpr int const OVECTOR_SIZE = 30; +constexpr int const LOG_ROLL_INTERVAL = 86400; +constexpr int const LOG_ROLL_OFFSET = 0; + +TSCont config_cont{nullptr}; +Regex config_re; + +void * +ts_malloc(size_t s) +{ + return TSmalloc(s); +} + +void +ts_free(void *s) +{ + return TSfree(s); +} + +struct Invalidate { + std::string regex_text{}; + Regex regex{}; + time_t epoch{0}; + time_t expiry{0}; + + Invalidate() = default; + + Invalidate(Invalidate const &orig) + { + regex_text = orig.regex_text; + epoch = orig.epoch; + expiry = orig.expiry; + regex.compile(regex_text.c_str()); + } + + Invalidate(Invalidate &&orig) = default; + Invalidate &operator=(Invalidate &&rhs) = default; + + Invalidate & + operator=(Invalidate const &rhs) + { + if (&rhs != this) { + regex_text = rhs.regex_text; + epoch = rhs.epoch; + expiry = rhs.expiry; + regex.compile(regex_text.c_str()); + } + return *this; + } + + ~Invalidate() = default; + + inline bool + is_valid() const + { + return regex.is_valid(); + } + + inline bool + matches(char const *const url, int const url_len) const + { + return regex.matches(std::string_view{url, (unsigned)url_len}); + } + + static Invalidate fromLine(time_t const epoch, Regex const &config_re, char *const line); +}; + +struct PluginState { + std::string config_file{}; + std::shared_ptr<std::vector<Invalidate>> invalidate_vec; + bool timed_reload{true}; + time_t config_file_mtime{0}; + time_t min_expiry{0}; + TSTextLogObject log{nullptr}; + + ~PluginState() + { + if (nullptr != log) { + TSTextLogObjectDestroy(log); + } + } + + bool fromArgs(int argc, char const **argv); + bool loadConfig(time_t const timenow, std::vector<Invalidate> *const newrules) const; + + void printConfig() const; + void logConfig() const; +}; + +Invalidate +Invalidate::fromLine(time_t const epoch, Regex const &config_re, char *const line) +{ + Invalidate rule; + + int ovector[OVECTOR_SIZE]; + DEBUG_LOG("'%s'", line); + int const rc = config_re.exec(line, ovector, OVECTOR_SIZE); + + if (3 == rc) { + int const regbeg = ovector[2]; + int const regend = ovector[3]; + + char const *const regstr = line + regbeg; + char const oldch = line[regend]; + line[regend] = '\0'; // temporarily inject null termination + + if (rule.regex.compile(regstr)) { + rule.regex_text = regstr; + rule.expiry = (time_t)atoll(line + ovector[4]); + rule.epoch = epoch; + } else { + DEBUG_LOG("Invalid regex in line: '%s'", regstr); + } + + // restore the line char* + line[regend] = oldch; + } + + return rule; +} + +void +get_time_now_str(char *const buf, size_t const buflen) +{ + TSHRTime const timenowusec = TShrtime(); + int64_t const timemsec = (int64_t)(timenowusec / 1000000); + time_t const timesec = (time_t)(timemsec / 1000); + int const ms = (int)(timemsec % 1000); + + struct tm tm; + gmtime_r(×ec, &tm); + size_t const dtlen = strftime(buf, buflen, "%b %e %H:%M:%S", &tm); + + // tack on the ms + snprintf(buf + dtlen, buflen - dtlen, ".%03d", ms); +} + +void +PluginState::printConfig() const +{ + char timebuf[64] = {'\0'}; + get_time_now_str(timebuf, sizeof(timebuf)); + + fprintf(stderr, "[%s] %s config file: %s\n", timebuf, PLUGIN_NAME, config_file.c_str()); + + if (invalidate_vec) { + for (Invalidate const &iv : *invalidate_vec) { + fprintf(stderr, "[%s] %s line: '%s' epoch: %ju expiry: %ju\n", timebuf, PLUGIN_NAME, iv.regex_text.c_str(), + (uintmax_t)iv.epoch, (uintmax_t)iv.expiry); + } + } else { + fprintf(stderr, "[%s] %s config: EMPTY\n", timebuf, PLUGIN_NAME); + } + + fflush(stderr); +} + +void +PluginState::logConfig() const +{ + TSDebug(PLUGIN_NAME, "Current config: %s", config_file.c_str()); + if (nullptr != log) { + TSTextLogObjectWrite(log, "Current config: %s", config_file.c_str()); + } + + if (invalidate_vec) { + for (Invalidate const &iv : *invalidate_vec) { + TSDebug(PLUGIN_NAME, "line: '%s' epoch: %ju expiry: %ju", iv.regex_text.c_str(), (uintmax_t)iv.epoch, (uintmax_t)iv.expiry); + if (nullptr != log) { + TSTextLogObjectWrite(log, "line: '%s' epoch: %ju expiry: %ju", iv.regex_text.c_str(), (uintmax_t)iv.epoch, + (uintmax_t)iv.expiry); + } + } + } else { + TSDebug(PLUGIN_NAME, "Configuration EMPTY"); + if (nullptr != log) { + TSTextLogObjectWrite(log, "EMPTY"); + } + } +} + +bool +PluginState::fromArgs(int argc, char const **argv) +{ + int c; + constexpr option const longopts[] = { + {"config", required_argument, nullptr, 'c'}, + {"disable-timed-reload", no_argument, nullptr, 'd'}, + {"log", required_argument, nullptr, 'l'}, + {nullptr, 0, nullptr, 0}, + }; + + while ((c = getopt_long(argc, (char *const *)argv, "c:l:d", longopts, nullptr)) != -1) { + switch (c) { + case 'c': + config_file = optarg; + + // path is relative to config dir + if ('/' != config_file[0]) { + config_file = std::string(TSConfigDirGet()) + "/" + config_file; + } + + DEBUG_LOG("Config File: %s", config_file.c_str()); + break; + case 'l': + if (TS_SUCCESS == TSTextLogObjectCreate(optarg, TS_LOG_MODE_ADD_TIMESTAMP, &log)) { + TSTextLogObjectRollingEnabledSet(log, 1); + TSTextLogObjectRollingIntervalSecSet(log, LOG_ROLL_INTERVAL); + TSTextLogObjectRollingOffsetHrSet(log, LOG_ROLL_OFFSET); + DEBUG_LOG("Logging Mode enabled"); + } + break; + case 'd': + timed_reload = false; + DEBUG_LOG("Timed reload disabled (disable-timed-reload)"); + break; + default: + break; + } + } + + if (config_file.empty()) { + ERROR_LOG("Plugin requires a --config option along with a config file name"); + return false; + } + + return true; +} + +time_t +timeForFile(std::string const &filepath) +{ + time_t mtime{0}; + struct stat fstat; + if (0 == stat(filepath.c_str(), &fstat)) { + mtime = fstat.st_mtime; + } else { + DEBUG_LOG("Could not stat %s", filepath.c_str()); + } + return mtime; +} + +// load config, true if rules changed +bool +PluginState::loadConfig(time_t const timenow, std::vector<Invalidate> *const rules) const +{ + TSAssert(nullptr != rules); + + FILE *const fs = fopen(config_file.c_str(), "r"); + if (nullptr == fs) { + DEBUG_LOG("Could not open %s for reading", config_file.c_str()); + return false; + } + + // load from file + std::vector<Invalidate> loaded; + int lineno = 0; + char line[LINE_MAX]; + while (nullptr != fgets(line, LINE_MAX, fs)) { + ++lineno; + line[strcspn(line, "\r\n")] = '\0'; + if (0 < strlen(line) && '#' != line[0]) { + Invalidate rnew = Invalidate::fromLine(timenow, config_re, line); + if (rnew.is_valid()) { + loaded.push_back(std::move(rnew)); + } else { + DEBUG_LOG("Invalid rule '%s' from line: '%d'", line, lineno); + } + } + } + + fclose(fs); + + if (loaded.empty()) { + DEBUG_LOG("No rules loaded from file '%s'", config_file.c_str()); + return false; + } + + // stable sort to make clearing duplicates easy + std::stable_sort(loaded.begin(), loaded.end(), + [](Invalidate const &lhs, Invalidate const &rhs) { return lhs.regex_text < rhs.regex_text; }); + + // sweep to clear duplicates, last one wins + for (size_t index = 0; index < (loaded.size() - 1); ++index) { Review comment: Why not a range-based for loop? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
