Mesos源码分析(5): Mesos Master的启动之四

时间:2025-03-19 11:38:07

 

5. Create an instance of allocator.

 

代码如下

Mesos源码分析(5): Mesos Master的启动之四

 

Mesos源码中默认的Allocator,即HierarchicalDRFAllocator的位置在$MESOS_HOME/src/master/allocator/mesos/hierarchical.hpp,而DRF中对每个Framework排序的Sorter位于$MESOS_HOME/src/master/allocator/sorter/drf/sorter.cpp,可以查看其源码了解它的工作原理。

 

HierarchicalDRF的基本原理

 

如何作出offer分配的决定是由资源分配模块Allocator实现的,该模块存在于Master之中。资源分配模块确定Framework接受offer的顺序,与此同时,确保在资源利用最大化的条件下公平地共享资源。

由于Mesos为跨数据中心调度资源并且是异构的资源需求时,资源分配相比普通调度将会更加困难。因此Mesos采用了DRF(主导资源公平算法 Dominant Resource Fairness)

Framework拥有的全部资源类型份额中占最高百分比的就是Framework的主导份额。DRF算法会使用所有已注册的Framework来计算主导份额,以确保每个Framework能接收到其主导资源的公平份额。

 

举个例子

 

考虑一个9CPU,18GBRAM的系统,拥有两个用户,其中用户A运行的任务的需求向量为{1CPU, 4GB},用户B运行的任务的需求向量为{3CPU,1GB},用户可以执行尽量多的任务来使用系统的资源。

在上述方案中,A的每个任务消耗总cpu的1/9和总内存的2/9,所以A的dominant resource是内存;B的每个任务消耗总cpu的1/3和总内存的1/18,所以B的dominant resource为CPU。DRF会均衡用户的dominant shares,执行3个用户A的任务,执行2个用户B的任务。三个用户A的任务总共消耗了{3CPU,12GB},两个用户B的任务总共消耗了{6CPU,2GB};在这个分配中,每一个用户的dominant share是相等的,用户A获得了2/3的RAM,而用户B获得了2/3的CPU。

以上的这个分配可以用如下方式计算出来:x和y分别是用户A和用户B的分配任务的数目,那么用户A消耗了{xCPU,4xGB},用户B消耗了{3yCPU,yGB},在图三中用户A和用户B消耗了同等dominant resource;用户A的dominant share为4x/18,用户B的dominant share为3y/9。所以DRF分配可以通过求解以下的优化问题来得到:

 

max(x,y)     #(Maximize allocations)

    subject to

        x + 3y <= 9         #(CPU constraint)

        4x + y <= 18         #(Memory Constraint)

            2x/9 = y/3     #(Equalize dominant shares)

 

最后解出x=3以及y=2,因而用户A获得{3CPU,12GB},B得到{6CPU, 2GB}。

 

HierarchicalDRF核心算法实现

 

HierachicalDRF的实现在Src/main/allocator/mesos/hierarchical.cpp中

 

Mesos源码分析(5): Mesos Master的启动之四

 

