Simple wrapper to interface with backing devs SysFS
542314
def _bcsys(dev, name, value=None, log_lvl=None, log_msg=None):
    '''
    
    '''
    return _sysfs_attr([_bcpath(dev), name], value, log_lvl, log_msg)
171770
def ssh_wrapper(opts, functions=None, context=None):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(
            opts,
            'wrapper',
            base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')),
        ),
        opts,
        tag='wrapper',
        pack={
            '__salt__': functions,
            '__grains__': opts.get('grains', {}),
            '__pillar__': opts.get('pillar', {}),
            '__context__': context,
            },
    )
738912
private static String wrapSystemId(String systemId) {
        if (systemId == null) {
            return "jstl:";
        } else if (UrlUtil.isAbsoluteUrl(systemId)) {
            return systemId;
        } else {
            return ("jstl:" + systemId);
        }
    }
945949
function setupSystemD (name, options, callback) {
  options.stdOut = (options.logDir && `${options.logDir}/${name}-out.log`) || null
  options.stdErr = (options.logDir && `${options.logDir}/${name}-err.log`) || null

  const filepath = `/etc/systemd/system/${name}.service`

  const script = systemdTemplate(options)

  if (options.dryRun) {
    console.log(script)
    return
  }

  console.log(`Installing service on: ${filepath}`)
  fs.exists(filepath, exists => {
    if(!exists) {
      fs.writeFile(filepath,script, err => {
        if (err) {
          callback(err)
          return
        }

        fs.chmod(filepath,'755', err => {
          if (err) {
            callback(err)
            return
          }

          let cmd = 'systemctl daemon-reload'
          console.log('Running %s...', cmd)
          exec(cmd, err => {
            callback(err, 'SystemD service registered succesfully')
          })
        })
      })
    } else {
      callback('Service already exists, please uninstall first')
    }
  })
}
388867
def main(argv=None, loop=SharedLoop):
    """"""

    if argv is None:
        argv = sys.argv[1:]

    list_parser = argparse.ArgumentParser(add_help=False)
    list_parser.add_argument('-l', '--list', action='store_true', help="List all known installed interfaces and devices and then exit")
    list_parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")

    parser = argparse.ArgumentParser(description="Serve acess to a virtual IOTile device using a virtual IOTile interface")

    parser.add_argument('interface', help="The name of the virtual device interface to use")
    parser.add_argument('device', help="The name of the virtual device to create")
    parser.add_argument('-c', '--config', help="An optional JSON config file with arguments for the interface and device")
    parser.add_argument('-l', '--list', action='store_true', help="List all known installed interfaces and devices and then exit")
    parser.add_argument('-n', '--scenario', help="Load a test scenario from the given file")
    parser.add_argument('-s', '--state', help="Load a given state into the device before starting to serve it.  Only works with emulated devices.")
    parser.add_argument('-d', '--dump', help="Dump the device's state when we exit the program.  Only works with emulated devices.")
    parser.add_argument('-t', '--track', help="Track all changes to the device's state.  Only works with emulated devices.")
    parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")

    args, _rest = list_parser.parse_known_args(argv)

    if args.list:
        configure_logging(args.verbose)

        reg = ComponentRegistry()
        print("Installed Device Servers:")
        for name, _iface in reg.load_extensions('iotile.device_server', class_filter=AbstractDeviceServer):
            print('- {}'.format(name))

        print("\nInstalled Virtual Devices:")
        for name, dev in reg.load_extensions('iotile.virtual_device', class_filter=VirtualIOTileDevice,
                                             product_name="virtual_device"):
            print('- {}: {}'.format(name, one_line_desc(dev)))

        return 0

    args = parser.parse_args(argv)

    configure_logging(args.verbose)

    config = {}
    if args.config is not None:
        with open(args.config, "r") as conf_file:
            config = json.load(conf_file)

    started = False
    device = None
    stop_immediately = args.interface == 'null'
    try:
        server = instantiate_interface(args.interface, config, loop)
        device = instantiate_device(args.device, config, loop)

        if args.state is not None:
            print("Loading device state from file %s" % args.state)
            device.load_state(args.state)

        if args.scenario is not None:
            print("Loading scenario from file %s" % args.scenario)

            with open(args.scenario, "r") as infile:
                scenario = json.load(infile)

            # load_metascenario expects a list of scenarios even when there is only one
            if isinstance(scenario, dict):
                scenario = [scenario]

            device.load_metascenario(scenario)

        if args.track is not None:
            print("Tracking all state changes to device")
            device.state_history.enable()

        adapter = VirtualDeviceAdapter(devices=[device], loop=loop)
        server.adapter = adapter

        loop.run_coroutine(adapter.start())

        try:
            loop.run_coroutine(server.start())
        except:
            loop.run_coroutine(adapter.stop())
            adapter = None
            raise

        started = True

        print("Starting to serve virtual IOTile device")

        if stop_immediately:
            return 0

        # We need to periodically process events that are queued up in the interface
        while True:
            time.sleep(0.5)

    except KeyboardInterrupt:
        print("Break received, cleanly exiting...")
    finally:
        if args.dump is not None and device is not None:
            print("Dumping final device state to %s" % args.dump)
            device.save_state(args.dump)

        if started:
            loop.run_coroutine(server.stop())
            loop.run_coroutine(adapter.stop())

        if args.track is not None and device is not None:
            print("Saving state history to file %s" % args.track)
            device.state_history.dump(args.track)

    return 0
