--- RegistryClientV2 
Create a new Docker Registry V2 client for a particular repository.

@param opts.insecure {Boolean} Optional. Default false. Set to true
to *not* fail on an invalid or self-signed server certificate.
... TODO: lots more to document
1410
function RegistryClientV2(opts) {
    var self = this;
    assert.object(opts, 'opts');
    // One of `opts.name` or `opts.repo`.
    assert.ok((opts.name || opts.repo) && !(opts.name && opts.repo),
        'exactly one of opts.name or opts.repo must be given');
    if (opts.name) {
        assert.string(opts.name, 'opts.name');
    } else {
        assert.object(opts.repo, 'opts.repo');
    }
    assert.optionalObject(opts.log, 'opts.log');
    assert.optionalString(opts.username, 'opts.username');
    if (opts.username) {
        assert.string(opts.password,
            'opts.password required if username given');
    } else {
        assert.optionalString(opts.password, 'opts.password');
    }
    assert.optionalString(opts.token, 'opts.token');  // for Bearer auth
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.scheme, 'opts.scheme');
    assert.optionalBool(opts.acceptManifestLists, 'opts.acceptManifestLists');
    assert.optionalNumber(opts.maxSchemaVersion, 'opts.maxSchemaVersion');
    // TODO: options to control the trust db for CA verification
    // TODO add passing through other restify options: userAgent, ...
    // Restify/Node HTTP client options.
    assert.optionalBool(opts.agent, 'opts.agent');
    assert.optionalString(opts.userAgent, 'opts.userAgent');

    this.log = _createLogger(opts.log);

    this.insecure = Boolean(opts.insecure);
    if (opts.name) {
        this.repo = common.parseRepo(opts.name);
    } else {
        this.repo = common.deepObjCopy(opts.repo);
    }
    if (opts.scheme) {
        this.repo.index.scheme = opts.scheme;
    } else if (!this.repo.index.scheme &&
        common.isLocalhost(this.repo.index.name))
    {
        // Per docker.git:registry/config.go#NewServiceConfig we special
        // case localhost to allow HTTP. Note that this lib doesn't do
        // the "try HTTPS, then fallback to HTTP if allowed" thing that
        // Docker-docker does, we'll just prefer HTTP for localhost.
        this.repo.index.scheme = 'http';
    }

    this.acceptManifestLists = opts.acceptManifestLists || false;
    this.maxSchemaVersion = opts.maxSchemaVersion || 1;
    this.username = opts.username;
    this.password = opts.password;
    this._loggedIn = false;
    this._loggedInScope = null; // Keeps track of the login type.
    this._authInfo = null;
    this._headers = {};

    _setAuthHeaderFromAuthInfo(this._headers, {
        token: opts.token,
        username: opts.username,
        password: opts.password
    });

    // XXX relevant for v2?
    //this._cookieJar = new tough.CookieJar();

    if (this.repo.index.official) {  // v1
        this._url = DEFAULT_V2_REGISTRY;
    } else {
        this._url = common.urlFromIndex(this.repo.index);
    }
    this.log.trace({url: this._url}, 'RegistryClientV2 url');

    this._commonHttpClientOpts = {
        log: this.log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !this.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    };
    this._clientsToClose = [];

    Object.defineProperty(this, '_api', {
        get: function () {
            if (self.__api === undefined) {
                self.__api = new DockerJsonClient(common.objMerge({
                    url: self._url
                }, self._commonHttpClientOpts));
                self._clientsToClose.push(self.__api);
            }
            return this.__api;
        }
    });

    Object.defineProperty(this, '_httpapi', {
        get: function () {
            if (self.__httpapi === undefined) {
                self.__httpapi = new restifyClients.HttpClient(common.objMerge({
                    url: self._url
                }, self._commonHttpClientOpts));
                self._clientsToClose.push(self.__httpapi);
            }
            return this.__httpapi;
        }
    });
}
810810
@Override
    protected AmazonS3Encryption build(AwsSyncClientParams clientParams) {
        return new AmazonS3EncryptionClient(
                new AmazonS3EncryptionClientParamsWrapper(clientParams,
                        resolveS3ClientOptions(),
                        encryptionMaterials,
                        cryptoConfig != null ? cryptoConfig : new CryptoConfiguration(),
                        kms));
    }
