Home | History | Annotate | Download | only in update_engine
      1 //
      2 // Copyright (C) 2012 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 
     17 #include <inttypes.h>
     18 #include <sys/stat.h>
     19 #include <sys/types.h>
     20 #include <unistd.h>
     21 #include <xz.h>
     22 
     23 #include <algorithm>
     24 #include <string>
     25 #include <vector>
     26 
     27 #include <base/at_exit.h>
     28 #include <base/command_line.h>
     29 #include <base/files/dir_reader_posix.h>
     30 #include <base/files/file_util.h>
     31 #include <base/logging.h>
     32 #include <base/strings/string_util.h>
     33 #include <base/strings/stringprintf.h>
     34 #include <brillo/flag_helper.h>
     35 
     36 #include "update_engine/common/terminator.h"
     37 #include "update_engine/common/utils.h"
     38 #include "update_engine/daemon.h"
     39 
     40 using std::string;
     41 
     42 namespace chromeos_update_engine {
     43 namespace {
     44 
     45 string GetTimeAsString(time_t utime) {
     46   struct tm tm;
     47   CHECK_EQ(localtime_r(&utime, &tm), &tm);
     48   char str[16];
     49   CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
     50   return str;
     51 }
     52 
     53 #ifdef __ANDROID__
     54 constexpr char kSystemLogsRoot[] = "/data/misc/update_engine_log";
     55 constexpr size_t kLogCount = 5;
     56 
     57 // Keep the most recent |kLogCount| logs but remove the old ones in
     58 // "/data/misc/update_engine_log/".
     59 void DeleteOldLogs(const string& kLogsRoot) {
     60   base::DirReaderPosix reader(kLogsRoot.c_str());
     61   if (!reader.IsValid()) {
     62     LOG(ERROR) << "Failed to read " << kLogsRoot;
     63     return;
     64   }
     65 
     66   std::vector<string> old_logs;
     67   while (reader.Next()) {
     68     if (reader.name()[0] == '.')
     69       continue;
     70 
     71     // Log files are in format "update_engine.%Y%m%d-%H%M%S",
     72     // e.g. update_engine.20090103-231425
     73     uint64_t date;
     74     uint64_t local_time;
     75     if (sscanf(reader.name(),
     76                "update_engine.%" PRIu64 "-%" PRIu64 "",
     77                &date,
     78                &local_time) == 2) {
     79       old_logs.push_back(reader.name());
     80     } else {
     81       LOG(WARNING) << "Unrecognized log file " << reader.name();
     82     }
     83   }
     84 
     85   std::sort(old_logs.begin(), old_logs.end(), std::greater<string>());
     86   for (size_t i = kLogCount; i < old_logs.size(); i++) {
     87     string log_path = kLogsRoot + "/" + old_logs[i];
     88     if (unlink(log_path.c_str()) == -1) {
     89       PLOG(WARNING) << "Failed to unlink " << log_path;
     90     }
     91   }
     92 }
     93 
     94 string SetupLogFile(const string& kLogsRoot) {
     95   DeleteOldLogs(kLogsRoot);
     96 
     97   return base::StringPrintf("%s/update_engine.%s",
     98                             kLogsRoot.c_str(),
     99                             GetTimeAsString(::time(nullptr)).c_str());
    100 }
    101 #else
    102 constexpr char kSystemLogsRoot[] = "/var/log";
    103 
    104 void SetupLogSymlink(const string& symlink_path, const string& log_path) {
    105   // TODO(petkov): To ensure a smooth transition between non-timestamped and
    106   // timestamped logs, move an existing log to start the first timestamped
    107   // one. This code can go away once all clients are switched to this version or
    108   // we stop caring about the old-style logs.
    109   if (utils::FileExists(symlink_path.c_str()) &&
    110       !utils::IsSymlink(symlink_path.c_str())) {
    111     base::ReplaceFile(base::FilePath(symlink_path),
    112                       base::FilePath(log_path),
    113                       nullptr);
    114   }
    115   base::DeleteFile(base::FilePath(symlink_path), true);
    116   if (symlink(log_path.c_str(), symlink_path.c_str()) == -1) {
    117     PLOG(ERROR) << "Unable to create symlink " << symlink_path
    118                 << " pointing at " << log_path;
    119   }
    120 }
    121 
    122 string SetupLogFile(const string& kLogsRoot) {
    123   const string kLogSymlink = kLogsRoot + "/update_engine.log";
    124   const string kLogsDir = kLogsRoot + "/update_engine";
    125   const string kLogPath =
    126       base::StringPrintf("%s/update_engine.%s",
    127                          kLogsDir.c_str(),
    128                          GetTimeAsString(::time(nullptr)).c_str());
    129   mkdir(kLogsDir.c_str(), 0755);
    130   SetupLogSymlink(kLogSymlink, kLogPath);
    131   return kLogSymlink;
    132 }
    133 #endif  // __ANDROID__
    134 
    135 void SetupLogging(bool log_to_system, bool log_to_file) {
    136   logging::LoggingSettings log_settings;
    137   log_settings.lock_log = logging::DONT_LOCK_LOG_FILE;
    138   log_settings.logging_dest = static_cast<logging::LoggingDestination>(
    139       (log_to_system ? logging::LOG_TO_SYSTEM_DEBUG_LOG : 0) |
    140       (log_to_file ? logging::LOG_TO_FILE : 0));
    141   log_settings.log_file = nullptr;
    142 
    143   string log_file;
    144   if (log_to_file) {
    145     log_file = SetupLogFile(kSystemLogsRoot);
    146     log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
    147     log_settings.log_file = log_file.c_str();
    148   }
    149   logging::InitLogging(log_settings);
    150 
    151 #ifdef __ANDROID__
    152   // The log file will have AID_LOG as group ID; this GID is inherited from the
    153   // parent directory "/data/misc/update_engine_log" which sets the SGID bit.
    154   chmod(log_file.c_str(), 0640);
    155 #endif
    156 }
    157 
    158 }  // namespace
    159 }  // namespace chromeos_update_engine
    160 
    161 int main(int argc, char** argv) {
    162   DEFINE_bool(logtofile, false, "Write logs to a file in log_dir.");
    163   DEFINE_bool(logtostderr, false,
    164               "Write logs to stderr instead of to a file in log_dir.");
    165   DEFINE_bool(foreground, false,
    166               "Don't daemon()ize; run in foreground.");
    167 
    168   chromeos_update_engine::Terminator::Init();
    169   brillo::FlagHelper::Init(argc, argv, "Chromium OS Update Engine");
    170 
    171   // We have two logging flags "--logtostderr" and "--logtofile"; and the logic
    172   // to choose the logging destination is:
    173   // 1. --logtostderr --logtofile -> logs to both
    174   // 2. --logtostderr             -> logs to system debug
    175   // 3. --logtofile or no flags   -> logs to file
    176   bool log_to_system = FLAGS_logtostderr;
    177   bool log_to_file = FLAGS_logtofile || !FLAGS_logtostderr;
    178   chromeos_update_engine::SetupLogging(log_to_system, log_to_file);
    179   if (!FLAGS_foreground)
    180     PLOG_IF(FATAL, daemon(0, 0) == 1) << "daemon() failed";
    181 
    182   LOG(INFO) << "Chrome OS Update Engine starting";
    183 
    184   // xz-embedded requires to initialize its CRC-32 table once on startup.
    185   xz_crc32_init();
    186 
    187   // Ensure that all written files have safe permissions.
    188   // This is a mask, so we _block_ all permissions for the group owner and other
    189   // users but allow all permissions for the user owner. We allow execution
    190   // for the owner so we can create directories.
    191   // Done _after_ log file creation.
    192   umask(S_IRWXG | S_IRWXO);
    193 
    194   chromeos_update_engine::UpdateEngineDaemon update_engine_daemon;
    195   int exit_code = update_engine_daemon.Run();
    196 
    197   LOG(INFO) << "Chrome OS Update Engine terminating with exit code "
    198             << exit_code;
    199   return exit_code;
    200 }
    201