void KatranLb::attachBpfProgs()

in katran/lib/KatranLb.cpp [851:906]


void KatranLb::attachBpfProgs() {
  if (!progsLoaded_) {
    throw std::invalid_argument("failed to attach bpf prog: prog not loaded");
  }
  int res;
  auto main_fd = bpfAdapter_.getProgFdByName(kBalancerProgName.toString());
  auto interface_index = ctlValues_[kMainIntfPos].ifindex;
  if (standalone_) {
    // attaching main bpf prog in standalone mode
    res = bpfAdapter_.modifyXdpProg(
        main_fd, interface_index, config_.xdpAttachFlags);
    if (res != 0) {
      throw std::invalid_argument(folly::sformat(
          "can't attach main bpf prog "
          "to main inteface, error: {}",
          folly::errnoStr(errno)));
    }
  } else if (!config_.disableForwarding) {
    // we are in "shared" mode and must register ourself in root xdp prog
    rootMapFd_ = bpfAdapter_.getPinnedBpfObject(config_.rootMapPath);
    if (rootMapFd_ < 0) {
      throw std::invalid_argument(folly::sformat(
          "can't get fd of xdp's root map, error: {}", folly::errnoStr(errno)));
    }
    res = bpfAdapter_.bpfUpdateMap(rootMapFd_, &config_.rootMapPos, &main_fd);
    if (res) {
      throw std::invalid_argument(folly::sformat(
          "can't register in root array, error: {}", folly::errnoStr(errno)));
    }
  }

  if (config_.enableHc && !progsReloaded_) {
    // attaching healthchecking bpf prog.
    auto hc_fd = getHealthcheckerProgFd();
    res = bpfAdapter_.addTcBpfFilter(
        hc_fd,
        ctlValues_[kHcIntfPos].ifindex,
        "katran-healthchecker",
        config_.priority,
        TC_EGRESS);
    if (res != 0) {
      if (standalone_) {
        // will try to remove main bpf prog.
        bpfAdapter_.detachXdpProg(interface_index, config_.xdpAttachFlags);
      } else {
        bpfAdapter_.bpfMapDeleteElement(rootMapFd_, &config_.rootMapPos);
      }
      throw std::invalid_argument(folly::sformat(
          "can't attach healthchecking bpf prog "
          "to given inteface: {}, error: {}",
          config_.hcInterface,
          folly::errnoStr(errno)));
    }
  }
  progsAttached_ = true;
}