402394
public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException {
		synchronized(registryCache) {
			Integer portObj = port;
			Registry registry = registryCache.get(portObj);
			if(registry==null) {
				registry = LocateRegistry.createRegistry(port, csf, ssf);
				registryCache.put(portObj, registry);
			}
			return registry;
		}
	}
353608
function(app, opts) {
  opts.context = app;
  opts.routeContext = app;
  if(!!opts.rpcClient) {
    return opts.rpcClient.create(opts);
  } else {
    return Client.create(opts);
  }
}
1092221
function() {
  var split;
  var opts = {};

  if (process.env.DOCKER_HOST) {
    split = /tcp:\/\/([0-9.]+):([0-9]+)/g.exec(process.env.DOCKER_HOST);

    if (process.env.DOCKER_TLS_VERIFY === '1') {
      opts.protocol = 'https';
    }
    else {
      opts.protocol = 'http';
    }

    opts.host = split[1];

    if (process.env.DOCKER_CERT_PATH) {
      opts.ca = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));
      opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));
      opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));
    }

    opts.port = split[2];
  }
  else {
    opts.socketPath = '/var/run/docker.sock';
  }

  return new Docker(opts);
}
233158
private com.github.dockerjava.api.DockerClient createDockerClient() {
        return DockerClientImpl.getInstance(getDockerClientConfig())
                .withDockerCmdExecFactory(new JerseyDockerCmdExecFactory());
    }
234097
@SuppressWarnings("unchecked")
    public static ClientServerEndpointBuilder<DockerClientBuilder, DockerClientBuilder> docker() {
        return new ClientServerEndpointBuilder(new DockerClientBuilder(), new DockerClientBuilder()) {
            @Override
            public EndpointBuilder<? extends Endpoint> server() {
                throw new UnsupportedOperationException("Citrus Docker stack has no support for server implementation");
            }
        };
    }