不是每次把所有的资源都给所有的framework,而是根据资源分配算法,每个framework拿到的不同

 

  1. void HierarchicalAllocatorProcess::allocate(
  2.     const hashset<SlaveID>& slaveIds_)
  3. {
  4.   ++metrics.allocation_runs;
  5.   // Compute the offerable resources, per framework:
  6.   // (1) For reserved resources on the slave, allocate these to a
  7.   // framework having the corresponding role.
  8.   // (2) For unreserved resources on the slave, allocate these
  9.   // to a framework of any role.
  10.   hashmap<FrameworkID, hashmap<SlaveID, Resources>> offerable;
  11.   // NOTE: This function can operate on a small subset of slaves, we have to
  12.   // make sure that we don't assume cluster knowledge when summing resources
  13.   // from that set.
  14.   vector<SlaveID> slaveIds;
  15.   slaveIds.reserve(slaveIds_.size());
  16.   // Filter out non-whitelisted and deactivated slaves in order not to send
  17.   // offers for them.
  18.   foreach (const SlaveID& slaveId, slaveIds_) {
  19.     if (isWhitelisted(slaveId) && slaves[slaveId].activated) {
  20.       slaveIds.push_back(slaveId);
  21.     }
  22.   }
  23.   // Randomize the order in which slaves' resources are allocated.
  24.   //
  25.   // TODO(vinod): Implement a smarter sorting algorithm.
  26.   std::random_shuffle(slaveIds.begin(), slaveIds.end());
  27.   // Returns the __quantity__ of resources allocated to a quota role. Since we
  28.   // account for reservations and persistent volumes toward quota, we strip
  29.   // reservation and persistent volume related information for comparability.
  30.   // The result is used to determine whether a role's quota is satisfied, and
  31.   // also to determine how many resources the role would need in order to meet
  32.   // its quota.
  33.   //
  34.   // NOTE: Revocable resources are excluded in `quotaRoleSorter`.
  35.   auto getQuotaRoleAllocatedResources = [this](const
    string& role) {
  36.     CHECK(quotas.contains(role));
  37.     // NOTE: `allocationScalarQuantities` omits dynamic reservation and
  38.     // persistent volume info, but we additionally strip `role` here.
  39.     Resources resources;
  40.     foreach (Resource resource,
  41.              quotaRoleSorter->allocationScalarQuantities(role)) {
  42.       CHECK(!resource.has_reservation());
  43.       CHECK(!resource.has_disk());
  44.       resource.set_role("*");
  45.       resources += resource;
  46.     }
  47.     return resources;
  48.   };
  49.   // Quota comes first and fair share second. Here we process only those
  50.   // roles, for which quota is set (quota'ed roles). Such roles form a
  51.   // special allocation group with a dedicated sorter.
  52.   foreach (const SlaveID& slaveId, slaveIds) {
  53.     foreach (const
    string& role, quotaRoleSorter->sort()) {
  54.       CHECK(quotas.contains(role));
  55.       // If there are no active frameworks in this role, we do not
  56.       // need to do any allocations for this role.
  57.       if (!activeRoles.contains(role)) {
  58.         continue;
  59.       }
  60.       // Get the total quantity of resources allocated to a quota role. The
  61.       // value omits role, reservation, and persistence info.
  62.       Resources roleConsumedResources = getQuotaRoleAllocatedResources(role);
  63.       // If quota for the role is satisfied, we do not need to do any further
  64.       // allocations for this role, at least at this stage.
  65.       //
  66.       // TODO(alexr): Skipping satisfied roles is pessimistic. Better
  67.       // alternatives are:
  68.       // * A custom sorter that is aware of quotas and sorts accordingly.
  69.       // * Removing satisfied roles from the sorter.
  70.       if (roleConsumedResources.contains(quotas[role].info.guarantee())) {
  71.         continue;
  72.       }
  73.       // Fetch frameworks according to their fair share.
  74.       foreach (const
    string& frameworkId_, frameworkSorters[role]->sort()) {
  75.         FrameworkID frameworkId;
  76.         frameworkId.set_value(frameworkId_);
  77.         // If the framework has suppressed offers, ignore. The unallocated
  78.         // part of the quota will not be allocated to other roles.
  79.         if (frameworks[frameworkId].suppressed) {
  80.           continue;
  81.         }
  82.         // Only offer resources from slaves that have GPUs to
  83.         // frameworks that are capable of receiving GPUs.
  84.         // See MESOS-5634.
  85.         if (!frameworks[frameworkId].gpuAware &&
  86.             slaves[slaveId].total.gpus().getOrElse(0) > 0) {
  87.           continue;
  88.         }
  89.         // Calculate the currently available resources on the slave.
  90.         Resources available = slaves[slaveId].total - slaves[slaveId].allocated;
  91.         // The resources we offer are the unreserved resources as well as the
  92.         // reserved resources for this particular role. This is necessary to
  93.         // ensure that we don't offer resources that are reserved for another
  94.         // role.
  95.         //
  96.         // NOTE: Currently, frameworks are allowed to have '*' role.
  97.         // Calling reserved('*') returns an empty Resources object.
  98.         //
  99.         // Quota is satisfied from the available non-revocable resources on the
  100.         // agent. It's important that we include reserved resources here since
  101.         // reserved resources are accounted towards the quota guarantee. If we
  102.         // were to rely on stage 2 to offer them out, they would not be checked
  103.         // against the quota guarantee.
  104.         Resources resources =
  105.           (available.unreserved() + available.reserved(role)).nonRevocable();
  106.         // It is safe to break here, because all frameworks under a role would
  107.         // consider the same resources, so in case we don't have allocatable
  108.         // resources, we don't have to check for other frameworks under the
  109.         // same role. We only break out of the innermost loop, so the next step
  110.         // will use the same `slaveId`, but a different role.
  111.         //
  112.         // NOTE: The resources may not be allocatable here, but they can be
  113.         // accepted by one of the frameworks during the second allocation
  114.         // stage.
  115.         if (!allocatable(resources)) {
  116.           break;
  117.         }
  118.         // If the framework filters these resources, ignore. The unallocated
  119.         // part of the quota will not be allocated to other roles.
  120.         if (isFiltered(frameworkId, slaveId, resources)) {
  121.           continue;
  122.         }
  123.         VLOG(2) << "Allocating " << resources << " on agent " << slaveId
  124.                 << " to framework " << frameworkId
  125.                 << " as part of its role quota";
  126.         // NOTE: We perform "coarse-grained" allocation for quota'ed
  127.         // resources, which may lead to overcommitment of resources beyond
  128.         // quota. This is fine since quota currently represents a guarantee.
  129.         offerable[frameworkId][slaveId] += resources;
  130.         slaves[slaveId].allocated += resources;
  131.         // Resources allocated as part of the quota count towards the
  132.         // role's and the framework's fair share.
  133.         //
  134.         // NOTE: Revocable resources have already been excluded.
  135.         frameworkSorters[role]->add(slaveId, resources);
  136.         frameworkSorters[role]->allocated(frameworkId_, slaveId, resources);
  137.         roleSorter->allocated(role, slaveId, resources);
  138.         quotaRoleSorter->allocated(role, slaveId, resources);
  139.       }
  140.     }
  141.   }
  142.   // Calculate the total quantity of scalar resources (including revocable
  143.   // and reserved) that are available for allocation in the next round. We
  144.   // need this in order to ensure we do not over-allocate resources during
  145.   // the second stage.
  146.   //
  147.   // For performance reasons (MESOS-4833), this omits information about
  148.   // dynamic reservations or persistent volumes in the resources.
  149.   //
  150.   // NOTE: We use total cluster resources, and not just those based on the
  151.   // agents participating in the current allocation (i.e. provided as an
  152.   // argument to the `allocate()` call) so that frameworks in roles without
  153.   // quota are not unnecessarily deprived of resources.
  154.   Resources remainingClusterResources = roleSorter->totalScalarQuantities();
  155.   foreachkey (const
    string& role, activeRoles) {
  156.     remainingClusterResources -= roleSorter->allocationScalarQuantities(role);
  157.   }
  158.   // Frameworks in a quota'ed role may temporarily reject resources by
  159.   // filtering or suppressing offers. Hence quotas may not be fully allocated.
  160.   Resources unallocatedQuotaResources;
  161.   foreachpair (const
    string& name, const Quota& quota, quotas) {
  162.     // Compute the amount of quota that the role does not have allocated.
  163.     //
  164.     // NOTE: Revocable resources are excluded in `quotaRoleSorter`.
  165.     // NOTE: Only scalars are considered for quota.
  166.     Resources allocated = getQuotaRoleAllocatedResources(name);
  167.     const Resources required = quota.info.guarantee();
  168.     unallocatedQuotaResources += (required - allocated);
  169.   }
  170.   // Determine how many resources we may allocate during the next stage.
  171.   //
  172.   // NOTE: Resources for quota allocations are already accounted in
  173.   // `remainingClusterResources`.
  174.   remainingClusterResources -= unallocatedQuotaResources;
  175.   // To ensure we do not over-allocate resources during the second stage
  176.   // with all frameworks, we use 2 stopping criteria:
  177.   // * No available resources for the second stage left, i.e.
  178.   // `remainingClusterResources` - `allocatedStage2` is empty.
  179.   // * A potential offer will force the second stage to use more resources
  180.   // than available, i.e. `remainingClusterResources` does not contain
  181.   // (`allocatedStage2` + potential offer). In this case we skip this
  182.   // agent and continue to the next one.
  183.   //
  184.   // NOTE: Like `remainingClusterResources`, `allocatedStage2` omits
  185.   // information about dynamic reservations and persistent volumes for
  186.   // performance reasons. This invariant is preserved because we only add
  187.   // resources to it that have also had this metadata stripped from them
  188.   // (typically by using `Resources::createStrippedScalarQuantity`).
  189.   Resources allocatedStage2;
  190.   // At this point resources for quotas are allocated or accounted for.
  191.   // Proceed with allocating the remaining free pool.
  192.   foreach (const SlaveID& slaveId, slaveIds) {
  193.     // If there are no resources available for the second stage, stop.
  194.     if (!allocatable(remainingClusterResources - allocatedStage2)) {
  195.       break;
  196.     }
  197.     foreach (const
    string& role, roleSorter->sort()) {
  198.       foreach (const
    string& frameworkId_,
  199.                frameworkSorters[role]->sort()) {
  200.         FrameworkID frameworkId;
  201.         frameworkId.set_value(frameworkId_);
  202.         // If the framework has suppressed offers, ignore.
  203.         if (frameworks[frameworkId].suppressed) {
  204.           continue;
  205.         }
  206.         // Only offer resources from slaves that have GPUs to
  207.         // frameworks that are capable of receiving GPUs.
  208.         // See MESOS-5634.
  209.         if (!frameworks[frameworkId].gpuAware &&
  210.             slaves[slaveId].total.gpus().getOrElse(0) > 0) {
  211.           continue;
  212.         }
  213.         // Calculate the currently available resources on the slave.
  214.         Resources available = slaves[slaveId].total - slaves[slaveId].allocated;
  215.         // The resources we offer are the unreserved resources as well as the
  216.         // reserved resources for this particular role. This is necessary to
  217.         // ensure that we don't offer resources that are reserved for another
  218.         // role.
  219.         //
  220.         // NOTE: Currently, frameworks are allowed to have '*' role.
  221.         // Calling reserved('*') returns an empty Resources object.
  222.         //
  223.         // NOTE: We do not offer roles with quota any more non-revocable
  224.         // resources once their quota is satisfied. However, note that this is
  225.         // not strictly true due to the coarse-grained nature (per agent) of the
  226.         // allocation algorithm in stage 1.
  227.         //
  228.         // TODO(mpark): Offer unreserved resources as revocable beyond quota.
  229.         Resources resources = available.reserved(role);
  230.         if (!quotas.contains(role)) {
  231.           resources += available.unreserved();
  232.         }
  233.         // It is safe to break here, because all frameworks under a role would
  234.         // consider the same resources, so in case we don't have allocatable
  235.         // resources, we don't have to check for other frameworks under the
  236.         // same role. We only break out of the innermost loop, so the next step
  237.         // will use the same slaveId, but a different role.
  238.         //
  239.         // The difference to the second `allocatable` check is that here we also
  240.         // check for revocable resources, which can be disabled on a per frame-
  241.         // work basis, which requires us to go through all frameworks in case we
  242.         // have allocatable revocable resources.
  243.         if (!allocatable(resources)) {
  244.           break;
  245.         }
  246.         // Remove revocable resources if the framework has not opted for them.
  247.         if (!frameworks[frameworkId].revocable) {
  248.           resources = resources.nonRevocable();
  249.         }
  250.         // If the resources are not allocatable, ignore. We can not break
  251.         // here, because another framework under the same role could accept
  252.         // revocable resources and breaking would skip all other frameworks.
  253.         if (!allocatable(resources)) {
  254.           continue;
  255.         }
  256.         // If the framework filters these resources, ignore.
  257.         if (isFiltered(frameworkId, slaveId, resources)) {
  258.           continue;
  259.         }
  260.         // If the offer generated by `resources` would force the second
  261.         // stage to use more than `remainingClusterResources`, move along.
  262.         // We do not terminate early, as offers generated further in the
  263.         // loop may be small enough to fit within `remainingClusterResources`.
  264.         const Resources scalarQuantity =
  265.           resources.createStrippedScalarQuantity();
  266.         if (!remainingClusterResources.contains(
  267.                 allocatedStage2 + scalarQuantity)) {
  268.           continue;
  269.         }
  270.         VLOG(2) << "Allocating " << resources << " on agent " << slaveId
  271.                 << " to framework " << frameworkId;
  272.         // NOTE: We perform "coarse-grained" allocation, meaning that we always
  273.         // allocate the entire remaining slave resources to a single framework.
  274.         //
  275.         // NOTE: We may have already allocated some resources on the current
  276.         // agent as part of quota.
  277.         offerable[frameworkId][slaveId] += resources;
  278.         allocatedStage2 += scalarQuantity;
  279.         slaves[slaveId].allocated += resources;
  280.         frameworkSorters[role]->add(slaveId, resources);
  281.         frameworkSorters[role]->allocated(frameworkId_, slaveId, resources);
  282.         roleSorter->allocated(role, slaveId, resources);
  283.         if (quotas.contains(role)) {
  284.           // See comment at `quotaRoleSorter` declaration regarding
  285.           // non-revocable.
  286.           quotaRoleSorter->allocated(role, slaveId, resources.nonRevocable());
  287.         }
  288.       }
  289.     }
  290.   }
  291.   if (offerable.empty()) {
  292.     VLOG(1) << "No allocations performed";
  293.   } else {
  294.     // Now offer the resources to each framework.
  295.     foreachkey (const FrameworkID& frameworkId, offerable) {
  296.       offerCallback(frameworkId, offerable[frameworkId]);
  297.     }
  298.   }
  299.   // NOTE: For now, we implement maintenance inverse offers within the
  300.   // allocator. We leverage the existing timer/cycle of offers to also do any
  301.   // "deallocation" (inverse offers) necessary to satisfy maintenance needs.
  302.   deallocate(slaveIds_);
  303. }

 