825671
def _set_sysfs(self, fcp, target_wwpn, target_lun):
        """"""
        device = '0.0.%s' % fcp
        unit_add = "echo '%s' > " % target_lun
        unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\
                    % {'device': device, 'wwpn': target_wwpn}
        return unit_add
965123
def releaseInterface(self):
        """
        util.release_interface(self.dev, self.__claimed_interface)
        self.__claimed_interface = -1
350890
def frontend(ctx, dev, rebuild, no_install, build_type):
    """"""

    install_frontend(instance=ctx.obj['instance'],
                     forcerebuild=rebuild,
                     development=dev,
                     install=not no_install,
                     build_type=build_type)
484298
def cli(ctx, timeout, proxy, output, quiet, lyric, again):
    """"""
    ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again)
793681
def _IOC(cls, dir, op, structure=None):
        
        control = cls(dir, op, structure)

        def do(dev, **args):
            return control(dev, **args)
        return do
237538
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--log-level", default="INFO",
                        choices=logging._nameToLevel,
                        help="Logging verbosity.")
    subparsers = parser.add_subparsers(help="Commands", dest="command")

    def add_backend_args(p):
        p.add_argument("--backend", default=None, help="Backend to use.")
        p.add_argument("--args", default=None, help="Backend's arguments.")

    def add_index_args(p):
        p.add_argument("--username", default="",
                       help="Username for the Git repository with the index.")
        p.add_argument("--password", default="",
                       help="Password for the Git repository with the index.")
        p.add_argument("--index-repo", default=None,
                       help="Url of the remote Git repository.")
        p.add_argument("--cache", default=None,
                       help="Path to the folder where the Git repository will be cached.")
        p.add_argument("-s", "--signoff", action="store_true",
                       help="Add Signed-off-by line by the committer at the end of the commit log "
                            "message. The meaning of a signoff depends on the project, but it "
                            "typically certifies that committer has the rights to submit this work"
                            " under the same license and agrees to a Developer Certificate of "
                            "Origin (see http://developercertificate.org/ for more information).")

    def add_templates_args(p):
        p.add_argument(
            "--template-model",
            default=os.path.join(os.path.dirname(__file__), "templates/template_model.md.jinja2"),
            help="Path to the jinja2 template used in the index for the model.")
        p.add_argument(
            "--template-readme",
            default=os.path.join(os.path.dirname(__file__), "templates/template_readme.md.jinja2"),
            help="Path to the jinja2 template used in the index for the readme.")

    # ------------------------------------------------------------------------
    init_parser = subparsers.add_parser("init", help="Initialize the registry.")
    init_parser.set_defaults(handler=initialize_registry)
    init_parser.add_argument("-f", "--force", action="store_true",
                             help="Destructively initialize the registry.")
    add_index_args(init_parser)
    add_backend_args(init_parser)
    # ------------------------------------------------------------------------
    dump_parser = subparsers.add_parser(
        "dump", help="Print a brief information about the model to stdout.")
    dump_parser.set_defaults(handler=dump_model)
    dump_parser.add_argument(
        "input", help="Path to the model file, URL or UUID.")
    add_index_args(dump_parser)
    add_backend_args(dump_parser)
    # ------------------------------------------------------------------------
    install_parser = subparsers.add_parser(
        "install", help="Install the environment to run the model.")
    install_parser.set_defaults(handler=install_environment)
    install_parser.add_argument(
        "input", help="Path to the model file, URL or UUID.")
    install_parser.add_argument(
        "--reproduce", action="store_true",
        help="Ensure that training the model is possible.")
    install_parser.add_argument(
        "--pip", nargs="*", help="Additional arguments to pass to pip.")
    add_index_args(install_parser)
    add_backend_args(install_parser)
    # ------------------------------------------------------------------------
    publish_parser = subparsers.add_parser(
        "publish", help="Upload the model and update the registry.")
    publish_parser.set_defaults(handler=publish_model)
    publish_parser.add_argument(
        "model", help="The path to the model to publish.")
    publish_parser.add_argument(
        "--meta", default=os.path.join(os.path.dirname(__file__), "templates/template_meta.json"),
        help="Path to the JSON file which contains the additional metadata of the model.")
    publish_parser.add_argument("-d", "--update-default", action="store_true",
                                help="Set this model as the default one.")
    publish_parser.add_argument("-f", "--force", action="store_true",
                                help="Overwrite existing models.")
    add_index_args(publish_parser)
    add_backend_args(publish_parser)
    add_templates_args(publish_parser)
    # ------------------------------------------------------------------------
    list_parser = subparsers.add_parser(
        "list", help="Lists all the models in the registry.")
    list_parser.set_defaults(handler=list_models)
    add_index_args(list_parser)
    # ------------------------------------------------------------------------
    delete_parser = subparsers.add_parser("delete", help="Delete a model.")
    delete_parser.set_defaults(handler=delete_model)
    delete_parser.add_argument(
        "input", help="UUID of the model to be deleted.")
    add_index_args(delete_parser)
    add_backend_args(delete_parser)
    add_templates_args(delete_parser)
    # ------------------------------------------------------------------------
    args = parser.parse_args()
    args.log_level = logging._nameToLevel[args.log_level]
    slogging.setup(args.log_level, False)
    try:
        handler = args.handler
    except AttributeError:
        def print_usage(_):
            parser.print_usage()

        handler = print_usage
    return handler(args)
971415
def main_cli(ctx, verbose=False):
    
    sTime = time.time()
    if ctx.obj is None:  # Fix for bug (as of 3.0)
        # https://github.com/pallets/click/issues/888
        ctx.obj = {}
    ctx.obj['VERBOSE'] = verbose
    ctx.obj['STIME'] = sTime

    click.secho("Ontospy " + VERSION, fg='white')
    # click.secho("------------", fg='white')
    if not verbose and ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
811215
def show_backends(socket=DEFAULT_SOCKET_URL):
    '''
    
    '''
    ha_conn = _get_conn(socket)
    ha_cmd = haproxy.cmds.showBackends()
    return ha_conn.sendCmd(ha_cmd)
150115
private function _ide()
    {
        foreach ($this->readaixdata() as $line) {
            if (preg_match("/^[\*\+]\s\S+\s+\S+\s+(.*IDE.*)/", $line, $ar_buf)) {
                $dev = new HWDevice();
                $dev->setName(trim($ar_buf[1]));
                $this->sys->setIdeDevices($dev);
            }
        }
    }
828371
def build_interface(iface, iface_type, enabled, **settings):
    '''
    
    '''
    if __grains__['os'] == 'Fedora':
        if __grains__['osmajorrelease'] >= 18:
            rh_major = '7'
        else:
            rh_major = '6'
    else:
        rh_major = __grains__['osrelease'][:1]

    iface_type = iface_type.lower()

    if iface_type not in _IFACE_TYPES:
        _raise_error_iface(iface, iface_type, _IFACE_TYPES)

    if iface_type == 'slave':
        settings['slave'] = 'yes'
        if 'master' not in settings:
            msg = 'master is a required setting for slave interfaces'
            log.error(msg)
            raise AttributeError(msg)

    if iface_type == 'vlan':
        settings['vlan'] = 'yes'

    if iface_type == 'bridge':
        __salt__['pkg.install']('bridge-utils')

    if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']:
        opts = _parse_settings_eth(settings, iface_type, enabled, iface)
        try:
            template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major))
        except jinja2.exceptions.TemplateNotFound:
            log.error(
                'Could not load template rh%s_eth.jinja',
                rh_major
            )
            return ''
        ifcfg = template.render(opts)

    if 'test' in settings and settings['test']:
        return _read_temp(ifcfg)

    _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}')
    path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))

    return _read_file(path)
217397
def compatcallback(f):
    
    if getattr(click, '__version__', '0.0') >= '2.0':
        return f
    return update_wrapper(lambda ctx, value: f(ctx, None, value), f)
1226571
def cli(env, identifier):
    """"""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    instance = vsi.get_instance(vs_id)

    table = formatting.Table(['username', 'password'])
    for item in instance['operatingSystem']['passwords']:
        table.add_row([item['username'], item['password']])
    env.fout(table)