summaryrefslogtreecommitdiff
path: root/profcollectd/libprofcollectd/scheduler.cpp
blob: 38bf19a49c028fa53eaf5a0a2b433bc1d321d4c3 (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
//
// Copyright (C) 2020 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.
//

#define LOG_TAG "profcollectd_scheduler"

#include "scheduler.h"

#include <fstream>
#include <variant>
#include <vector>

#include <android-base/logging.h>
#include <android-base/properties.h>

#include "compress.h"
#include "hwtrace_provider.h"
#include "json/json.h"
#include "json/writer.h"

// Default option values.
using config_t = std::pair<const char*, std::variant<const int, const char*>>;
static constexpr const config_t CONFIG_BUILD_FINGERPRINT = {"Fingerprint", "unknown"};
static constexpr const config_t CONFIG_COLLECTION_INTERVAL_SEC = {"CollectionInterval", 600};
static constexpr const config_t CONFIG_SAMPLING_PERIOD_MS = {"SamplingPeriod", 500};
static constexpr const config_t CONFIG_TRACE_OUTDIR = {"TraceDir", "/data/misc/profcollectd/trace"};
static constexpr const config_t CONFIG_PROFILE_OUTDIR = {"ProfileDir",
                                                         "/data/misc/profcollectd/output"};
static constexpr const config_t CONFIG_BINARY_FILTER = {"BinaryFilter", ""};

namespace android {
namespace profcollectd {

namespace fs = std::filesystem;
using ::android::base::GetIntProperty;
using ::android::base::GetProperty;

// Hwtrace provider registry
extern std::unique_ptr<HwtraceProvider> REGISTER_SIMPLEPERF_ETM_PROVIDER();

namespace {

void ClearDir(const fs::path& path) {
  if (fs::exists(path)) {
    for (const auto& entry : fs::directory_iterator(path)) {
      fs::remove_all(entry);
    }
  }
}

bool ClearOnConfigChange(const ProfcollectdScheduler::Config& config) {
  const fs::path configFile = config.profileOutputDir / "config.json";
  ProfcollectdScheduler::Config oldConfig{};

  // Read old config, if exists.
  if (fs::exists(configFile)) {
    std::ifstream ifs(configFile);
    ifs >> oldConfig;
  }

  if (oldConfig != config) {
    LOG(INFO) << "Clearing profiles due to config change.";
    ClearDir(config.traceOutputDir);
    ClearDir(config.profileOutputDir);

    // Write new config.
    std::ofstream ofs(configFile);
    ofs << config;
    return true;
  }
  return false;
}

void PeriodicCollectionWorker(std::future<void> terminationSignal, ProfcollectdScheduler& scheduler,
                              std::chrono::seconds& interval) {
  do {
    scheduler.TraceOnce();
  } while ((terminationSignal.wait_for(interval)) == std::future_status::timeout);
}

}  // namespace

ProfcollectdScheduler::ProfcollectdScheduler() {
  ReadConfig();

  // Load a registered hardware trace provider.
  if ((hwtracer = REGISTER_SIMPLEPERF_ETM_PROVIDER())) {
    LOG(INFO) << "ETM provider registered.";
    return;
  } else {
    LOG(ERROR) << "No hardware trace provider found for this architecture.";
    exit(EXIT_FAILURE);
  }
}

OptError ProfcollectdScheduler::ReadConfig() {
  if (workerThread != nullptr) {
    static std::string errmsg = "Terminate the collection before refreshing config.";
    return errmsg;
  }

  const std::lock_guard<std::mutex> lock(mu);

  config.buildFingerprint = GetProperty("ro.build.fingerprint", "unknown");
  config.collectionInterval = std::chrono::seconds(
      GetIntProperty("profcollectd.collection_interval",
                     std::get<const int>(CONFIG_COLLECTION_INTERVAL_SEC.second)));
  config.samplingPeriod = std::chrono::milliseconds(GetIntProperty(
      "profcollectd.sampling_period_ms", std::get<const int>(CONFIG_SAMPLING_PERIOD_MS.second)));
  config.traceOutputDir = GetProperty("profcollectd.trace_output_dir",
                                      std::get<const char*>(CONFIG_TRACE_OUTDIR.second));
  config.profileOutputDir =
      GetProperty("profcollectd.output_dir", std::get<const char*>(CONFIG_PROFILE_OUTDIR.second));
  config.binaryFilter =
      GetProperty("profcollectd.binary_filter", std::get<const char*>(CONFIG_BINARY_FILTER.second));
  ClearOnConfigChange(config);

  return std::nullopt;
}

OptError ProfcollectdScheduler::ScheduleCollection() {
  if (workerThread != nullptr) {
    static std::string errmsg = "Collection is already scheduled.";
    return errmsg;
  }

  workerThread =
      std::make_unique<std::thread>(PeriodicCollectionWorker, terminate.get_future(),
                                    std::ref(*this), std::ref(config.collectionInterval));
  return std::nullopt;
}

OptError ProfcollectdScheduler::TerminateCollection() {
  if (workerThread == nullptr) {
    static std::string errmsg = "Collection is not scheduled.";
    return errmsg;
  }

  terminate.set_value();
  workerThread->join();
  workerThread = nullptr;
  terminate = std::promise<void>();  // Reset promise.
  return std::nullopt;
}

OptError ProfcollectdScheduler::TraceOnce() {
  const std::lock_guard<std::mutex> lock(mu);
  bool success = hwtracer->Trace(config.traceOutputDir, config.samplingPeriod);
  if (!success) {
    static std::string errmsg = "Trace failed";
    return errmsg;
  }
  return std::nullopt;
}

OptError ProfcollectdScheduler::ProcessProfile() {
  const std::lock_guard<std::mutex> lock(mu);
  hwtracer->Process(config.traceOutputDir, config.profileOutputDir, config.binaryFilter);
  std::vector<fs::path> profiles;
  profiles.insert(profiles.begin(), fs::directory_iterator(config.profileOutputDir),
                  fs::directory_iterator());
  bool success = CompressFiles("/sdcard/profile.zip", profiles);
  if (!success) {
    static std::string errmsg = "Compress files failed";
    return errmsg;
  }
  return std::nullopt;
}

std::ostream& operator<<(std::ostream& os, const ProfcollectdScheduler::Config& config) {
  Json::Value root;
  const auto writer = std::make_unique<Json::StyledStreamWriter>();
  root[CONFIG_BUILD_FINGERPRINT.first] = config.buildFingerprint;
  root[CONFIG_COLLECTION_INTERVAL_SEC.first] = config.collectionInterval.count();
  root[CONFIG_SAMPLING_PERIOD_MS.first] = config.samplingPeriod.count();
  root[CONFIG_TRACE_OUTDIR.first] = config.traceOutputDir.c_str();
  root[CONFIG_PROFILE_OUTDIR.first] = config.profileOutputDir.c_str();
  root[CONFIG_BINARY_FILTER.first] = config.binaryFilter.c_str();
  writer->write(os, root);
  return os;
}

std::istream& operator>>(std::istream& is, ProfcollectdScheduler::Config& config) {
  Json::Value root;
  const auto reader = std::make_unique<Json::Reader>();
  bool success = reader->parse(is, root);
  if (!success) {
    return is;
  }

  config.buildFingerprint = root[CONFIG_BUILD_FINGERPRINT.first].asString();
  config.collectionInterval =
      std::chrono::seconds(root[CONFIG_COLLECTION_INTERVAL_SEC.first].asInt64());
  config.samplingPeriod =
      std::chrono::duration<float>(root[CONFIG_SAMPLING_PERIOD_MS.first].asFloat());
  config.traceOutputDir = root[CONFIG_TRACE_OUTDIR.first].asString();
  config.profileOutputDir = root[CONFIG_PROFILE_OUTDIR.first].asString();
  config.binaryFilter = root[CONFIG_BINARY_FILTER.first].asString();

  return is;
}

}  // namespace profcollectd
}  // namespace android