上面这段算法非常复杂,概况来说调用了三个Sorter,对所有的Framework进行排序,哪个先得到资源,哪个后得到资源。

 

在src/master/allocator/mesos/hierarchical.hpp中,有对三个重要的sorter的定义和注释,可以帮助了解sorter的逻辑。

 

Mesos源码分析(5): Mesos Master的启动之四

 

Mesos源码分析(5): Mesos Master的启动之四

 

Mesos源码分析(5): Mesos Master的启动之四

 

 

总的来说分两大步:

  • 先保证有quota的role
  • 然后其他的资源没有quota的再分

在每一步Hierachical的意思是两层排序

  • 一层是按照role排序
  • 第二层是相同的role的不同Framework排序

每一层的排序都是按照计算的share进行排序来先给谁,再给谁

 

在src/master/allocator/sorter/drf/sorter.cpp中

Mesos源码分析(5): Mesos Master的启动之四

 

 

  1. double DRFSorter::calculateShare(const
    string& name)
  2. {
  3.   double share = 0.0;
  4.   // TODO(benh): This implementation of "dominant resource fairness"
  5.   // currently does not take into account resources that are not
  6.   // scalars.
  7.   foreach (const
    string& scalar, total_.scalarQuantities.names()) {
  8.     // Filter out the resources excluded from fair sharing.
  9.     if (fairnessExcludeResourceNames.isSome() &&
  10.         fairnessExcludeResourceNames->count(scalar) > 0) {
  11.       continue;
  12.     }
  13.     // We collect the scalar accumulated total value from the
  14.     // `Resources` object.
  15.     //
  16.     // NOTE: Although in principle scalar resources may be spread
  17.     // across multiple `Resource` objects (e.g., persistent volumes),
  18.     // we currently strip persistence and reservation metadata from
  19.     // the resources in `scalarQuantities`.
  20.     Option<Value::Scalar> __total =
  21.       total_.scalarQuantities.get<Value::Scalar>(scalar);
  22.     CHECK_SOME(__total);
  23.     const
    double _total = __total.get().value();
  24.     if (_total > 0.0) {
  25.       double allocation = 0.0;
  26.       // We collect the scalar accumulated allocation value from the
  27.       // `Resources` object.
  28.       //
  29.       // NOTE: Although in principle scalar resources may be spread
  30.       // across multiple `Resource` objects (e.g., persistent volumes),
  31.       // we currently strip persistence and reservation metadata from
  32.       // the resources in `scalarQuantities`.
  33.       Option<Value::Scalar> _allocation =
  34.         allocations[name].scalarQuantities.get<Value::Scalar>(scalar);
  35.       if (_allocation.isSome()) {
  36.         allocation = _allocation.get().value();
  37.       }
  38.       share = std::max(share, allocation / _total);
  39.     }
  40.   }
  41.   return share / weights[name];
  42. }

 

 

