Android P update_engine分析 --update_engine_client的工作

Posted Give.Me.Five

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android P update_engine分析 --update_engine_client的工作相关的知识,希望对你有一定的参考价值。

当AB系统升级时,有两种方式来调用updateengine,来实现升级,一种方法是直接执行shell命令,调用 update_engine_client,带参数来实现升级,另一种方式是应用层直接调用UpdateEngine的applyPayload方法来升级。

update_engine_client 带参升级

shell命令调用update_engine_client带参数去升级,具体如下:

update_engine_client --payload=file:///sdcard/payload.bin --update --headers="FILE_HASH=qeebzpLK4f/FaDAVJ9ilCxnUC/TMO16S5QP39AjsYKc=
FILE_SIZE=445814087
METADATA_HASH=nn9V2c3dQ3yHwQQJW0R0Q+y+OQzWuJ5FZt4HxCiAry0=
METADATA_SIZE=58898"

后面带了payload-file和 headers的参数,那我们来分析下update_engine_client 到底是如何来工作的。

int main(int argc, char** argv) {
//初始化UpdateEngineClientandroid,然后执行 
  chromeos_update_engine::internal::UpdateEngineClientAndroid client(
      argc, argv);
  return client.Run();
}
class UpdateEngineClientAndroid : public brillo::Daemon {
  ....

UpdateEngineClientAndroid 是继承brillo::Daemon的,这个类我们在启动update_engine里分析过,执行其Run函数时,会先调用 onInit(), 那我们一起来看看onInit:


int UpdateEngineClientAndroid::OnInit() {
  int ret = Daemon::OnInit();
  if (ret != EX_OK)
    return ret;
//对后续参数的数据类型,默认值,以及参数解释
  DEFINE_bool(update, false, "Start a new update, if no update in progress.");
  DEFINE_string(payload,
                "http://127.0.0.1:8080/payload",
                "The URI to the update payload to use.");
  DEFINE_int64(offset, 0,
               "The offset in the payload where the CrAU update starts. "
               "Used when --update is passed.");
  DEFINE_int64(size, 0,
               "The size of the CrAU part of the payload. If 0 is passed, it "
               "will be autodetected. Used when --update is passed.");
  DEFINE_string(headers,
                "",
                "A list of key-value pairs, one element of the list per line. "
                "Used when --update is passed.");

  DEFINE_bool(suspend, false, "Suspend an ongoing update and exit.");
  DEFINE_bool(resume, false, "Resume a suspended update.");
  DEFINE_bool(cancel, false, "Cancel the ongoing update and exit.");
  DEFINE_bool(reset_status, false, "Reset an already applied update and exit.");
  DEFINE_bool(follow,
              false,
              "Follow status update changes until a final state is reached. "
              "Exit status is 0 if the update succeeded, and 1 otherwise.");

  // 使用Brillo::FlagHelper来解析带的参数
  base::CommandLine::Init(argc_, argv_);
  brillo::FlagHelper::Init(argc_, argv_, "Android Update Engine Client");
  if (argc_ == 1) {
    LOG(ERROR) << "Nothing to do. Run with --help for help.";
    return 1;
  }

  // 检测参数的合法性
  const std::vector<std::string> positional_args =
      base::CommandLine::ForCurrentProcess()->GetArgs();
  if (!positional_args.empty()) {
    LOG(ERROR) << "Found a positional argument '" << positional_args.front()
               << "'. If you want to pass a value to a flag, pass it as "
                  "--flag=value.";
    return 1;
  }
//启动brillo的log系统
  bool keep_running = false;
  brillo::InitLog(brillo::kLogToStderr);

//启动一个binder的看门狗
  binder_watcher_.Init();
//通过Binder获取UpdateEngineService的服务,并赋仠给service_
  android::status_t status = android::getService(
      android::String16("android.os.UpdateEngineService"), &service_);
  if (status != android::OK) {
    LOG(ERROR) << "Failed to get IUpdateEngine binder from service manager: "
               << Status::fromStatusT(status).toString8();
    return ExitWhenIdle(1);
  }
//如果有接suspend的参数
  if (FLAGS_suspend) {
    return ExitWhenIdle(service_->suspend());
  }
//如果有接resume参数
  if (FLAGS_resume) {
    return ExitWhenIdle(service_->resume());
  }
//如果有接cancel参数
  if (FLAGS_cancel) {
    return ExitWhenIdle(service_->cancel());
  }
  //如果有接reset_status参数
  if (FLAGS_reset_status) {
    return ExitWhenIdle(service_->resetStatus());
  }
//如果有接follow,
  if (FLAGS_follow) {
    // Register a callback object with the service.
    callback_ = new UECallback(this);
    bool bound;
    if (!service_->bind(callback_, &bound).isOk() || !bound) {
      LOG(ERROR) << "Failed to bind() the UpdateEngine daemon.";
      return 1;
    }
    keep_running = true;
  }
//如果有接update参数,解析分割headers参数
  if (FLAGS_update) {
    std::vector<std::string> headers = base::SplitString(
        FLAGS_headers, "\\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
    std::vector<android::String16> and_headers;
    for (const auto& header : headers) {
      and_headers.push_back(android::String16{header.data(), header.size()});
    }
    //执行applyPayload函数,执行升级
    Status status = service_->applyPayload(
        android::String16{FLAGS_payload.data(), FLAGS_payload.size()},
        FLAGS_offset,
        FLAGS_size,
        and_headers);
    if (!status.isOk())
      return ExitWhenIdle(status);
  }

  if (!keep_running)
    return ExitWhenIdle(EX_OK);

  //监听service_状态的改变,如UpdateEngineServiceDied
  android::BinderWrapper::Create();
  android::BinderWrapper::Get()->RegisterForDeathNotifications(
      android::os::IUpdateEngine::asBinder(service_),
      base::Bind(&UpdateEngineClientAndroid::UpdateEngineServiceDied,
                 base::Unretained(this)));

  return EX_OK;
}

从上面可以看到先定义参数的数据类型,检查其合法,解析参数,获取updateEngineService服务,然后执行其applyPayload。这个方式感觉UpdateEngine.applyPayload方式一样,具体是否一致呢,我们来看看UpdateEngine的applyPayload的实现。

UpdateEngine.applyPayload

    public void applyPayload(String url, long offset, long size, String[] headerKeyValuePairs) {
        try {
        	//调用 service的applyPayload
            mUpdateEngine.applyPayload(url, offset, size, headerKeyValuePairs);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
    public UpdateEngine() {
    	//mUpdateEngine 也是通过Binder获取update_engine service
        mUpdateEngine = IUpdateEngine.Stub.asInterface(
                ServiceManager.getService(UPDATE_ENGINE_SERVICE));
    }    

那我们猜的结果是一样,也是调用updateEngine服务的applyPayload。那升级的具体实现其实是调用applyPayload来实现的。

UpdateEngine服务

上面看到不管是update_engine_client 还是Java层的updateEngine接口,最后调用到都是updateEngine服务,对应到的是BinderUpdateEngineAndroidService:

class BinderUpdateEngineAndroidService : public android::os::BnUpdateEngine,
                                         public ServiceObserverInterface {
  const char* ServiceName() const {
    return "android.os.UpdateEngineService";
  }  
}
Status BinderUpdateEngineAndroidService::applyPayload(
    const android::String16& url,
    int64_t payload_offset,
    int64_t payload_size,
    const std::vector<android::String16>& header_kv_pairs) {
  const std::string payload_url{android::String8{url}.string()};
  std::vector<std::string> str_headers;
  str_headers.reserve(header_kv_pairs.size());
  for (const auto& header : header_kv_pairs) {
    str_headers.emplace_back(android::String8{header}.string());
  }
  brillo::ErrorPtr error;
  if (!service_delegate_->ApplyPayload(
          payload_url, payload_offset, payload_size, str_headers, &error)) {
    return ErrorPtrToStatus(error);
  }
  return Status::ok();
}                                         

updateService 实际上的是service_delegate_,这个也是DaemonStateAndroid 获取的service_delegate,也就是update_attempter_.get(), 对应的类是UpdateAttempterAndroid。


bool UpdateAttempterAndroid::ApplyPayload(
    const string& payload_url,
    int64_t payload_offset,
    int64_t payload_size,
    const vector<string>& key_value_pair_headers,
    brillo::ErrorPtr* error) {
  //如果需要升级,不能继续再升级了
  if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
    return LogAndSetError(
        error, FROM_HERE, "An update already applied, waiting for reboot");
  }
  //如果在升级过程中,不能继续升级
  if (ongoing_update_) {
    return LogAndSetError(
        error, FROM_HERE, "Already processing an update, cancel it first.");
  }
  DCHECK(status_ == UpdateStatus::IDLE);

 //将headers的参数解析出来后,添加到headers的maps中
  std::map<string, string> headers;
  for (const string& key_value_pair : key_value_pair_headers) {
    string key;
    string value;
    if (!brillo::string_utils::SplitAtFirst(
            key_value_pair, "=", &key, &value, false)) {
      return LogAndSetError(
          error, FROM_HERE, "Passed invalid header: " + key_value_pair);
    }
    if (!headers.emplace(key, value).second)
      return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
  }

  //设置一个对应的独一无二的id
  string payload_id = (headers[kPayloadPropertyFileHash] +
                       headers[kPayloadPropertyMetadataHash]);

  //初始化一个install_plan_, 然后将applyPayload的参数赋值给install_plan_。
  install_plan_ = InstallPlan();

  install_plan_.download_url = payload_url;
  install_plan_.version = "";
  base_offset_ = payload_offset;
  InstallPlan::Payload payload;
  payload.size = payload_size;
  if (!payload.size) {
    if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
                              &payload.size)) {
      payload.size = 0;
    }
  }
  if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
                                           &payload.hash)) {
    LOG(WARNING) << "Unable to decode base64 file hash: "
                 << headers[kPayloadPropertyFileHash];
  }
  if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
                            &payload.metadata_size)) {
    payload.metadata_size = 0;
  }
  // The |payload.type| is not used anymore since minor_version 3.
  payload.type = InstallPayloadType::kUnknown;
  install_plan_.payloads.push_back(payload);

  // The |public_key_rsa| key would override the public key stored on disk.
  install_plan_.public_key_rsa = "";

  install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
  install_plan_.is_resume = !payload_id.empty() &&
                            DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
  if (!install_plan_.is_resume) {
    if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
      LOG(WARNING) << "Unable to reset the update progress.";
    }
    if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
      LOG(WARNING) << "Unable to save the update check response hash.";
    }
  }
  install_plan_.source_slot = boot_control_->GetCurrentSlot();
  install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;

  install_plan_.powerwash_required =
      GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);

  install_plan_.switch_slot_on_reboot =
      GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);

  install_plan_.run_post_install = true;
  //判断是否可以设置run_post_install
  if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
    bool post_install_succeeded = false;
    prefs_->GetBoolean(kPrefsPostInstallSucceeded, &post_install_succeeded);
    if (post_install_succeeded) {
      install_plan_.run_post_install =
          GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
    }
  }
