Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,56 @@ maximize the chances of your PR being merged.
[envoy-filter-example](https://github.com/envoyproxy/envoy-filter-example) (for example making a new
branch so that CI can pass) it is your responsibility to follow through with merging those
changes back to master once the CI dance is done.
* If your PR is a high risk change, the reviewer may ask that you runtime guard
it. See the section on runtime guarding below.


# Runtime guarding

Some high risk changes in Envoy are deemed worthy of runtime guarding. Instead of just replacing
old code with new code, both code paths are supported for between one Envoy release (if it is
guarded due to performance concerns) and a full deprecation cycle (if it is a high risk behavioral
change).

The canonican way to runtime guard a feature is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless canonicans are some sci-fi aliens that always speak canonically, I assume this is typo :)

```
if (Runtime::LoaderSingleton::getExisting() &&
Runtime::LoaderSingleton::getExisting()->snapshot()->runtimeFeatureEnabled("
envoy.reloadable_features.my_feature_name")) {
[new code path]
} else {
[old_code_path]
}
```
Runtime guarded features named with the "envoy.reloadable_features." prefix must be safe to flip
true or false on running Envoy instances. In some situations, for example the buffer rewrite in
[#5441](https://github.com/envoyproxy/envoy/pull/5441), it may make more sense to
latch the value in a member variable on class creation, for example:

```
bool use_new_code_path_ = Runtime::LoaderSingleton::getExisting() &&
Runtime::LoaderSingleton::getExisting()->snapshot()->runtimeFeatureEnabled(
"envoy.reloadable_features.my_feature_name"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth trying to make this a bit less verbose at the sites where it is used? There's a lot of boilerplate to get to runtimeFeatureEnabled.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah we could likely have a wrapper that internally loads the singleton and does the right thing if it doesn't exist.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely the right way to go.

Less clear, should we use this in tests? I was a bit bummed at the heavyweight work in TestEnvironment to be able to flag override - setting up all those fake components. With the helper if we want to have a friend test-only class in ConstSingleton we can skip all the static state and just muck with the const singleton directly. I think that might also work for integration tests, which would be pretty awesome.

That said, it's making our const-singleton non-const and I know how much the larger Envoy community loves hacks like that ;-)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about an approach like #6139 with some test class mixin that changes the singleton behavior? That seems like a really cleanly structured way to have a "mostly const" singleton that alters behavior only within a particular test.

```

Runtime guarded features may either set true (running the new code by default) in the initial PR,
after a testing interval, or during the next release cycle, at the PR author's and reviewing
maintainer's discretion. Generally all runtime guarded features will be set true when a
release is cut, and the old code path will be deprecated at that time. Runtime features
are set true by default by inclusion in
[source/common/runtime/runtime_features.h](https://github.com/envoyproxy/envoy/blob/master/source/common/runtime/runtime_features.h)

There are three options for testing new runtime features:

1. Create a per-test Runtime::LoaderSingleton as done in [DeprecatedFieldsTest.IndividualFieldDisallowedWithRuntimeOverride](https://github.com/envoyproxy/envoy/blob/master/test/common/protobuf/utility_test.cc)
2. Set up integration tests with custom runtime defaults as documented in the
[integration test README](https://github.com/envoyproxy/envoy/blob/master/test/integration/README.md)
3. Run a given unit test with the new runtime value explicitly set true as done
for [runtime_flag_override_test](https://github.com/envoyproxy/envoy/blob/master/test/common/runtime/BUILD)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it also worth specifically calling out parameterized tests as a useful tool here? I find that particularly useful when the logical behavior is supposed to be the same regardless of flag value (ie, goal is pure refactoring or performance improvement).


Runtime code is held to the same standard as regular Envoy code, so both the old
path and the new should have 100% coverage both with the feature defaulting true
and false.

# PR review policy for maintainers

Expand Down
7 changes: 7 additions & 0 deletions include/envoy/runtime/runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ class Snapshot {
// configuration of "false" in runtime config.
virtual bool deprecatedFeatureEnabled(const std::string& key) const PURE;

// Returns true if a runtime feature is enabled.
//
// Runtime features are used to easily allow switching between old and new code paths for high
// risk changes. The intent is for the old code path to be short lived - the old code path is
// deprecated as the feature is defaulted true, and removed with the following Envoy release.
virtual bool runtimeFeatureEnabled(const std::string& key) const PURE;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use absl::string_view? It will avoid constructing std::string when caller call this with literals. but might require underlying methods take string_view.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As written I think someone could
static std::string feature = "envoy.reloadable_features.my_feature_name"));
if (Runtime::runtimeFeatureEnabled(feature) { ...} and avoid the string conversion on hash map lookup each time.

If they do the inefficient
if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.my_feature_name")
they're creating a string every time.

If I switch to string_view I think the map lookup will convert the string piece to the string on every single call, and there's no way to avoid it, so I think that's strictly less performant?

I could update the instructions to encourage static string on the canonical non-latch path if we think that makes more sense

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As long as it is an absl::flat_hash_{map,set} I think heterogenous lookup means that there is no string construction in the map lookup, even though the type in the map is std::string: https://abseil.io/tips/144

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL! Ok, got that to work for the flat hash, but unfortunately to string_view all the way up the API we need to also change Runtime::EntryMap in include/envoy/runtime/runtime.h to have a comparator. I'd prefer to land this as-is and do a separate PR converting to string piece, especially as none of the call sites will need to change. What do you think of a TODO and a follow-up?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah fine to leave as TODO. static std::string feature = "envoy.reloadable_features.my_feature_name"; is a static non-POD object initialization so there might be static initialization fiasco. string_view constructor is safe as it is constexpr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds fine to me.


/**
* Test if a feature is enabled using the built in random generator. This is done by generating
* a random number in the range 0-99 and seeing if this number is < the value stored in the
Expand Down
2 changes: 1 addition & 1 deletion source/common/protobuf/utility.h
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ class MessageUtil {
* @param message message to validate.
* @param loader optional a pointer to the runtime loader for live deprecation status.
* @throw ProtoValidationException if deprecated fields are used and listed
* Runtime::DisallowedFeatures
* in disallowed_features in runtime_features.h
*/
static void
checkForDeprecation(const Protobuf::Message& message,
Expand Down
34 changes: 31 additions & 3 deletions source/common/runtime/runtime_features.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,57 @@
namespace Envoy {
namespace Runtime {

// Add additional features here to enable the new code paths by default.
//
// These features should not be overridden with run-time guards without a bug
// being filed on github as once high risk features are true by default, the
// old code path will be removed with the next release.
const char* runtime_features[] = {
// Enabled
"envoy.reloadable_features.test_feature_true",
// Disabled
// "envoy.reloadable_features.test_feature_false",
};

// TODO(alyssawilk) handle deprecation of reloadable_features. Ideally runtime
// override of a deprecated feature will log(warn) on runtime-load if not deprecated
// and hard-fail once it has been deprecated.
const char* disallowed_features[] = {
// Acts as both a test entry for deprecated.proto and a marker for the Envoy
// deprecation scripts.
"envoy.deprecated_features.deprecated.proto:is_deprecated_fatal",
};

class DisallowedFeatures {
class RuntimeFeatures {
public:
DisallowedFeatures() {
RuntimeFeatures() {
for (auto& feature : disallowed_features) {
disallowed_features_.insert(feature);
}
for (auto& feature : runtime_features) {
enabled_features_.insert(feature);
}
}

// This tracks proto configured features, to determine if a given deprecated
// feature is still allowed, or has been made fatal-by-default per the Envoy
// deprecation process.
bool disallowedByDefault(const std::string& feature) const {
return disallowed_features_.find(feature) != disallowed_features_.end();
}

// This tracks config-guarded code paths, to determine if a given
// runtime-guarded-code-path has the new code run by default or the old code.
bool enabledByDefault(const std::string& feature) const {
return enabled_features_.find(feature) != enabled_features_.end();
}

private:
absl::flat_hash_set<std::string> disallowed_features_;
absl::flat_hash_set<std::string> enabled_features_;
};

using DisallowedFeaturesDefaults = ConstSingleton<DisallowedFeatures>;
using RuntimeFeaturesDefaults = ConstSingleton<RuntimeFeatures>;

} // namespace Runtime
} // namespace Envoy
14 changes: 13 additions & 1 deletion source/common/runtime/runtime_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ bool SnapshotImpl::deprecatedFeatureEnabled(const std::string& key) const {
bool stored = getBoolean(key, allowed);
// If not, the default value is based on disallowedByDefault.
if (!stored) {
allowed = !DisallowedFeaturesDefaults::get().disallowedByDefault(key);
allowed = !RuntimeFeaturesDefaults::get().disallowedByDefault(key);
}

if (!allowed) {
Expand All @@ -165,6 +165,18 @@ bool SnapshotImpl::deprecatedFeatureEnabled(const std::string& key) const {
return true;
}

bool SnapshotImpl::runtimeFeatureEnabled(const std::string& key) const {
bool enabled = false;
// See if this value is explicitly set as a runtime boolean.
bool stored = getBoolean(key, enabled);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this can just be inlined in the if statement below?

// If not, the default value is based on runtime_features.
if (!stored) {
enabled = RuntimeFeaturesDefaults::get().enabledByDefault(key);
}

return enabled;
}

bool SnapshotImpl::featureEnabled(const std::string& key, uint64_t default_value,
uint64_t random_value, uint64_t num_buckets) const {
return random_value % num_buckets < std::min(getInteger(key, default_value), num_buckets);
Expand Down
1 change: 1 addition & 0 deletions source/common/runtime/runtime_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class SnapshotImpl : public Snapshot,

// Runtime::Snapshot
bool deprecatedFeatureEnabled(const std::string& key) const override;
bool runtimeFeatureEnabled(const std::string& key) const override;
bool featureEnabled(const std::string& key, uint64_t default_value, uint64_t random_value,
uint64_t num_buckets) const override;
bool featureEnabled(const std::string& key, uint64_t default_value) const override;
Expand Down
12 changes: 12 additions & 0 deletions test/common/runtime/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ envoy_cc_test(
],
)

envoy_cc_test(
name = "runtime_flag_override_test",
srcs = ["runtime_flag_override_test.cc"],
args = [
"--runtime-feature-override-for-tests=envoy.reloadable_features.test_feature_false",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, this seems like a generally useful feature for runtime configuration where people don't want to use the filesystem (CLI/gflags implementation like we discussed). Is it worth adding a TODO or opening a help wanted issue on that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, if possible can you rename envoy.reloadable_features.test_feature_false to something else? I found it pretty confusing to try to sort out the logic with the built in envoy.reloadable_features.test_feature_true. Maybe more comments would help also or just a different name like envoy.reloadable_features.injected_test_feature and envoy.reloadable_features.built_in_test_feature or something?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think other folks would use this? I thought from prior discussions you thought google was flag happy but most folks wanted to use the existing runtime.
I think if we're going to use it out of test we have to allow for feature=true,feature2=false which I can do pretty easily.

Not sure if removing test_feature_false helps - I've clarified the language in both tests to hopefully clarify things.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do think that Google is an outlier in using flags for this type of stuff, but I was just suggesting that this code might be generally useful to someone, so probably worth tracking somewhere in case it comes up again. I think it's totally fine to leave as test only code for now.

Thanks for all the comments, it's much easier to understand for me now.

],
coverage = False,
deps = [
"//source/common/runtime:runtime_lib",
],
)

envoy_cc_test(
name = "uuid_util_test",
srcs = ["uuid_util_test.cc"],
Expand Down
16 changes: 16 additions & 0 deletions test/common/runtime/runtime_flag_override_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include "common/runtime/runtime_impl.h"

#include "gmock/gmock.h"

namespace Envoy {
namespace Runtime {

// In the envoy_cc_test declaration, the flag is set
// "--runtime-feature-override-for-tests=envoy.reloadable_features.test_feature_false"
TEST(RuntimeFlagOverrideTest, OverridesWork) {
Snapshot& snapshot = Runtime::LoaderSingleton::getExisting()->snapshot();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const Snapshot& ?

EXPECT_EQ(true, snapshot.runtimeFeatureEnabled("envoy.reloadable_features.test_feature_false"));
}

} // namespace Runtime
} // namespace Envoy
4 changes: 4 additions & 0 deletions test/common/runtime/runtime_impl_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ TEST_F(DiskBackedLoaderImplTest, All) {
// File1 is not a boolean.
EXPECT_EQ(false, snapshot->getBoolean("file1", value));

// Feature defaults.
EXPECT_EQ(false, snapshot->runtimeFeatureEnabled("envoy.reloadable_features.test_feature_false"));
EXPECT_EQ(true, snapshot->runtimeFeatureEnabled("envoy.reloadable_features.test_feature_true"));

// Files with comments.
EXPECT_EQ(123UL, loader->snapshot().getInteger("file5", 1));
EXPECT_EQ("/home#about-us", loader->snapshot().get("file6"));
Expand Down
1 change: 1 addition & 0 deletions test/mocks/runtime/mocks.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class MockSnapshot : public Snapshot {
~MockSnapshot() override;

MOCK_CONST_METHOD1(deprecatedFeatureEnabled, bool(const std::string& key));
MOCK_CONST_METHOD1(runtimeFeatureEnabled, bool(const std::string& key));
MOCK_CONST_METHOD2(featureEnabled, bool(const std::string& key, uint64_t default_value));
MOCK_CONST_METHOD3(featureEnabled,
bool(const std::string& key, uint64_t default_value, uint64_t random_value));
Expand Down
1 change: 1 addition & 0 deletions test/test_common/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ envoy_cc_test_library(
"//source/common/json:json_loader_lib",
"//source/common/network:utility_lib",
"//source/server:options_lib",
"//test/mocks/server:server_mocks",
],
)

Expand Down
66 changes: 66 additions & 0 deletions test/test_common/environment.cc
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,71 @@
#include "common/common/compiler_requirements.h"
#include "common/common/logger.h"
#include "common/common/macros.h"
#include "common/runtime/runtime_impl.h"
#include "common/common/utility.h"

#include "server/options_impl.h"

#include "test/mocks/server/mocks.h"
#include "test/test_common/network_utility.h"

#include "absl/strings/match.h"
#include "test/test_common/test_base.h"
#include "spdlog/spdlog.h"

#include "tclap/CmdLine.h"

#include "gtest/gtest.h"
namespace Envoy {
namespace {

std::string findAndRemove(const std::regex& pattern, int& argc, char**& argv) {
std::smatch matched;
std::string return_value;
for (int i = 0; i < argc; ++i) {
if (return_value.empty()) {
std::string argument = std::string(argv[i]);
if (regex_search(argument, matched, pattern)) {
return_value = matched[1];
argc--;
}
}
if (!return_value.empty() && i < argc) {
argv[i] = argv[i + 1];
}
}
return return_value;
}

// This class is created iff a test is run with the special runtime override flag.
class RuntimeManagingListener : public ::testing::EmptyTestEventListener {
public:
RuntimeManagingListener(std::string& runtime_override) : runtime_override_(runtime_override) {}

// On each test start, create and register a runtime instance, with this specific feature set to
// true.
void OnTestStart(const ::testing::TestInfo&) override {
if (!runtime_override_.empty()) {
runtime_state_ = std::make_unique<RuntimeState>();
Runtime::LoaderSingleton::getExisting()->mergeValues({{runtime_override_, "true"}});
}
}

// As each test ends, clean up the singleton state.
void OnTestEnd(const ::testing::TestInfo&) override { runtime_state_.reset(); }

struct RuntimeState {
NiceMock<ThreadLocal::MockInstance> tls;
Stats::IsolatedStoreImpl store;
Runtime::MockRandomGenerator rand;
Runtime::ScopedLoaderSingleton loader{
Runtime::LoaderPtr{new Runtime::LoaderImpl(rand, store, tls)}};
};

std::unique_ptr<RuntimeState> runtime_state_;
std::string runtime_override_;
};

std::string makeTempDir(char* name_template) {
#ifdef WIN32
char* dirname = ::_mktemp(name_template);
Expand Down Expand Up @@ -129,6 +181,20 @@ std::string TestEnvironment::getCheckedEnvVar(const std::string& var) {
}

void TestEnvironment::initializeOptions(int argc, char** argv) {
// Before latching argv and argc, remove any runtime override flag.
// This allows doing test overrides of Envoy runtime features without adding
// test flags to the Envoy production command line.
const std::regex PATTERN{"--runtime-feature-override-for-tests=(.*)", std::regex::optimize};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a probably stupid question: Is there any reason we couldn't just hit this directly from a test given that we already have static support and also have some work that @jmarantz did to clean things up at the end of tests? I'm just wondering if we could avoid some of the regex/listener/etc. magic here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, now that I did the const-singleton refactor this is much less tied to environment.cc than it was.

I'd be inclined to forklift all this code over to TestRunner::RunTests - we still need the regex magic and I'd prefer a separate listener just to avoid the set up and teardown checks for the vast majority of tests which don't need them.

I'm going to hold off until we've decided what to do with command line flags - if we want to make it general purpose I'd be inclined to leave it here with the TODO, and the move it into the main server TCLAP in the follow-up.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think my feeling is to not making it general purpose for now, and just track somewhere in a TODO/issue/etc. that we might want to think about this in the future. So in that case, I guess I would opt for making the test code as simple as possible so maybe do the move you suggested? Though if we do a move, why do we need all the regex stuff? Couldn't we just hit a static method with a string to alter runtime state for a test?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, we can do this statically from test, but in-house when introducing a high risk flag we often just dup a full test (or tests) with no edits, so we have one variant running with true and the other running with the flag false. We've found it pretty handy especially for tests which are already parameterized so hard to muck with.

It's not a lot of code so I'd be inclined to check it in and we can always remove it if no one uses it and it turns out to be overkill. WDYT?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a strong opinion on this one way or the other, but couldn't we accomplish roughly the same thing with a TEST_P and some type of param helper that just toggles a specific string? I think @dnoe mentioned this? I'm mainly just wondering if the same behavior can be achieved with less code?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can, but if a test is already a TEST_P it can mean updating all the test params from GetParam() to GetParam(0), adding GetParam(1) for every test fixture in the whole class, creating or editing the constructur etc, then tearing it all back down in a few months. Given many of our files have 3-5 fixtures this can end up being a lot of throwaway work per test you want to dual-dun, which is why we bother with the flag based solution internally.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK SGTM if you think this is the best option.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again it's really handy to have, but TDB if folks use it.
I've added a calendar reminder 6 months out to revisit - if no one uses it I'll tear these changes out then.

Any other comments you're waiting on?

std::string runtime_override = findAndRemove(PATTERN, argc, argv);
if (!runtime_override.empty()) {
ENVOY_LOG_TO_LOGGER(Logger::Registry::getLog(Logger::Id::testing), info,
"Running with runtime feature override {}", runtime_override);
// Set up a listener which will create a global runtime and set the feature
// to true for the duration of each test instance.
::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Append(new RuntimeManagingListener(runtime_override));
}

argc_ = argc;
argv_ = argv;
}
Expand Down