Extracts load balancing configs from a service config.
426012
@SuppressWarnings("unchecked")
  @VisibleForTesting
  public static List<Map<String, ?>> getLoadBalancingConfigsFromServiceConfig(
      Map<String, ?> serviceConfig) {
    /* schema as follows
    {
      "loadBalancingConfig": [
        {"xds" :
          {
            "balancerName": "balancer1",
            "childPolicy": [...],
            "fallbackPolicy": [...],
          }
        },
        {"round_robin": {}}
      ],
      "loadBalancingPolicy": "ROUND_ROBIN"  // The deprecated policy key
    }
    */
    List<Map<String, ?>> lbConfigs = new ArrayList<>();
    if (serviceConfig.containsKey(SERVICE_CONFIG_LOAD_BALANCING_CONFIG_KEY)) {
      List<?> configs = getList(serviceConfig, SERVICE_CONFIG_LOAD_BALANCING_CONFIG_KEY);
      for (Map<String, ?> config : checkObjectList(configs)) {
        lbConfigs.add(config);
      }
    }
    if (lbConfigs.isEmpty()) {
      // No LoadBalancingConfig found.  Fall back to the deprecated LoadBalancingPolicy
      if (serviceConfig.containsKey(SERVICE_CONFIG_LOAD_BALANCING_POLICY_KEY)) {
        // TODO(zhangkun83): check if this is null.
        String policy = getString(serviceConfig, SERVICE_CONFIG_LOAD_BALANCING_POLICY_KEY);
        // Convert the policy to a config, so that the caller can handle them in the same way.
        policy = policy.toLowerCase(Locale.ROOT);
        Map<String, ?> fakeConfig = Collections.singletonMap(policy, Collections.emptyMap());
        lbConfigs.add(fakeConfig);
      }
    }
    return Collections.unmodifiableList(lbConfigs);
  }
519547
def cli(env):
    """"""

    mgr = SoftLayer.LoadBalancerManager(env.client)

    table = formatting.Table(['price_id', 'capacity', 'description', 'price'])

    table.sortby = 'price'
    table.align['price'] = 'r'
    table.align['capacity'] = 'r'
    table.align['id'] = 'r'

    packages = mgr.get_lb_pkgs()

    for package in packages:
        table.add_row([
            package['prices'][0]['id'],
            package.get('capacity'),
            package['description'],
            '%.2f' % float(package['prices'][0]['recurringFee'])
        ])

    env.fout(table)
507231
def get_config(self, service, setting):
        
        try:
            return self.get_service(service)[setting]
        except KeyError:
            return getattr(self, setting + '_DEFAULT')
704660
def cli(env):
    """"""

    mgr = SoftLayer.LoadBalancerManager(env.client)

    hc_types = mgr.get_hc_types()
    table = formatting.KeyValueTable(['ID', 'Name'])
    table.align['ID'] = 'l'
    table.align['Name'] = 'l'
    table.sortby = 'ID'
    for hc_type in hc_types:
        table.add_row([hc_type['id'], hc_type['name']])

    env.fout(table)
711125
def extract_config(self):
        

        try:
            reply = yield from self._hypervisor.send('vm extract_config "{}"'.format(self._name))
        except DynamipsError:
            # for some reason Dynamips gets frozen when it does not find the magic number in the NVRAM file.
            return None, None
        reply = reply[0].rsplit(' ', 2)[-2:]
        startup_config = reply[0][1:-1]  # get statup-config and remove single quotes
        private_config = reply[1][1:-1]  # get private-config and remove single quotes
        return startup_config, private_config
