1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #pragma once
17
18 #include <ostream>
19 #include <string>
20 #include <type_traits>
21 #include <unordered_map>
22 #include <unordered_set>
23 #include <vector>
24
25 #include <android-base/logging.h>
26 #include <fruit/fruit.h>
27
28 #include "common/libs/utils/result.h"
29 #include "common/libs/utils/type_name.h"
30
31 namespace cuttlefish {
32
33 template <typename Subclass>
34 class Feature {
35 public:
36 virtual ~Feature() = default;
37
38 virtual std::string Name() const = 0;
39
40 static Result<void> TopologicalVisit(
41 const std::unordered_set<Subclass*>& features,
42 const std::function<Result<void>(Subclass*)>& callback);
43
44 private:
45 virtual std::unordered_set<Subclass*> Dependencies() const = 0;
46 };
47
48 class SetupFeature : public virtual Feature<SetupFeature> {
49 public:
50 virtual ~SetupFeature();
51
52 static Result<void> RunSetup(const std::vector<SetupFeature*>& features);
53
54 virtual bool Enabled() const = 0;
55
56 private:
57 virtual Result<void> ResultSetup() = 0;
58 };
59
60 template <typename T>
61 class ReturningSetupFeature : public SetupFeature {
62 public:
ReturningSetupFeature()63 ReturningSetupFeature() {
64 if constexpr (std::is_void_v<T>) {
65 calculated_ = false;
66 } else {
67 calculated_ = {};
68 }
69 }
70 template <typename S = T>
71 std::enable_if_t<!std::is_void_v<S>, S&> operator*() {
72 CHECK(calculated_.has_value()) << "precondition violation";
73 return *calculated_;
74 }
75 template <typename S = T>
76 std::enable_if_t<!std::is_void_v<S>, const S&> operator*() const {
77 CHECK(calculated_.has_value()) << "precondition violation";
78 return *calculated_;
79 }
80 template <typename S = T>
81 std::enable_if_t<!std::is_void_v<S>, S*> operator->() {
82 CHECK(calculated_.has_value()) << "precondition violation";
83 return &*calculated_;
84 }
85 template <typename S = T>
86 std::enable_if_t<!std::is_void_v<S>, const S*> operator->() const {
87 CHECK(calculated_.has_value()) << "precondition violation";
88 return &*calculated_;
89 }
90 template <typename S = T>
Move()91 std::enable_if_t<!std::is_void_v<S>, S> Move() {
92 CHECK(calculated_.has_value()) << "precondition violation";
93 return std::move(*calculated_);
94 }
95
96 private:
ResultSetup()97 Result<void> ResultSetup() override final {
98 if constexpr (std::is_void_v<T>) {
99 CF_EXPECT(!calculated_, "precondition violation");
100 CF_EXPECT(Calculate());
101 calculated_ = true;
102 } else {
103 CF_EXPECT(!calculated_.has_value(), "precondition violation");
104 calculated_ = CF_EXPECT(Calculate());
105 }
106 return {};
107 }
108
109 virtual Result<T> Calculate() = 0;
110
111 std::conditional_t<std::is_void_v<T>, bool, std::optional<T>> calculated_;
112 };
113
114 class FlagFeature : public Feature<FlagFeature> {
115 public:
116 static Result<void> ProcessFlags(const std::vector<FlagFeature*>& features,
117 std::vector<std::string>& flags);
118 static bool WriteGflagsHelpXml(const std::vector<FlagFeature*>& features,
119 std::ostream& out);
120
121 private:
122 // Must be executed in dependency order following Dependencies(). Expected to
123 // mutate the `flags` argument to remove handled flags, and possibly introduce
124 // new flag values (e.g. from a file).
125 virtual Result<void> Process(std::vector<std::string>& flags) = 0;
126
127 // TODO(schuffelen): Migrate the xml help to human-readable help output after
128 // the gflags migration is done.
129
130 // Write an xml fragment that is compatible with gflags' `--helpxml` format.
131 virtual bool WriteGflagsCompatHelpXml(std::ostream& out) const = 0;
132 };
133
134 template <typename Subclass>
TopologicalVisit(const std::unordered_set<Subclass * > & features,const std::function<Result<void> (Subclass *)> & callback)135 Result<void> Feature<Subclass>::TopologicalVisit(
136 const std::unordered_set<Subclass*>& features,
137 const std::function<Result<void>(Subclass*)>& callback) {
138 enum class Status { UNVISITED, VISITING, VISITED };
139 std::unordered_map<Subclass*, Status> features_status;
140 for (const auto& feature : features) {
141 features_status[feature] = Status::UNVISITED;
142 }
143 std::function<Result<void>(Subclass*)> visit;
144 visit = [&callback, &features_status,
145 &visit](Subclass* feature) -> Result<void> {
146 CF_EXPECT(features_status.count(feature) > 0,
147 "Dependency edge to "
148 << feature->Name() << " but it is not part of the feature "
149 << "graph. This feature is either disabled or not correctly "
150 << "registered.");
151 if (features_status[feature] == Status::VISITED) {
152 return {};
153 }
154 CF_EXPECT(features_status[feature] != Status::VISITING,
155 "Cycle detected while visiting " << feature->Name());
156 features_status[feature] = Status::VISITING;
157 for (const auto& dependency : feature->Dependencies()) {
158 CF_EXPECT(dependency != nullptr,
159 "SetupFeature " << feature->Name() << " has a null dependency.");
160 CF_EXPECT(visit(dependency),
161 "Error detected while visiting " << feature->Name());
162 }
163 features_status[feature] = Status::VISITED;
164 CF_EXPECT(callback(feature), "Callback error on " << feature->Name());
165 return {};
166 };
167 for (const auto& feature : features) {
168 CF_EXPECT(visit(feature)); // `visit` will log the error chain.
169 }
170 return {};
171 }
172
173 template <typename... Args>
SetupFeatureDeps(const std::tuple<Args...> & args)174 std::unordered_set<SetupFeature*> SetupFeatureDeps(
175 const std::tuple<Args...>& args) {
176 std::unordered_set<SetupFeature*> deps;
177 std::apply(
178 [&deps](auto&&... arg) {
179 (
180 [&] {
181 using ArgType = std::remove_reference_t<decltype(arg)>;
182 if constexpr (std::is_base_of_v<SetupFeature, ArgType>) {
183 deps.insert(static_cast<SetupFeature*>(&arg));
184 }
185 }(),
186 ...);
187 },
188 args);
189 return deps;
190 }
191
192 template <auto Fn, typename R, typename... Args>
193 class GenericReturningSetupFeature : public ReturningSetupFeature<R> {
194 public:
INJECT(GenericReturningSetupFeature (Args...args))195 INJECT(GenericReturningSetupFeature(Args... args))
196 : args_(std::forward_as_tuple(args...)) {}
197
Enabled()198 bool Enabled() const override { return true; }
199
Name()200 std::string Name() const override {
201 static constexpr auto kName = ValueName<Fn>();
202 return std::string(kName);
203 }
204
Dependencies()205 std::unordered_set<SetupFeature*> Dependencies() const override {
206 return SetupFeatureDeps(args_);
207 }
208
209 private:
Calculate()210 Result<R> Calculate() override {
211 if constexpr (std::is_void_v<R>) {
212 CF_EXPECT(std::apply(Fn, args_));
213 return {};
214 } else {
215 return CF_EXPECT(std::apply(Fn, args_));
216 }
217 }
218 std::tuple<Args...> args_;
219 };
220
221 template <auto Fn1, typename Fn2>
222 struct GenericSetupImpl;
223
224 template <auto Fn, typename R, typename... Args>
225 struct GenericSetupImpl<Fn, Result<R> (*)(Args...)> {
226 using Type = GenericReturningSetupFeature<Fn, R, Args...>;
227
228 static fruit::Component<
229 fruit::Required<typename std::remove_reference_t<Args>...>, Type>
230 Component() {
231 return fruit::createComponent()
232 .template addMultibinding<SetupFeature, Type>();
233 }
234 };
235
236 template <auto Fn>
237 using AutoSetup = GenericSetupImpl<Fn, decltype(Fn)>;
238
239 } // namespace cuttlefish
240