private void mergeUpgradePack(UpgradePack pack, List<UpgradePack> servicePacks) throws AmbariException {

    List<Grouping> originalGroups = pack.getAllGroups();
    Map<String, List<Grouping>> allGroupMap = new HashMap<>();
    for (Grouping group : originalGroups) {
      List<Grouping> list = new ArrayList<>();
      list.add(group);
      allGroupMap.put(group.name, list);
    }

    for (UpgradePack servicePack : servicePacks) {
      for (Grouping group : servicePack.getAllGroups()) {

        /*
         !!! special case where the service pack is targeted for any version.  When
         a service UP targets to run after another group, check to make sure that the
         base UP contains the group.
         */
        if (servicePack.isAllTarget() && !allGroupMap.keySet().contains(group.addAfterGroup)) {
          LOG.warn("Service Upgrade Pack specified after-group of {}, but that is not found in {}",
              group.addAfterGroup, StringUtils.join(allGroupMap.keySet(), ','));
          continue;
        }

        if (allGroupMap.containsKey(group.name)) {
          List<Grouping> list = allGroupMap.get(group.name);
          Grouping first = list.get(0);
          if (!first.getClass().equals(group.getClass())) {
            throw new AmbariException("Expected class: " + first.getClass() + " instead of " + group.getClass());
          }
          /* If the current group doesn't specify an "after entry" and the first group does
             then the current group should be added first.  The first group in the list should
             never be ordered relative to any other group. */
          if (group.addAfterGroupEntry == null && first.addAfterGroupEntry != null) {
            list.add(0, group);
          }
          else {
            list.add(group);
          }
        } else {
          List<Grouping> list = new ArrayList<>();
          list.add(group);
          allGroupMap.put(group.name, list);
        }
      }
    }

    Map<String, Grouping> mergedGroupMap = new HashMap<>();
    for (String key : allGroupMap.keySet()) {
      Iterator<Grouping> iterator = allGroupMap.get(key).iterator();
      Grouping group = iterator.next();
      if (iterator.hasNext()) {
        group.merge(iterator);
      }
      mergedGroupMap.put(key, group);
    }

    orderGroups(originalGroups, mergedGroupMap);
  }
Attempts to merge, into the stack upgrade, all the upgrades
for any service which specifies its own upgrade.
ambari-server/src/main/java/org/apache/ambari/server/stack/StackModule.java