Convert topologies from GNS3 2.0.0 to 2.1

    Changes:
     * Remove startup_script_path from VPCS and base config file for IOU and Dynamips
191656
def _convert_2_0_0(topo, topo_path):
    
    topo["revision"] = 8

    for node in topo.get("topology", {}).get("nodes", []):
        if "properties" in node:
            if node["node_type"] == "vpcs":
                if "startup_script_path" in node["properties"]:
                    del node["properties"]["startup_script_path"]
                if "startup_script" in node["properties"]:
                    del node["properties"]["startup_script"]
            elif node["node_type"] == "dynamips" or node["node_type"] == "iou":
                if "startup_config" in node["properties"]:
                    del node["properties"]["startup_config"]
                if "private_config" in node["properties"]:
                    del node["properties"]["private_config"]
                if "startup_config_content" in node["properties"]:
                    del node["properties"]["startup_config_content"]
                if "private_config_content" in node["properties"]:
                    del node["properties"]["private_config_content"]
    return topo
209747
def _build_paths(venv=None):
    
    if venv:
        paths = venv.paths
    else:
        paths = sysconfig.get_paths()
    return {
        "prefix": sys.prefix if not venv else venv.venv_dir.as_posix(),
        "data": paths["data"],
        "scripts": paths["scripts"],
        "headers": paths["include"],
        "purelib": paths["purelib"],
        "platlib": paths["platlib"],
    }
1322185
def cli(env, **kwargs):
    

    mgr = SoftLayer.DedicatedHostManager(env.client)
    tables = []

    if not kwargs['flavor'] and not kwargs['datacenter']:
        options = mgr.get_create_options()

        # Datacenters
        dc_table = formatting.Table(['datacenter', 'value'])
        dc_table.sortby = 'value'
        for location in options['locations']:
            dc_table.add_row([location['name'], location['key']])
        tables.append(dc_table)

        dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
        dh_table.sortby = 'value'
        for item in options['dedicated_host']:
            dh_table.add_row([item['name'], item['key']])
        tables.append(dh_table)
    else:
        if kwargs['flavor'] is None or kwargs['datacenter'] is None:
            raise exceptions.ArgumentError('Both a flavor and datacenter need '
                                           'to be passed as arguments '
                                           'ex. slcli dh create-options -d '
                                           'ams01 -f '
                                           '56_CORES_X_242_RAM_X_1_4_TB')
        router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
        br_table = formatting.Table(
            ['Available Backend Routers'])
        for router in router_opt:
            br_table.add_row([router['hostname']])
        tables.append(br_table)

    env.fout(formatting.listing(tables, separator='\n'))
1321126
def _merge_system_configs(host_config, container_config, out_file=None):
    
    out = copy.deepcopy(container_config)
    for k, v in host_config.items():
        if k in set(["galaxy_config"]):
            out[k] = v
        elif k == "resources":
            for pname, resources in v.items():
                if not isinstance(resources, dict) and pname not in out[k]:
                    out[k][pname] = resources
                else:
                    for rname, rval in resources.items():
                        if (rname in set(["cores", "jvm_opts", "memory"])
                              or pname in set(["gatk", "mutect"])):
                            if pname not in out[k]:
                                out[k][pname] = {}
                            out[k][pname][rname] = rval
    # Ensure final file is relocatable by mapping back to reference directory
    if "bcbio_system" in out and ("galaxy_config" not in out or not os.path.isabs(out["galaxy_config"])):
        out["galaxy_config"] = os.path.normpath(os.path.join(os.path.dirname(out["bcbio_system"]),
                                                             os.pardir, "galaxy",
                                                             "universe_wsgi.ini"))
    if out_file:
        with open(out_file, "w") as out_handle:
            yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
    return out
1183115
def _format_vpc_config(self):
        '''
        
        '''
        if self._config.raw['vpc']:
            return {
                'SubnetIds': self._config.raw['vpc']['subnets'],
                'SecurityGroupIds': self._config.raw['vpc']['security_groups']
            }
        else:
            return {
                'SubnetIds': [],
                'SecurityGroupIds': [],
            }