567642
func insecureRegisterClient(params RegisterParams) (*Client, error) {
	tlsConfig := utils.TLSConfig(params.CipherSuites)

	cert, err := readCA(params)
	if err != nil && !trace.IsNotFound(err) {
		return nil, trace.Wrap(err)
	}

	// If no CA was found, then create a insecure connection to the Auth Server,
	// otherwise use the CA on disk to validate the Auth Server.
	if trace.IsNotFound(err) {
		tlsConfig.InsecureSkipVerify = true

		log.Warnf("Joining cluster without validating the identity of the Auth " +
			"Server. This may open you up to a Man-In-The-Middle (MITM) attack if an " +
			"attacker can gain privileged network access. To remedy this, use the CA pin " +
			"value provided when join token was generated to validate the identity of " +
			"the Auth Server.")
	} else {
		certPool := x509.NewCertPool()
		certPool.AddCert(cert)
		tlsConfig.RootCAs = certPool

		log.Infof("Joining remote cluster %v, validating connection with certificate on disk.", cert.Subject.CommonName)
	}

	client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return client, nil
}
1075259
function(opts) {
  var self = this;

  opts = _.defaults(opts || {}, {
    clientId:         null,
    clientSecret:     null,
    redirectUri:      null,
    authEndpoint:     AUTH_ENDPOINT,
    testAuthEndpoint: TEST_AUTH_ENDPOINT,
    loginUri:         LOGIN_URI,
    testLoginUri:     TEST_LOGIN_URI,
    apiVersion:       38,
    environment:      'production',
    mode:             'multi',
    gzip:             false,
    autoRefresh:      false,
    onRefresh:        undefined,
    timeout:          undefined,
    oauth:            undefined,
    username:         undefined,
    password:         undefined,
    securityToken:    undefined
  });

  // convert option values
  opts.apiVersion = opts.apiVersion.toString().toLowerCase().replace('v', '').replace('.0', '');
  opts.environment = opts.environment.toLowerCase();
  opts.mode = opts.mode.toLowerCase();

  self = _.assign(this, opts);

  // validate options
  if(!_.isString(this.clientId)) throw new Error('invalid or missing clientId');
  if(!_.isString(this.authEndpoint)) throw new Error('invalid or missing authEndpoint');
  if(!_.isString(this.testAuthEndpoint)) throw new Error('invalid or missing testAuthEndpoint');
  if(!_.isString(this.loginUri)) throw new Error('invalid or missing loginUri');
  if(!_.isString(this.testLoginUri)) throw new Error('invalid or missing testLoginUri');
  if(!_.isBoolean(this.gzip)) throw new Error('gzip must be a boolean');
  if(!_.isString(this.environment) || _.indexOf(ENVS, this.environment) === -1) {
    throw new Error('invalid environment, only ' + ENVS.join(' and ') + ' are allowed');
  }
  if(!_.isString(this.mode) || _.indexOf(MODES, this.mode) === -1) {
    throw new Error('invalid mode, only ' + MODES.join(' and ') + ' are allowed');
  }
  if(!_.isString(this.redirectUri) && this.mode != 'single') {
    throw new Error('invalid or missing redirectUri');
  }
  if(this.onRefresh && !_.isFunction(this.onRefresh)) throw new Error('onRefresh must be a function');
  if(this.timeout && !_.isNumber(this.timeout)) throw new Error('timeout must be a number');

  // parse api version
  try {
    this.apiVersion = 'v' + parseInt(this.apiVersion, 10) + '.0';
  } catch (err) {
    throw new Error('invalid apiVersion number');
  }

  // parse timeout into integer in case it's a floating point.
  this.timeout = parseInt(this.timeout, 10);

  // load plugins
  if(opts.plugins && _.isArray(opts.plugins)) {
    opts.plugins.forEach(function(pname) {
      if(!plugins[pname]) throw new Error('plugin ' + pname + ' not found');
      // clone the object
      self[pname] = _.clone(plugins[pname]._fns);

      // now bind to the connection object
      _.forOwn(self[pname], function(fn, key) {
        self[pname][key] = _.bind(self[pname][key], self);
      });
    });
  }
}
752906
function Registry(opt_options) {
  if (!(this instanceof Registry)) {
    return new Registry(opt_options);
  }
  opt_options = opt_options || {};

  this.breakOnError = opt_options.breakOnError || false;
  this.depth = opt_options.depth || 10;

  // regex to match "$schema.*"
  this._match = /"\$id:[a-z0-9_-]*"/ig;
  // regex to escape strings for usage as regex
  this._escape = /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;

  this.schemas = {};
}
674232
func getRegistryClient(clientConfig *restclient.Config, registryCABundle string, registryInsecure bool) (*http.Client, error) {
	var (
		err                      error
		cadata                   []byte
		registryCABundleIncluded = false
		token                    = clientConfig.BearerToken
	)

	if len(token) == 0 {
		return nil, errNoToken
	}

	if len(registryCABundle) > 0 {
		cadata, err = ioutil.ReadFile(registryCABundle)
		if err != nil {
			return nil, fmt.Errorf("failed to read registry ca bundle: %v", err)
		}
	}

	// copy the config
	registryClientConfig := *clientConfig
	registryClientConfig.TLSClientConfig.Insecure = registryInsecure

	// zero out everything we don't want to use
	registryClientConfig.BearerToken = ""
	registryClientConfig.CertFile = ""
	registryClientConfig.CertData = []byte{}
	registryClientConfig.KeyFile = ""
	registryClientConfig.KeyData = []byte{}

	if registryInsecure {
		// it's not allowed to specify insecure flag together with CAs
		registryClientConfig.CAFile = ""
		registryClientConfig.CAData = []byte{}

	} else if len(cadata) > 0 && len(registryClientConfig.CAData) == 0 {
		// If given, we want to append cabundle to the resulting tlsConfig.RootCAs. However, if we
		// leave CAData unset, tlsConfig may not be created. We could append the caBundle to the
		// CAData here directly if we were ok doing a binary magic, which is not the case.
		registryClientConfig.CAData = cadata
		registryCABundleIncluded = true
	}

	// we have to set a username to something for the Docker login but it's not actually used
	registryClientConfig.Username = "unused"

	// set the "password" to be the token
	registryClientConfig.Password = token

	tlsConfig, err := restclient.TLSConfigFor(&registryClientConfig)
	if err != nil {
		return nil, err
	}

	// Add the CA bundle to the client config's CA roots if provided and we haven't done that already.
	// FIXME: handle registryCABundle on one place
	if tlsConfig != nil && len(cadata) > 0 && !registryCABundleIncluded && !registryInsecure {
		if tlsConfig.RootCAs == nil {
			tlsConfig.RootCAs = x509.NewCertPool()
		}
		tlsConfig.RootCAs.AppendCertsFromPEM(cadata)
	}

	transport := knet.SetTransportDefaults(&http.Transport{
		TLSClientConfig: tlsConfig,
	})

	wrappedTransport, err := restclient.HTTPWrappersForConfig(&registryClientConfig, transport)
	if err != nil {
		return nil, err
	}

	return &http.Client{
		Transport: wrappedTransport,
	}, nil
}
440856
function createCsrSubject(opts) {
    const data = {
        C: opts.country,
        ST: opts.state,
        L: opts.locality,
        O: opts.organization,
        OU: opts.organizationUnit,
        CN: opts.commonName || 'localhost',
        emailAddress: opts.emailAddress
    };

    return Object.entries(data).map(([key, value]) => {
        value = (value || '').replace(/[^\w .*,@'-]+/g, ' ').trim();
        return value ? `/${key}=${value}` : '';
    }).join('');
}
1173646
function (opts, cb) {
            var self = this;
            cb = cb || function () {
                };
            opts = opts || {};
            var url = this._geturi(opts);
            this.client.get({
                uri: url
            }, cb);
        }
1190456
function _getToken(opts, cb) {
    assert.string(opts.indexName, 'opts.indexName'); // used for error messages
    assert.string(opts.realm, 'opts.realm');
    assert.optionalString(opts.service, 'opts.service');
    assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    // HTTP client opts:
    assert.object(opts.log, 'opts.log');
    assert.optionalObject(opts.agent, 'opts.agent');
    // assert.optional object or bool(opts.proxy, 'opts.proxy');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    var log = opts.log;

    // - add https:// prefix (or http) if none on 'realm'
    var tokenUrl = opts.realm;
    var match = /^(\w+):\/\//.exec(tokenUrl);
    if (!match) {
        tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
    } else if (['http', 'https'].indexOf(match[1]) === -1) {
        return cb(new Error(fmt('unsupported scheme for ' +
            'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
    }

    // - GET $realm
    //      ?service=$service
    //      (&scope=$scope)*
    //      (&account=$username)
    //   Authorization: Basic ...
    var headers = {};
    var query = {};
    if (opts.service) {
        query.service = opts.service;
    }
    if (opts.scopes && opts.scopes.length) {
        query.scope = opts.scopes;  // intentionally singular 'scope'
    }

    if (opts.username) {
        query.account = opts.username;
        _setAuthHeaderFromAuthInfo(headers, {
            username: opts.username,
            password: opts.password
        });
    }
    if (Object.keys(query).length) {
        tokenUrl += '?' + querystring.stringify(query);
    }
    log.trace({tokenUrl: tokenUrl}, '_getToken: url');

    var parsedUrl = mod_url.parse(tokenUrl);
    var client = new DockerJsonClient({
        url: parsedUrl.protocol + '//' + parsedUrl.host,
        log: log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !opts.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    });
    client.get({
        path: parsedUrl.path,
        headers: headers
    }, function (err, req, res, body) {
        client.close();
        if (err) {
            if (err.statusCode === 401) {
                // Convert *all* 401 errors to use a generic error constructor
                // with a simple error message.
                var errMsg = _getRegistryErrorMessage(err);
                return cb(new errors.UnauthorizedError(errMsg));
            }
            return cb(err);
        } else if (!body.token) {
            return cb(new errors.UnauthorizedError(err, 'authorization ' +
                'server did not include a token in the response'));
        }
        cb(null, body.token);
    });
}
795157
def adjust_for_registry_api_versions(self):
        
        versions = self.spec.registry_api_versions.value

        if 'v2' not in versions:
            raise OsbsValidationException('v1-only docker registry API is not supported')

        try:
            push_conf = self.dj.dock_json_get_plugin_conf('postbuild_plugins',
                                                          'tag_and_push')
            tag_and_push_registries = push_conf['args']['registries']
        except (KeyError, IndexError):
            tag_and_push_registries = {}

        if 'v1' not in versions:
            # Remove v1-only plugins
            for phase, name in [('postbuild_plugins', 'pulp_push')]:
                logger.info("removing v1-only plugin: %s", name)
                self.dj.remove_plugin(phase, name)

            # remove extra tag_and_push config
            self.remove_tag_and_push_registries(tag_and_push_registries, 'v1')

        # Remove 'version' from tag_and_push plugin config as it's no
        # longer needed
        for regdict in tag_and_push_registries.values():
            if 'version' in regdict:
                del regdict['version']
324656
function Client(svc, opts) {
  opts = opts || {};
  events.EventEmitter.call(this);

  // We have to suffix all client properties to be safe, since the message
  // names aren't prefixed with clients (unlike servers).
  this._svc$ = svc;
  this._channels$ = []; // Active channels.
  this._fns$ = []; // Middleware functions.

  this._buffering$ = !!opts.buffering;
  this._cache$ = opts.cache || {}; // For backwards compatibility.
  this._policy$ = opts.channelPolicy;
  this._strict$ = !!opts.strictTypes;
  this._timeout$ = utils.getOption(opts, 'timeout', 10000);

  if (opts.remoteProtocols) {
    insertRemoteProtocols(this._cache$, opts.remoteProtocols, svc, true);
  }

  this._svc$.messages.forEach(function (msg) {
    this[msg.name] = this._createMessageHandler$(msg);
  }, this);
}
986705
function ServerNode(opts) {

    opts = opts || {};

    /**
     * ### ServerNode.defaultConfDir
     *
     * The directory of execution of the server
     */
    this.rootDir = path.resolve(__dirname, '..');


    // Creates the http or https server (must be after rootDir is set).
    this.createServer(opts);

    /**
     * ### ServerNode.http
     *
     * The server
     */
    this.http = exp;

    /**
     * ### ServerNode.port
     *
     * Default port for server
     */
    this.port = 8080;

    /**
     * ### ServerNode.version
     *
     * The software version of the server as a string
     */
    this.version = require(path.resolve(this.rootDir, 'package.json')).version;

    /**
     * ### ServerNode.nodeGameVersion
     *
     * The official release version of nodeGame
     *
     * This includes all other modules, and it is passed by the launcher.
     *
     * Default: ServerNode.version
     */
    this.nodeGameVersion = opts.nodeGameVersion || this.version;

    /**
     * ### ServerNode.modulesVersion
     *
     * Versions of all nodegame submodules
     *
     * This includes all other modules, and it is passed by the launcher.
     *
     * Default: ServerNode.version
     */
    this.modulesVersion =
        require(path.join(this.rootDir, 'bin', 'info.js')).modulesVersion;

    /**
     * ### ServerNode.defaultConfDir
     *
     * The directory from which the default configuration files are located
     *
     * @see ServerNode.rootDir
     */
    this.defaultConfDir = path.join(this.rootDir, 'conf');

    /**
     * ### ServerNode.channels
     *
     * Object containing references to all the existing channels
     *
     * @see ServerChannel
     */
    this.channels = {};

    /**
     * ### ServerNode.defaultChannel
     *
     * The name of the default channel (will be served from '/')
     *
     * @see ServerChannel
     */
    this.defaultChannel = null;

    /**
     * ### ServerNode._defaultChannel
     *
     * The name of the default channel as specified by options
     *
     * Needs to be distinguished at load time.
     */
    this._defaultChannel = opts.defaultChannel || null;

    /**
     * ### ServerNode.rooms
     *
     * Object containing references to all existing game rooms in all channels
     *
     * @see GameRoom
     */
    this.rooms = {};

    /**
     * ### ServerNode.info
     *
     * Object containing global information about games and channels
     *
     * Games actually include also aliases.
     *
     * @see ServerNode.loadGames
     */
    this.info = {
        channels: {},
        games: {},
        aliases: {}
    };

    /**
     * ### ServerNode.defaults
     *
     * Defaults settings for the server and the channels
     *
     * Will be populated by the configure function.
     */
    this.defaults = {};

    /**
     * ### ServerNode.gamesDirs
     *
     * Array of directories that will be sequentially scanned for games
     */
    this.gamesDirs = [];

    /**
     * ### ServerNode.scannedGamesDirs
     *
     * Keeps tracks of games directories already scanned and of the outcome
     */
    this.scannedGamesDirs = {};

    /**
     * ### ServerNode.logger
     *
     * Default logger before any configuration is loaded.
     *
     * Does not print anything.
     */
    this.logger = winston;
    if (opts.logLevel) {
        if (opts.logLevel !== 'error' &&
            opts.logLevel !== 'warn' &&
            opts.logLevel !== 'info' &&
            opts.logLevel !== 'verbose' &&
            opts.logLevel !== 'debug' &&
            opts.logLevel !== 'silly') {

            throw new Error('ServerNode constructor: invalid logLevel: ' +
                            opts.logLevel);
        }
    }
    this.logger.level = opts.logLevel || 'warn';

    /**
     * ### ServerNode.debug
     *
     * If TRUE, errors will be thrown, otherwise caught and logged.
     */
    this.debug = false;

    /**
     * ### ServerNode.asyncQueue
     *
     * Object containing callbacks to be executed if no operation is in progress
     */
    this.asyncQueue = J.getQueue();

    /**
     * ### ServerNode.sio
     *
     * The Socket.IO app of the server.
     *
     * The app is shared with all the channels.
     */
    this.sio = socket_io.listen(http);

    // see http://nodejs.org/docs/latest/
    //            api/events.html#events_emitter_setmaxlisteners_n
    this.sio.sockets.setMaxListeners(0);

    /**
     * ### ServerNode.gameLoader
     *
     * Object responsible to load the games from the file system.
     */
    this.gameLoader = new GameLoader(this);

    /**
     * ### ServerNode.page
     *
     * Loading, caching of static resources and templates from file system.
     */
    this.resourceManager = new ResourceManager(this);

    /**
     * ### ServerNode.logDir
     *
     * Log directory
     */
    this.logDir = path.join(this.rootDir, 'log');

    /**
     * ### ServerNode.lastError
     *
     * Last error caught by error manager
     */
    this.lastError = null;

    /**
     * ### ServerNode.acm
     *
     * Access control from channels on servernode
     *
     * Important! Currently, acm is not enforced, all channels have access
     * to ServerNode and can modify it. Do not rely on this in production!
     *
     * @experimental
     */
    this.acm = {
        read: {},
        modify: {}
    };

    // Loading configurations.
    this.init(opts || {});
}