//检测网络id
  NetworkId network_id = kDefaultNetworkId;
  if (!headers[kPayloadPropertyNetworkId].empty()) {
    if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
                              &network_id)) {
      return LogAndSetError(
          error,
          FROM_HERE,
          "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
    }
    if (!network_selector_->SetProcessNetwork(network_id)) {
      return LogAndSetError(
          error,
          FROM_HERE,
          "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
    }
  }
//打印install_plan_的信息
  LOG(INFO) << "Using this install plan:";
  install_plan_.Dump();
//开启UpdateAction的动作,开启推动升级开始
  BuildUpdateActions(payload_url);
  //设置额外的校验头 和 用户代理的头
  HttpFetcher* fetcher = download_action_->http_fetcher();
  if (!headers[kPayloadPropertyAuthorization].empty())
    fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
  if (!headers[kPayloadPropertyUserAgent].empty())
    fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
  //回调升级的状态
  SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
  ongoing_update_ = true;

  //升级之前,确认当前的bootFlags 已经 更新
  UpdateBootFlags();
  //更新本地存储的升级信息,包括 ,升级次数,重启次数,升级时间等
  UpdatePrefsOnUpdateStart(install_plan_.is_resume);
  return true;
}

从上面的注释里可以看到,先将applyPayload的相关信息与参数传给install_plan_的结构体中,然后调用BuildUpdateActions去开启升级。那下面我们继续分析BuildUpdateActions(payload_url)。


void UpdateAttempterAndroid::BuildUpdateActions(const string& url) {
  CHECK(!processor_->IsRunning());
  processor_->set_delegate(this);

  //初始化InstallPlanAction的升级安装行动
  shared_ptr<InstallPlanAction> install_plan_action(
      new InstallPlanAction(install_plan_));

  HttpFetcher* download_fetcher = nullptr;
  if (FileFetcher::SupportedUrl(url)) {
    DLOG(INFO) << "Using FileFetcher for file URL.";
    download_fetcher = new FileFetcher();
  } else {
#ifdef _UE_SIDELOAD
    LOG(FATAL) << "Unsupported sideload URI: " << url;
#Android P update_engine分析--升级核心DeltaPerformer的分析

Android P update_engine分析--升级核心DeltaPerformer的分析

Android P update_engine分析--升级核心DeltaPerformer的分析

Android P update_engine分析--升级核心DeltaPerformer的分析

Android P update_engine分析-- PostinstallRunnerAction的工作

Android P update_engine分析-- PostinstallRunnerAction的工作