3 ** Copyright 2015, The Android Open Source Project
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
9 ** http://www.apache.org/licenses/LICENSE-2.0
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
27 #include <sys/types.h>
39 #include <android-base/file.h>
40 #include <android-base/logging.h>
41 #include <android-base/macros.h>
42 #include <android-base/properties.h>
43 #include <android-base/stringprintf.h>
44 #include <android-base/unique_fd.h>
46 #include "perfprofd_record.pb.h"
48 #include "configreader.h"
49 #include "cpuconfig.h"
50 #include "perf_data_converter.h"
51 #include "perfprofdcore.h"
52 #include "symbolizer.h"
55 // Perf profiling daemon -- collects system-wide profiles using
57 // simpleperf record -a
59 // and encodes them so that they can be uploaded by a separate service.
62 //......................................................................
64 using ProtoUniquePtr = std::unique_ptr<android::perfprofd::PerfprofdRecord>;
67 // Output file from 'perf record'.
69 #define PERF_OUTPUT "perf.data"
72 // This enum holds the results of the "should we profile" configuration check.
76 // All systems go for profile collection.
79 // The selected configuration directory doesn't exist.
80 DONT_PROFILE_MISSING_CONFIG_DIR,
82 // Destination directory does not contain the semaphore file that
83 // the perf profile uploading service creates when it determines
84 // that the user has opted "in" for usage data collection. No
85 // semaphore -> no user approval -> no profiling.
86 DONT_PROFILE_MISSING_SEMAPHORE,
88 // No perf executable present
89 DONT_PROFILE_MISSING_PERF_EXECUTABLE,
91 // We're running in the emulator, perf won't be able to do much
92 DONT_PROFILE_RUNNING_IN_EMULATOR
97 // Are we running in the emulator? If so, stub out profile collection
98 // Starts as uninitialized (-1), then set to 1 or 0 at init time.
100 static int running_in_emulator = -1;
103 // Is this a debug build ('userdebug' or 'eng')?
104 // Starts as uninitialized (-1), then set to 1 or 0 at init time.
106 static int is_debug_build = -1;
109 // Path to the perf file to convert and exit? Empty value is the default, daemon mode.
111 static std::string perf_file_to_convert = "";
114 // Random number generator seed (set at startup time).
116 static unsigned short random_seed[3];
119 // SIGHUP handler. Sending SIGHUP to the daemon can be used to break it
120 // out of a sleep() call so as to trigger a new collection (debugging)
122 static void sig_hup(int /* signum */)
124 LOG(WARNING) << "SIGHUP received";
128 // Parse command line args. Currently supported flags:
129 // * "-c PATH" sets the path of the config file to PATH.
130 // * "-x PATH" reads PATH as a perf data file and saves it as a file in
131 // perf_profile.proto format. ".encoded" suffix is appended to PATH to form
132 // the output file path.
134 static void parse_args(int argc, char** argv)
138 for (ac = 1; ac < argc; ++ac) {
139 if (!strcmp(argv[ac], "-c")) {
141 LOG(ERROR) << "malformed command line: -c option requires argument)";
144 ConfigReader::setConfigFilePath(argv[ac+1]);
146 } else if (!strcmp(argv[ac], "-x")) {
148 LOG(ERROR) << "malformed command line: -x option requires argument)";
151 perf_file_to_convert = argv[ac+1];
154 LOG(ERROR) << "malformed command line: unknown option or arg " << argv[ac] << ")";
161 // Convert a CKPROFILE_RESULT to a string
163 const char *ckprofile_result_to_string(CKPROFILE_RESULT result)
166 case DO_COLLECT_PROFILE:
167 return "DO_COLLECT_PROFILE";
168 case DONT_PROFILE_MISSING_CONFIG_DIR:
169 return "missing config directory";
170 case DONT_PROFILE_MISSING_SEMAPHORE:
171 return "missing semaphore file";
172 case DONT_PROFILE_MISSING_PERF_EXECUTABLE:
173 return "missing 'perf' executable";
174 case DONT_PROFILE_RUNNING_IN_EMULATOR:
175 return "running in emulator";
182 // Convert a PROFILE_RESULT to a string
184 const char *profile_result_to_string(PROFILE_RESULT result)
187 case OK_PROFILE_COLLECTION:
188 return "profile collection succeeded";
189 case ERR_FORK_FAILED:
190 return "fork() system call failed";
191 case ERR_PERF_RECORD_FAILED:
192 return "perf record returned bad exit status";
193 case ERR_PERF_ENCODE_FAILED:
194 return "failure encoding perf.data to protobuf";
195 case ERR_OPEN_ENCODED_FILE_FAILED:
196 return "failed to open encoded perf file";
197 case ERR_WRITE_ENCODED_FILE_FAILED:
198 return "write to encoded perf file failed";
205 // Check to see whether we should perform a profile collection
207 static CKPROFILE_RESULT check_profiling_enabled(const Config& config)
210 // Profile collection in the emulator doesn't make sense
212 assert(running_in_emulator != -1);
213 if (running_in_emulator) {
214 return DONT_PROFILE_RUNNING_IN_EMULATOR;
217 if (!config.IsProfilingEnabled()) {
218 return DONT_PROFILE_MISSING_CONFIG_DIR;
221 // Check for existence of simpleperf/perf executable
222 std::string pp = config.perf_path;
223 if (access(pp.c_str(), R_OK|X_OK) == -1) {
224 LOG(WARNING) << "unable to access/execute " << pp;
225 return DONT_PROFILE_MISSING_PERF_EXECUTABLE;
231 return DO_COLLECT_PROFILE;
236 return android::base::GetBoolProperty("sys.boot_completed", false) != true;
240 // Constructor takes a timeout (in seconds) and a child pid; If an
241 // alarm set for the specified number of seconds triggers, then a
242 // SIGKILL is sent to the child. Destructor resets alarm. Example:
244 // pid_t child_pid = ...;
245 // { AlarmHelper h(10, child_pid);
246 // ... = read_from_child(child_pid, ...);
249 // NB: this helper is not re-entrant-- avoid nested use or
250 // use by multiple threads
254 AlarmHelper(unsigned num_seconds, pid_t child)
256 struct sigaction sigact;
259 memset(&sigact, 0, sizeof(sigact));
260 sigact.sa_sigaction = handler;
261 sigaction(SIGALRM, &sigact, &oldsigact_);
269 sigaction(SIGALRM, &oldsigact_, NULL);
271 static void handler(int, siginfo_t *, void *);
274 struct sigaction oldsigact_;
278 pid_t AlarmHelper::child_;
280 void AlarmHelper::handler(int, siginfo_t *, void *)
282 LOG(WARNING) << "SIGALRM timeout";
283 kill(child_, SIGKILL);
287 // This implementation invokes "dumpsys media.camera" and inspects the
288 // output to determine if any camera clients are active. NB: this is
289 // currently disable (via config option) until the selinux issues can
290 // be sorted out. Another possible implementation (not yet attempted)
291 // would be to use the binder to call into the native camera service
292 // via "ICameraService".
294 bool get_camera_active()
297 if (pipe2(pipefds, O_CLOEXEC) != 0) {
298 PLOG(ERROR) << "pipe2() failed";
303 PLOG(ERROR) << "fork() failed";
307 } else if (pid == 0) {
310 dup2(pipefds[1], fileno(stderr));
311 dup2(pipefds[1], fileno(stdout));
312 const char *argv[10];
314 argv[slot++] = "/system/bin/dumpsys";
315 argv[slot++] = "media.camera";
316 argv[slot++] = nullptr;
317 execvp(argv[0], (char * const *)argv);
318 PLOG(ERROR) << "execvp() failed";
322 AlarmHelper helper(10, pid);
326 bool have_cam = false;
327 bool have_clients = true;
328 std::string dump_output;
329 bool result = android::base::ReadFdToString(pipefds[0], &dump_output);
332 std::stringstream ss(dump_output);
334 while (std::getline(ss,line,'\n')) {
335 if (line.find("Camera module API version:") !=
339 if (line.find("No camera module available") !=
341 line.find("No active camera clients yet") !=
343 have_clients = false;
348 // reap child (no zombies please)
350 TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
351 return have_cam && have_clients;
356 std::string psdir("/sys/class/power_supply");
357 DIR* dir = opendir(psdir.c_str());
359 PLOG(ERROR) << "Failed to open dir " << psdir;
364 while ((e = readdir(dir)) != 0) {
365 if (e->d_name[0] != '.') {
366 std::string online_path = psdir + "/" + e->d_name + "/online";
367 std::string contents;
369 if (android::base::ReadFileToString(online_path.c_str(), &contents) &&
370 sscanf(contents.c_str(), "%d", &value) == 1) {
382 bool postprocess_proc_stat_contents(const std::string &pscontents,
383 long unsigned *idleticks,
384 long unsigned *remainingticks)
386 long unsigned usertime, nicetime, systime, idletime, iowaittime;
387 long unsigned irqtime, softirqtime;
389 int rc = sscanf(pscontents.c_str(), "cpu %lu %lu %lu %lu %lu %lu %lu",
390 &usertime, &nicetime, &systime, &idletime,
391 &iowaittime, &irqtime, &softirqtime);
395 *idleticks = idletime;
396 *remainingticks = usertime + nicetime + systime + iowaittime + irqtime + softirqtime;
400 unsigned collect_cpu_utilization()
402 std::string contents;
403 long unsigned idle[2];
404 long unsigned busy[2];
405 for (unsigned iter = 0; iter < 2; ++iter) {
406 if (!android::base::ReadFileToString("/proc/stat", &contents)) {
409 if (!postprocess_proc_stat_contents(contents, &idle[iter], &busy[iter])) {
416 long unsigned total_delta = (idle[1] + busy[1]) - (idle[0] + busy[0]);
417 long unsigned busy_delta = busy[1] - busy[0];
418 return busy_delta * 100 / total_delta;
421 static void annotate_encoded_perf_profile(android::perfprofd::PerfprofdRecord* profile,
422 const Config& config,
423 unsigned cpu_utilization)
426 // Incorporate cpu utilization (collected prior to perf run)
428 if (config.collect_cpu_utilization) {
429 profile->set_cpu_utilization(cpu_utilization);
433 // Load average as reported by the kernel
437 if (android::base::ReadFileToString("/proc/loadavg", &load) &&
438 sscanf(load.c_str(), "%lf", &fload) == 1) {
439 int iload = static_cast<int>(fload * 100.0);
440 profile->set_sys_load_average(iload);
442 PLOG(ERROR) << "Failed to read or scan /proc/loadavg";
446 // Device still booting? Camera in use? Plugged into charger?
448 bool is_booting = get_booting();
449 if (config.collect_booting) {
450 profile->set_booting(is_booting);
452 if (config.collect_camera_active) {
453 profile->set_camera_active(is_booting ? false : get_camera_active());
455 if (config.collect_charging_state) {
456 profile->set_on_charger(get_charging());
460 // Examine the contents of wake_unlock to determine whether the
461 // device display is on or off. NB: is this really the only way to
462 // determine this info?
465 if (android::base::ReadFileToString("/sys/power/wake_unlock", &disp)) {
466 bool ison = (strstr(disp.c_str(), "PowerManagerService.Display") == 0);
467 profile->set_display_on(ison);
469 PLOG(ERROR) << "Failed to read /sys/power/wake_unlock";
473 PROFILE_RESULT SerializeProtobuf(android::perfprofd::PerfprofdRecord* encodedProfile,
474 const char* encoded_file_path) {
476 // Serialize protobuf to array
478 size_t size = encodedProfile->ByteSize();
479 std::unique_ptr<uint8_t[]> data(new uint8_t[size]);
480 encodedProfile->SerializeWithCachedSizesToArray(data.get());
483 // Open file and write encoded data to it
485 unlink(encoded_file_path); // Attempt to unlink for a clean slate.
486 constexpr int kFlags = O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC;
487 android::base::unique_fd fd(open(encoded_file_path, kFlags, 0664));
488 if (fd.get() == -1) {
489 PLOG(WARNING) << "Could not open " << encoded_file_path << " for serialization";
490 return ERR_OPEN_ENCODED_FILE_FAILED;
492 if (!android::base::WriteFully(fd.get(), data.get(), size)) {
493 PLOG(WARNING) << "Could not write to " << encoded_file_path;
494 return ERR_WRITE_ENCODED_FILE_FAILED;
497 return OK_PROFILE_COLLECTION;
500 static ProtoUniquePtr encode_to_proto(const std::string &data_file_path,
501 const Config& config,
502 unsigned cpu_utilization,
503 perfprofd::Symbolizer* symbolizer) {
505 // Open and read perf.data file
507 ProtoUniquePtr encodedProfile(
508 android::perfprofd::RawPerfDataToAndroidPerfProfile(data_file_path, symbolizer));
509 if (encodedProfile == nullptr) {
513 // All of the info in 'encodedProfile' is derived from the perf.data file;
514 // here we tack display status, cpu utilization, system load, etc.
515 annotate_encoded_perf_profile(encodedProfile.get(), config, cpu_utilization);
517 return encodedProfile;
520 PROFILE_RESULT encode_to_proto(const std::string &data_file_path,
521 const char *encoded_file_path,
522 const Config& config,
523 unsigned cpu_utilization,
524 perfprofd::Symbolizer* symbolizer)
526 ProtoUniquePtr encodedProfile = encode_to_proto(data_file_path,
532 // Issue error if no samples
534 if (encodedProfile == nullptr || encodedProfile->perf_data().events_size() == 0) {
535 return ERR_PERF_ENCODE_FAILED;
538 return SerializeProtobuf(encodedProfile.get(), encoded_file_path);
542 // Invoke "perf record". Return value is OK_PROFILE_COLLECTION for
543 // success, or some other error code if something went wrong.
545 static PROFILE_RESULT invoke_perf(Config& config,
546 const std::string &perf_path,
547 unsigned sampling_period,
548 const char *stack_profile_opt,
550 const std::string &data_file_path,
551 const std::string &perf_stderr_path)
556 return ERR_FORK_FAILED;
562 // Open file to receive stderr/stdout from perf
563 FILE *efp = fopen(perf_stderr_path.c_str(), "w");
565 dup2(fileno(efp), STDERR_FILENO);
566 dup2(fileno(efp), STDOUT_FILENO);
568 PLOG(WARNING) << "unable to open " << perf_stderr_path << " for writing";
571 // marshall arguments
572 constexpr unsigned max_args = 14;
573 const char *argv[max_args];
575 argv[slot++] = perf_path.c_str();
576 argv[slot++] = "record";
580 argv[slot++] = data_file_path.c_str();
584 std::string p_str = android::base::StringPrintf("%u", sampling_period);
585 argv[slot++] = p_str.c_str();
588 if (stack_profile_opt)
589 argv[slot++] = stack_profile_opt;
592 if (config.process < 0) {
593 // system wide profiling
597 pid_str = std::to_string(config.process);
598 argv[slot++] = pid_str.c_str();
601 // no need for kernel symbols
602 argv[slot++] = "--no-dump-kernel-symbols";
605 argv[slot++] = "/system/bin/sleep";
606 std::string d_str = android::base::StringPrintf("%u", duration);
607 argv[slot++] = d_str.c_str();
610 argv[slot++] = nullptr;
611 assert(slot < max_args);
613 // record the final command line in the error output file for
614 // posterity/debugging purposes
615 fprintf(stderr, "perf invocation (pid=%d):\n", getpid());
616 for (unsigned i = 0; argv[i] != nullptr; ++i) {
617 fprintf(stderr, "%s%s", i ? " " : "", argv[i]);
619 fprintf(stderr, "\n");
622 execvp(argv[0], (char * const *)argv);
623 fprintf(stderr, "exec failed: %s\n", strerror(errno));
630 config.Sleep(duration);
632 // We may have been woken up to stop profiling.
633 if (config.ShouldStopProfiling()) {
634 // Send SIGHUP to simpleperf to make it stop.
638 // Wait for the child, so it's reaped correctly.
640 pid_t reaped = TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
643 PLOG(WARNING) << "waitpid failed";
644 } else if (WIFSIGNALED(st)) {
645 if (WTERMSIG(st) == SIGHUP && config.ShouldStopProfiling()) {
647 return OK_PROFILE_COLLECTION;
649 LOG(WARNING) << "perf killed by signal " << WTERMSIG(st);
650 } else if (WEXITSTATUS(st) != 0) {
651 LOG(WARNING) << "perf bad exit status " << WEXITSTATUS(st);
653 return OK_PROFILE_COLLECTION;
657 return ERR_PERF_RECORD_FAILED;
661 // Remove all files in the destination directory during initialization
663 static void cleanup_destination_dir(const std::string& dest_dir)
665 DIR* dir = opendir(dest_dir.c_str());
668 while ((e = readdir(dir)) != 0) {
669 if (e->d_name[0] != '.') {
670 std::string file_path = dest_dir + "/" + e->d_name;
671 remove(file_path.c_str());
676 PLOG(WARNING) << "unable to open destination dir " << dest_dir << " for cleanup";
681 // Post-processes after profile is collected and converted to protobuf.
682 // * GMS core stores processed file sequence numbers in
683 // /data/data/com.google.android.gms/files/perfprofd_processed.txt
684 // * Update /data/misc/perfprofd/perfprofd_produced.txt to remove the sequence
685 // numbers that have been processed and append the current seq number
686 // Returns true if the current_seq should increment.
688 static bool post_process(const Config& config, int current_seq)
690 const std::string& dest_dir = config.destination_directory;
691 std::string processed_file_path =
692 config.config_directory + "/" + PROCESSED_FILENAME;
693 std::string produced_file_path = dest_dir + "/" + PRODUCED_FILENAME;
696 std::set<int> processed;
697 FILE *fp = fopen(processed_file_path.c_str(), "r");
700 while(fscanf(fp, "%d\n", &seq) > 0) {
701 if (remove(android::base::StringPrintf(
702 "%s/perf.data.encoded.%d", dest_dir.c_str(),seq).c_str()) == 0) {
703 processed.insert(seq);
709 std::set<int> produced;
710 fp = fopen(produced_file_path.c_str(), "r");
713 while(fscanf(fp, "%d\n", &seq) > 0) {
714 if (processed.find(seq) == processed.end()) {
715 produced.insert(seq);
721 uint32_t maxLive = config.max_unprocessed_profiles;
722 if (produced.size() >= maxLive) {
726 produced.insert(current_seq);
727 fp = fopen(produced_file_path.c_str(), "w");
729 PLOG(WARNING) << "Cannot write " << produced_file_path;
732 for (std::set<int>::const_iterator iter = produced.begin();
733 iter != produced.end(); ++iter) {
734 fprintf(fp, "%d\n", *iter);
737 chmod(produced_file_path.c_str(),
738 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
743 // Collect a perf profile. Steps for this operation are:
744 // - kick off 'perf record'
745 // - read perf.data, convert to protocol buf
747 static ProtoUniquePtr collect_profile(Config& config)
750 // Collect cpu utilization if enabled
752 unsigned cpu_utilization = 0;
753 if (config.collect_cpu_utilization) {
754 cpu_utilization = collect_cpu_utilization();
758 // Form perf.data file name, perf error output file name
760 const std::string& destdir = config.destination_directory;
761 std::string data_file_path(destdir);
762 data_file_path += "/";
763 data_file_path += PERF_OUTPUT;
764 std::string perf_stderr_path(destdir);
765 perf_stderr_path += "/perferr.txt";
768 // Remove any existing perf.data file -- if we don't do this, perf
769 // will rename the old file and we'll have extra cruft lying around.
772 if (stat(data_file_path.c_str(), &statb) == 0) { // if file exists...
773 if (unlink(data_file_path.c_str())) { // then try to remove
774 PLOG(WARNING) << "unable to unlink previous perf.data file";
779 // The "mpdecision" daemon can cause problems for profile
780 // collection: if it decides to online a CPU partway through the
781 // 'perf record' run, the activity on that CPU will be invisible to
782 // perf, and if it offlines a CPU during the recording this can
783 // sometimes leave the PMU in an unusable state (dmesg errors of the
784 // form "perfevents: unable to request IRQXXX for ..."). To avoid
785 // these issues, if "mpdecision" is running the helper below will
786 // stop the service and then online all available CPUs. The object
787 // destructor (invoked when this routine terminates) will then
788 // restart the service again when needed.
790 uint32_t duration = config.sample_duration_in_s;
791 bool hardwire = config.hardwire_cpus;
792 uint32_t max_duration = config.hardwire_cpus_max_duration_in_s;
793 bool take_action = (hardwire && duration <= max_duration);
794 HardwireCpuHelper helper(take_action);
799 const char *stack_profile_opt =
800 (config.stack_profile ? "-g" : nullptr);
801 const std::string& perf_path = config.perf_path;
802 uint32_t period = config.sampling_period;
804 PROFILE_RESULT ret = invoke_perf(config,
811 if (ret != OK_PROFILE_COLLECTION) {
816 // Read the resulting perf.data file, encode into protocol buffer, then write
817 // the result to the file perf.data.encoded
819 std::unique_ptr<perfprofd::Symbolizer> symbolizer;
820 if (config.use_elf_symbolizer) {
821 symbolizer = perfprofd::CreateELFSymbolizer();
823 return encode_to_proto(data_file_path, config, cpu_utilization, symbolizer.get());
827 // Assuming that we want to collect a profile every N seconds,
828 // randomly partition N into two sub-intervals.
830 static void determine_before_after(unsigned &sleep_before_collect,
831 unsigned &sleep_after_collect,
832 unsigned collection_interval)
834 double frac = erand48(random_seed);
835 sleep_before_collect = (unsigned) (((double)collection_interval) * frac);
836 assert(sleep_before_collect <= collection_interval);
837 sleep_after_collect = collection_interval - sleep_before_collect;
841 // Set random number generator seed
843 static void set_seed(uint32_t use_fixed_seed)
846 if (use_fixed_seed) {
848 // Use fixed user-specified seed
850 seed = use_fixed_seed;
857 LOG(INFO) << "random seed set to " << seed;
858 // Distribute the 32-bit seed into the three 16-bit array
859 // elements. The specific values being written do not especially
860 // matter as long as we are setting them to something based on the seed.
861 random_seed[0] = seed & 0xffff;
862 random_seed[1] = (seed >> 16);
863 random_seed[2] = (random_seed[0] ^ random_seed[1]);
866 static void CommonInit(uint32_t use_fixed_seed, const char* dest_dir) {
867 // Children of init inherit an artificially low OOM score -- this is not
868 // desirable for perfprofd (its OOM score should be on par with
869 // other user processes).
870 std::stringstream oomscore_path;
871 oomscore_path << "/proc/" << getpid() << "/oom_score_adj";
872 if (!android::base::WriteStringToFile("0", oomscore_path.str())) {
873 LOG(ERROR) << "unable to write to " << oomscore_path.str();
876 set_seed(use_fixed_seed);
877 if (dest_dir != nullptr) {
878 cleanup_destination_dir(dest_dir);
881 running_in_emulator = android::base::GetBoolProperty("ro.kernel.qemu", false);
882 is_debug_build = android::base::GetBoolProperty("ro.debuggable", false);
888 static void init(const Config& config)
890 // TODO: Consider whether we want to clean things or just overwrite.
891 CommonInit(config.use_fixed_seed, nullptr);
894 static void init(ConfigReader &config)
896 if (!config.readFile()) {
897 LOG(ERROR) << "unable to open configuration file " << config.getConfigFilePath();
900 CommonInit(static_cast<uint32_t>(config.getUnsignedValue("use_fixed_seed")),
901 config.getStringValue("destination_directory").c_str());
903 signal(SIGHUP, sig_hup);
906 template <typename ConfigFn, typename UpdateFn>
907 static void ProfilingLoopImpl(ConfigFn config, UpdateFn update, HandlerFn handler) {
908 unsigned iterations = 0;
909 while(config()->main_loop_iterations == 0 ||
910 iterations < config()->main_loop_iterations) {
911 if (config()->ShouldStopProfiling()) {
915 // Figure out where in the collection interval we're going to actually
917 unsigned sleep_before_collect = 0;
918 unsigned sleep_after_collect = 0;
919 determine_before_after(sleep_before_collect, sleep_after_collect,
920 config()->collection_interval_in_s);
921 config()->Sleep(sleep_before_collect);
923 if (config()->ShouldStopProfiling()) {
927 // Run any necessary updates.
930 // Check for profiling enabled...
931 CKPROFILE_RESULT ckresult = check_profiling_enabled(*config());
932 if (ckresult != DO_COLLECT_PROFILE) {
933 LOG(INFO) << "profile collection skipped (" << ckprofile_result_to_string(ckresult) << ")";
935 // Kick off the profiling run...
936 LOG(INFO) << "initiating profile collection";
937 ProtoUniquePtr proto = collect_profile(*config());
938 if (proto == nullptr) {
939 LOG(WARNING) << "profile collection failed";
942 // Always report, even a null result.
943 bool handle_result = handler(proto.get(), config());
945 LOG(INFO) << "profile collection complete";
946 } else if (proto != nullptr) {
947 LOG(WARNING) << "profile handling failed";
951 if (config()->ShouldStopProfiling()) {
955 config()->Sleep(sleep_after_collect);
960 void ProfilingLoop(Config& config, HandlerFn handler) {
963 auto config_fn = [&config]() {
966 auto do_nothing = []() {
968 ProfilingLoopImpl(config_fn, do_nothing, handler);
973 // 1. parse cmd line args
974 // 2. read config file
977 // perform a profile collection
980 int perfprofd_main(int argc, char** argv, Config* config)
982 ConfigReader config_reader;
984 LOG(INFO) << "starting Android Wide Profiling daemon";
986 parse_args(argc, argv);
988 config_reader.FillConfig(config);
990 if (!perf_file_to_convert.empty()) {
991 std::string encoded_path = perf_file_to_convert + ".encoded";
992 encode_to_proto(perf_file_to_convert, encoded_path.c_str(), *config, 0, nullptr);
996 // Early exit if we're not supposed to run on this build flavor
997 if (is_debug_build != 1 && config->only_debug_build) {
998 LOG(INFO) << "early exit due to inappropriate build type";
1002 auto config_fn = [config]() {
1005 auto reread_config = [&config_reader, config]() {
1006 // Reread config file -- the uploader may have rewritten it as a result
1007 // of a gservices change
1008 config_reader.readFile();
1009 config_reader.FillConfig(config);
1012 auto handler = [&seq](android::perfprofd::PerfprofdRecord* proto, Config* handler_config) {
1013 if (proto == nullptr) {
1016 std::string data_file_path(handler_config->destination_directory);
1017 data_file_path += "/";
1018 data_file_path += PERF_OUTPUT;
1019 std::string path = android::base::StringPrintf("%s.encoded.%d", data_file_path.c_str(), seq);
1020 PROFILE_RESULT result = SerializeProtobuf(proto, path.c_str());
1021 if (result != PROFILE_RESULT::OK_PROFILE_COLLECTION) {
1025 if (!post_process(*handler_config, seq)) {
1031 ProfilingLoopImpl(config_fn, reread_config, handler);
1033 LOG(INFO) << "finishing Android Wide Profiling daemon";