aboutsummaryrefslogtreecommitdiff
path: root/host/libs/config/config_flag.cpp
blob: d1b9f191d4a3e8981bcd98bd09c495c4554f9303 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed 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 "host/libs/config/config_flag.h"

#include <android-base/logging.h>
#include <android-base/strings.h>
#include <gflags/gflags.h>
#include <json/json.h>
#include <fstream>
#include <set>
#include <string>

#include "common/libs/utils/files.h"
#include "common/libs/utils/flag_parser.h"
#include "host/commands/assemble_cvd/flags_defaults.h"
#include "host/libs/config/cuttlefish_config.h"

// To support other files that use this from gflags.
// TODO: Add a description to this flag
DEFINE_string(system_image_dir, CF_DEFAULTS_SYSTEM_IMAGE_DIR, "");

using gflags::FlagSettingMode::SET_FLAGS_DEFAULT;
using android::base::ReadFileToString;
using android::base::Split;

namespace cuttlefish {

namespace {

class SystemImageDirFlagImpl : public SystemImageDirFlag {
 public:
  INJECT(SystemImageDirFlagImpl()) {
    auto help = "Location of the system partition images.";
    flag_ = GflagsCompatFlag("system_image_dir", path_).Help(help);
  }
  const std::string& Path() override { return path_; }

  std::string Name() const override { return "SystemImageDirFlagImpl"; }
  std::unordered_set<FlagFeature*> Dependencies() const override { return {}; }
  bool Process(std::vector<std::string>& args) override {
    path_ = DefaultGuestImagePath("");
    if (!flag_.Parse(args)) {
      return false;
    }
    // To support other files that use this from gflags.
    FLAGS_system_image_dir = path_;
    gflags::SetCommandLineOptionWithMode("system_image_dir", path_.c_str(),
                                         SET_FLAGS_DEFAULT);
    return true;
  }
  bool WriteGflagsCompatHelpXml(std::ostream&) const override {
    // TODO(schuffelen): Write something here when this is removed from gflags
    return true;
  }

 private:
  std::string path_;
  Flag flag_;
};

class ConfigReader : public FlagFeature {
 public:
  INJECT(ConfigReader()) = default;

  bool HasConfig(const std::string& name) const {
    return allowed_config_presets_.count(name) > 0;
  }
  const std::set<std::string>& AvailableConfigs() const {
    return allowed_config_presets_;
  }
  std::optional<Json::Value> ReadConfig(const std::string& name) const {
    auto path =
        DefaultHostArtifactsPath("etc/cvd_config/cvd_config_" + name + ".json");
    Json::Value config;
    Json::CharReaderBuilder builder;
    std::ifstream ifs(path);
    std::string errorMessage;
    if (!Json::parseFromStream(builder, ifs, &config, &errorMessage)) {
      LOG(ERROR) << "Could not read config file " << path << ": "
                 << errorMessage;
      return {};
    }
    return config;
  }

  // FlagFeature
  std::string Name() const override { return "ConfigReader"; }
  std::unordered_set<FlagFeature*> Dependencies() const override { return {}; }
  bool Process(std::vector<std::string>&) override {
    auto directory_contents_result =
        DirectoryContents(DefaultHostArtifactsPath("etc/cvd_config"));
    CHECK(directory_contents_result.ok())
        << directory_contents_result.error().Message();
    for (const std::string& file : *directory_contents_result) {
      std::string_view local_file(file);
      if (android::base::ConsumePrefix(&local_file, "cvd_config_") &&
          android::base::ConsumeSuffix(&local_file, ".json")) {
        allowed_config_presets_.emplace(local_file);
      }
    }
    return true;
  }
  bool WriteGflagsCompatHelpXml(std::ostream&) const override { return true; }

 private:
  std::set<std::string> allowed_config_presets_;
};

class ConfigFlagImpl : public ConfigFlag {
 public:
  INJECT(ConfigFlagImpl(ConfigReader& cr, SystemImageDirFlag& s))
      : config_reader_(cr), system_image_dir_flag_(s) {
    is_default_ = true;
    config_ = "phone";  // default value
    auto help =
        "Config preset name. Will automatically set flag fields using the "
        "values from this file of presets. See "
        "device/google/cuttlefish/shared/config/config_*.json for possible "
        "values.";
    auto getter = [this]() { return config_; };
    auto setter = [this](const FlagMatch& m) { return ChooseConfig(m.value); };
    flag_ = GflagsCompatFlag("config").Help(help).Getter(getter).Setter(setter);
  }