713097
def _convert_2_0_0_alpha(topo, topo_path):
    
    topo["revision"] = 6
    for node in topo.get("topology", {}).get("nodes", []):
        if node.get("console_type") == "serial":
            node["console_type"] = "telnet"
        if node["node_type"] in ("vmware", "virtualbox"):
            prop = node.get("properties")
            if "enable_remote_console" in prop:
                del prop["enable_remote_console"]
    return topo
568422
def setup_argparse():
    
    parser = argparse.ArgumentParser(
        description='Convert old ini-style GNS3 topologies (<=0.8.7) to '
                    'the newer version 1+ JSON format')
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s ' + __version__)
    parser.add_argument('-n', '--name', help='Topology name (default uses the '
                                             'name of the old project '
                                             'directory)')
    parser.add_argument('-o', '--output', help='Output directory')
    parser.add_argument('topology', nargs='?', default='topology.net',
                        help='GNS3 .net topology file (default: topology.net)')
    parser.add_argument('--debug',
                        help='Enable debugging output',
                        action='store_true')
    parser.add_argument('-q', '--quiet',
                        help='Quiet-mode (no output to console)',
                        action='store_true')
    return parser
808254
def _addrs2nodes(addrs, G):
    
    for i, n in enumerate(G.nodes()):
        G.node[n]['addr'] = addrs[i]
655373
def _set_mtu_to_nics(self, conf):
        
        for dom_name, dom_spec in conf.get('domains', {}).items():
            for idx, nic in enumerate(dom_spec.get('nics', [])):
                net = self._get_net(conf, dom_name, nic)
                mtu = net.get('mtu', 1500)
                if mtu != 1500:
                    nic['mtu'] = mtu