446227
private List<String> loadBalanceSuites(List<ForkedJvmInfo> jvmInfo,
      TestsCollection testsCollection, List<SuiteBalancer> balancers) {
    
    // Order test suites identically for balancers.
    // and split into replicated and non-replicated suites.
    Map<Boolean,List<String>> partitioned = sortAndSplitReplicated(testsCollection.testClasses);

    Collection<String> replicated = partitioned.get(true);
    Collection<String> suites     = partitioned.get(false);

    final List<SuiteBalancer> balancersWithFallback = new ArrayList<>(balancers);
    balancersWithFallback.add(new RoundRobinBalancer());

    // Go through all the balancers, the first one to assign a suite wins.
    final List<String> remaining = new ArrayList<>(suites);
    Collections.sort(remaining);

    final Map<Integer,List<Assignment>> perJvmAssignments = new HashMap<>();
    for (ForkedJvmInfo si : jvmInfo) {
      perJvmAssignments.put(si.id, new ArrayList<Assignment>());
    }
    final int jvmCount = jvmInfo.size();
    for (SuiteBalancer balancer : balancersWithFallback) {
      balancer.setOwner(this);
      final List<Assignment> assignments =
          balancer.assign(
              Collections.unmodifiableCollection(remaining), jvmCount, masterSeed());

      for (Assignment e : assignments) {
        if (e == null) {
          throw new RuntimeException("Balancer must return non-null assignments.");
        }
        if (!remaining.remove(e.suiteName)) {
          throw new RuntimeException("Balancer must return suite name as a key: " + e.suiteName);
        }

        log(String.format(Locale.ROOT,
            "Assignment hint: J%-2d (cost %5d) %s (by %s)",
            e.slaveId,
            e.estimatedCost,
            e.suiteName,
            balancer.getClass().getSimpleName()), Project.MSG_VERBOSE);

        perJvmAssignments.get(e.slaveId).add(e);
      }
    }

    if (remaining.size() != 0) {
      throw new RuntimeException("Not all suites assigned?: " + remaining);
    }

    if (shuffleOnSlave) {
      // Shuffle suites on slaves so that the result is always the same wrt master seed
      // (sort first, then shuffle with a constant seed).
      for (List<Assignment> assignments : perJvmAssignments.values()) {
        Collections.sort(assignments);
        Collections.shuffle(assignments, new Random(this.masterSeed()));
      }
    }

    // Take a fraction of suites scheduled as last on each slave and move them to a common
    // job-stealing queue.
    List<SuiteHint> stealingQueueWithHints = new ArrayList<>();
    for (ForkedJvmInfo si : jvmInfo) {
      final List<Assignment> assignments = perJvmAssignments.get(si.id);
      int moveToCommon = (int) (assignments.size() * dynamicAssignmentRatio);

      if (moveToCommon > 0) {
        final List<Assignment> movedToCommon = 
            assignments.subList(assignments.size() - moveToCommon, assignments.size());
        for (Assignment a : movedToCommon) {
          stealingQueueWithHints.add(new SuiteHint(a.suiteName, a.estimatedCost));
        }
        movedToCommon.clear();
      }

      final ArrayList<String> slaveSuites = (si.testSuites = new ArrayList<>());
      for (Assignment a : assignments) {
        slaveSuites.add(a.suiteName);
      }
    }

    // Sort stealing queue according to descending cost.
    Collections.sort(stealingQueueWithHints, SuiteHint.DESCENDING_BY_WEIGHT);

    // Append all replicated suites to each forked JVM, AFTER we process the stealing queue
    // to enforce all replicated suites run on each bound JVM.
    if (!replicated.isEmpty()) {
      for (ForkedJvmInfo si : jvmInfo) {
        for (String suite : replicated) {
            si.testSuites.add(suite);
        }
        if (shuffleOnSlave) {
          // Shuffle suites on slaves so that the result is always the same wrt master seed
          // (sort first, then shuffle with a constant seed).
          Collections.shuffle(si.testSuites, new Random(this.masterSeed()));
        }
      }
    }

    // Dump scheduling information.
    for (ForkedJvmInfo si : jvmInfo) {
      log("Forked JVM J" + si.id + " assignments (after shuffle):", Project.MSG_VERBOSE);
      for (String suiteName : si.testSuites) {
        log("  " + suiteName, Project.MSG_VERBOSE);
      }
    }

    log("Stealing queue:", Project.MSG_VERBOSE);
    for (SuiteHint suiteHint : stealingQueueWithHints) {
      log("  " + suiteHint.suiteName + " " + suiteHint.cost, Project.MSG_VERBOSE);
    }

    List<String> stealingQueue = new ArrayList<>(stealingQueueWithHints.size());
    for (SuiteHint suiteHint : stealingQueueWithHints) {
      stealingQueue.add(suiteHint.suiteName);
    }
    return stealingQueue;
  }
617359
def _load_config():
    """"""
    fname = _get_config_fname()
    if fname is None or not op.isfile(fname):
        return dict()
    with open(fname, 'r') as fid:
        config = json.load(fid)
    return config