  std::string Name() const override { return "ConfigFlagImpl"; }
  std::unordered_set<FlagFeature*> Dependencies() const override {
    return {
        static_cast<FlagFeature*>(&config_reader_),
        static_cast<FlagFeature*>(&system_image_dir_flag_),
    };
  }
  bool Process(std::vector<std::string>& args) override {
    if (!flag_.Parse(args)) {
      LOG(ERROR) << "Failed to parse `--config` flag";
      return false;
    }

    if (auto info_cfg = FindAndroidInfoConfig(); is_default_ && info_cfg) {
      config_ = *info_cfg;
    }
    LOG(INFO) << "Launching CVD using --config='" << config_ << "'.";
    auto config_values = config_reader_.ReadConfig(config_);
    if (!config_values) {
      LOG(ERROR) << "Failed to read config for " << config_;
      return false;
    }
    for (const std::string& flag : config_values->getMemberNames()) {
      std::string value;
      if (flag == "custom_actions") {
        Json::StreamWriterBuilder factory;
        value = Json::writeString(factory, (*config_values)[flag]);
      } else {
        value = (*config_values)[flag].asString();
      }
      args.insert(args.begin(), "--" + flag + "=" + value);
      // To avoid the flag forwarder from thinking this song is different from a
      // default. Should fail silently if the flag doesn't exist.
      gflags::SetCommandLineOptionWithMode(flag.c_str(), value.c_str(),
                                           SET_FLAGS_DEFAULT);
    }
    return true;
  }
  bool WriteGflagsCompatHelpXml(std::ostream& out) const override {
    return flag_.WriteGflagsCompatXml(out);
  }

 private:
  bool ChooseConfig(const std::string& name) {
    if (!config_reader_.HasConfig(name)) {
      LOG(ERROR) << "Invalid --config option '" << name << "'. Valid options: "
                 << android::base::Join(config_reader_.AvailableConfigs(), ",");
      return false;
    }
    config_ = name;
    is_default_ = false;
    return true;
  }
  std::optional<std::string> FindAndroidInfoConfig() const {
    auto info_path = system_image_dir_flag_.Path() + "/android-info.txt";
    if (!FileExists(info_path)) {
      return {};
    }
    std::string android_info;
    if(!ReadFileToString(info_path, &android_info)) {
      return {};
    }
    // grab the last value of config in android-info.txt,
    // it's the setting that's respected.
    // TODO (rammuthiah) Replace this logic with ParseMiscInfo
    // from host/commands/assemble_cvd/misc_info.h
    // Currently blocked on linking error for misc_info which is part of
    // assemble_cvd and this bit of code which is in run_cvd.
    size_t config_idx = android_info.rfind("config=");
    if (config_idx == std::string::npos) {
      return {};
    }
    std::string config_value = android_info.substr(config_idx);
    std::string_view local_config_value(config_value);
    if (!android::base::ConsumePrefix(&local_config_value, "config=")) {
      return {};
    }
    auto split_config = Split(std::string{local_config_value},"\n");
    if (split_config.empty()) {
      return {};
    }
    config_value = split_config[0];
    if (!config_reader_.HasConfig(config_value)) {
      LOG(WARNING) << info_path << " contains invalid config preset: '"
                   << config_value << "'.";
      return {};
    }
    return config_value;
  }

  ConfigReader& config_reader_;
  SystemImageDirFlag& system_image_dir_flag_;
  std::string config_;
  bool is_default_;
  Flag flag_;
};

class ConfigFlagPlaceholderImpl : public ConfigFlag {
 public:
  INJECT(ConfigFlagPlaceholderImpl()) {}

  std::string Name() const override { return "ConfigFlagPlaceholderImpl"; }
  std::unordered_set<FlagFeature*> Dependencies() const override { return {}; }
  bool Process(std::vector<std::string>&) override { return true; }
  bool WriteGflagsCompatHelpXml(std::ostream&) const override { return true; }
};

}  // namespace

fruit::Component<SystemImageDirFlag, ConfigFlag> ConfigFlagComponent() {
  return fruit::createComponent()
      .addMultibinding<FlagFeature, ConfigReader>()
      .bind<ConfigFlag, ConfigFlagImpl>()
      .addMultibinding<FlagFeature, ConfigFlag>()
      .bind<SystemImageDirFlag, SystemImageDirFlagImpl>()
      .addMultibinding<FlagFeature, SystemImageDirFlag>();
}

fruit::Component<ConfigFlag> ConfigFlagPlaceholder() {
  return fruit::createComponent()
      .addMultibinding<FlagFeature, ConfigFlag>()
      .bind<ConfigFlag, ConfigFlagPlaceholderImpl>();
}

}  // namespace cuttlefish