584324
def start_new_hypervisor(self, working_dir=None):
        

        if not self._dynamips_path:
            self.find_dynamips()

        if not working_dir:
            working_dir = tempfile.gettempdir()

        # FIXME: hypervisor should always listen to 127.0.0.1
        # See https://github.com/GNS3/dynamips/issues/62
        server_config = self.config.get_section_config("Server")
        server_host = server_config.get("host")

        try:
            info = socket.getaddrinfo(server_host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
            if not info:
                raise DynamipsError("getaddrinfo returns an empty list on {}".format(server_host))
            for res in info:
                af, socktype, proto, _, sa = res
                # let the OS find an unused port for the Dynamips hypervisor
                with socket.socket(af, socktype, proto) as sock:
                    sock.bind(sa)
                    port = sock.getsockname()[1]
                    break
        except OSError as e:
            raise DynamipsError("Could not find free port for the Dynamips hypervisor: {}".format(e))

        port_manager = PortManager.instance()
        hypervisor = Hypervisor(self._dynamips_path, working_dir, server_host, port, port_manager.console_host)

        log.info("Creating new hypervisor {}:{} with working directory {}".format(hypervisor.host, hypervisor.port, working_dir))
        yield from hypervisor.start()
        log.info("Hypervisor {}:{} has successfully started".format(hypervisor.host, hypervisor.port))
        yield from hypervisor.connect()
        if parse_version(hypervisor.version) < parse_version('0.2.11'):
            raise DynamipsError("Dynamips version must be >= 0.2.11, detected version is {}".format(hypervisor.version))

        return hypervisor
1197029
def to_env_vars(self):
        

        env = {
            'hosts': self.hosts, 'network_interface_name': self.network_interface_name,
            'hps': self.hyperparameters, 'user_entry_point': self.user_entry_point,
            'framework_params': self.additional_framework_parameters,
            'resource_config': self.resource_config, 'input_data_config': self.input_data_config,
            'output_data_dir': self.output_data_dir,
            'channels': sorted(self.channel_input_dirs.keys()),
            'current_host': self.current_host, 'module_name': self.module_name,
            'log_level': self.log_level,
            'framework_module': self.framework_module, 'input_dir': self.input_dir,
            'input_config_dir': self.input_config_dir, 'output_dir': self.output_dir,
            'num_cpus': self.num_cpus,
            'num_gpus': self.num_gpus, 'model_dir': self.model_dir, 'module_dir': self.module_dir,
            'training_env': dict(self), 'user_args': self.to_cmd_args(),
            'output_intermediate_dir': self.output_intermediate_dir
        }

        for name, path in self.channel_input_dirs.items():
            env['channel_%s' % name] = path

        for key, value in self.hyperparameters.items():
            env['hp_%s' % key] = value

        return _mapping.to_env_vars(env)
290773
def cleanSystem(cls):
        
        resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
        os.environ.pop(cls.rootDirPathEnvName)
        shutil.rmtree(resourceRootDirPath)
        for k, v in list(os.environ.items()):
            if k.startswith(cls.resourceEnvNamePrefix):
                os.environ.pop(k)
61394
def replace_launch_config(self, scaling_group, launch_config_type,
            server_name, image, flavor, disk_config=None, metadata=None,
            personality=None, networks=None, load_balancers=None,
            key_name=None):
        
        return self._manager.replace_launch_config(scaling_group,
                launch_config_type, server_name, image, flavor,
                disk_config=disk_config, metadata=metadata,
                personality=personality, networks=networks,
                load_balancers=load_balancers, key_name=key_name)
960569
function normalizeConf (conf) {
  if (process.env.PROVIDER_URL) {
    conf.providerURL = process.env.PROVIDER_URL
  }

  if (process.env.WEBHOOK_URL) {
    conf.webhookURL = process.env.WEBHOOK_URL
  }

  if (process.env.AUTOSTART) {
    conf.autostart = yn(process.env.AUTOSTART)
  }

  if (process.env.PORT) {
    conf.port = Number(process.env.PORT)
  }

  conf.providerURL = conf.providerURL.replace(/\/+$/, '')
  if (!conf.webhookURL) {
    conf.webhookURL = `http://${ip.address()}:${conf.port}`
  }

  if (conf.autostart !== false) {
    conf.autostart = true
  }

  return conf
}
222656
def env(mounts):
    
    f_mounts = [m.strip("/") for m in mounts]

    root = local.path("/")

    ld_libs = [root / m / "lib" for m in f_mounts]
    ld_libs.extend([root / m / "lib64" for m in f_mounts])

    paths = [root / m / "bin" for m in f_mounts]
    paths.extend([root / m / "sbin" for m in f_mounts])
    paths.extend([root / m for m in f_mounts])
    return paths, ld_libs
1073384
function loadConfigGypi () {
    var configPath = path.resolve('build', 'config.gypi')
    fs.readFile(configPath, 'utf8', function (err, data) {
      if (err) {
        if (err.code == 'ENOENT') {
          callback(new Error('You must run `node-gyp configure` first!'))
        } else {
          callback(err)
        }
        return
      }
      config = JSON.parse(data.replace(/\#.+\n/, ''))

      // get the 'arch', 'buildType', and 'nodeDir' vars from the config
      buildType = config.target_defaults.default_configuration
      arch = config.variables.target_arch
      nodeDir = config.variables.nodedir

      if ('debug' in gyp.opts) {
        buildType = gyp.opts.debug ? 'Debug' : 'Release'
      }
      if (!buildType) {
        buildType = 'Release'
      }

      log.verbose('build type', buildType)
      log.verbose('architecture', arch)
      log.verbose('node dev dir', nodeDir)

      if (win) {
        findSolutionFile()
      } else {
        doWhich()
      }
    })
  }
442549
def map_vnics(vm):
        
        return {device.deviceInfo.label: device
                for device in vm.config.hardware.device
                if isinstance(device, vim.vm.device.VirtualEthernetCard)}