Quota, Reservation, Role, Weight

 

  • 每个Framework可以有Role,既用于权限,也用于资源分配
  • 可以给某个role在offerResources的时候回复Offer::Operation::RESERVE,来预订某台slave上面的资源。Reservation是很具体的,具体到哪台机器的多少资源属于哪个Role
  • Quota是每个Role的最小保证量,但是不具体到某个节点,而是在整个集群中保证有这么多就行了。
  • Reserved资源也算在Quota里面。
  • 不同的Role之间可以有Weight

 

最后将resource交给每一个Framework

在allocate函数的最后,依次调用offerCallback来讲resource分配给每一个Framework

Mesos源码分析(5): Mesos Master的启动之四

 

Mesos源码分析(5): Mesos Master的启动之四

 

那offerCallback函数是什么时候注册进来的呢?

 

Mesos源码分析(5): Mesos Master的启动之四

 

 

在Allocator的initialize函数中,OfferCallback被注册尽量,并且没过一段时间执行一次。

 

在Allocator初始化的时候,最后定义每allocationInterval运行一次

offerCallback是注册进来的函数,请记住。

 

6. flags.registry == "in_memory" or flags.registry == "replicated_log" 信息存储在内存,zk,本地文件夹

 

7. 选举和检测谁是Leader的对象初始化

 

Try<MasterContender*> contender_ = MasterContender::create(zk, flags.master_contender);

Try<MasterDetector*> detector_ = MasterDetector::create(zk, flags.master_detector);

 

8. 生成Master对象,启动Master线程

 

Mesos源码分析(5): Mesos Master的启动之四