1255994
def get_launch_config(self, scaling_group):
        
        key_map = {
            "OS-DCF:diskConfig": "disk_config",
            "flavorRef": "flavor",
            "imageRef": "image",
        }
        uri = "/%s/%s/launch" % (self.uri_base, utils.get_id(scaling_group))
        resp, resp_body = self.api.method_get(uri)
        ret = {}
        data = resp_body.get("launchConfiguration")
        ret["type"] = data.get("type")
        args = data.get("args", {})
        ret["load_balancers"] = args.get("loadBalancers")
        for key, value in args.get("server", {}).items():
            norm_key = key_map.get(key, key)
            ret[norm_key] = value
        return ret
715365
def list_loadbalancers(self, retrieve_all=True, **_params):
        """"""
        return self.list('loadbalancers', self.lbaas_loadbalancers_path,
                         retrieve_all, **_params)
11775
def read_config(cls, configparser):
        """"""
        config = dict()
        section = cls.__name__
        option = "prefixes"
        if configparser.has_option(section, option):
            value = configparser.get(section, option)
            names = [x.strip().lower() for x in value.split(",")]
        else:
            names = []
        config[option] = names
        return config
492509
def parse_config(data: dict) -> dict:
    
    return {
        'email': data.get('email'),
        'family': data['family_id'],
        'samples': [{
            'id': sample_id,
            'type': analysis_type,
        } for sample_id, analysis_type in data['analysis_type'].items()],
        'config_path': data['config_file_analysis'],
        'is_dryrun': True if 'dry_run_all' in data else False,
        'log_path': data['log_file'],
        'out_dir': data['outdata_dir'],
        'priority': data['slurm_quality_of_service'],
        'sampleinfo_path': data['sample_info_file'],
    }
182372
def extract_formats(config_handle):
    
    configurations = dict(config_handle)
    formats = dict(configurations.get('formats', {}))
    return formats
1009362
def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options):
        """"""
        results = []

        #randomize parameter space to do pseudo load balancing
        parameter_space = list(parameter_space)
        random.shuffle(parameter_space)

        #split parameter space into chunks
        work_per_thread = int(numpy.ceil(len(parameter_space) / float(self.max_threads)))
        chunks = _chunk_list(parameter_space, work_per_thread)

        for chunk in chunks:

            chunked_result = self._run_chunk(chunk, kernel_options, device_options, tuning_options)

            results.append(lift(chunked_result))

        return gather(*results)
1322346
def _get_service_config(self):
        
        # Should work for windows, osx, and linux environments
        if not os.path.exists(self.config_path):
            try:
                os.makedirs(os.path.dirname(self.config_path))
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    raise

            return {}

        with open(self.config_path, 'r') as data:
            return json.load(data)
488221
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        load_balancing_rules = []
        for raw_content in properties.get("loadBalancingRules", []):
            resource = Resource.from_raw_data(raw_content)
            load_balancing_rules.append(resource)
        properties["loadBalancingRules"] = load_balancing_rules

        return super(Probes, cls).process_raw_data(raw_data)
1213355
def format_load_balancer_configuration(result):
    '''
    
    '''
    from collections import OrderedDict
    # Only display parameters that have content
    order_dict = OrderedDict()
    if result.private_ip_address is not None:
        order_dict['privateIpAddress'] = format_private_ip_address(result.private_ip_address)
    if result.public_ip_address_resource_id is not None:
        order_dict['publicIpAddressResourceId'] = result.public_ip_address_resource_id
    if result.load_balancer_resource_id is not None:
        order_dict['loadBalancerResourceId'] = result.load_balancer_resource_id
    if result.probe_port is not None:
        order_dict['probePort'] = result.probe_port
    if result.sql_virtual_machine_instances is not None:
        order_dict['sqlVirtualMachineInstances'] = result.sql_virtual_machine_instances

    return order_dict
863639
def cli(env):
    """"""
    mgr = SoftLayer.LoadBalancerManager(env.client)

    routing_methods = mgr.get_routing_methods()
    table = formatting.KeyValueTable(['ID', 'Name'])
    table.align['ID'] = 'l'
    table.align['Name'] = 'l'
    table.sortby = 'ID'
    for routing_method in routing_methods:
        table.add_row([routing_method['id'], routing_method['name']])

    env.fout(table)