Self-host using 'bind' and 'port' from the WSGI config group.
971971
def listen(self):
        """"""

        msgtmpl = (u'Serving on host %(host)s:%(port)s')
        host = CONF.wsgi.wsgi_host
        port = CONF.wsgi.wsgi_port
        LOG.info(msgtmpl,
                 {'host': host, 'port': port})
        server_cls = self._get_server_cls(host)
        httpd = simple_server.make_server(host,
                                          port,
                                          self.app,
                                          server_cls)
        httpd.serve_forever()
1159641
def bind(self, sock):
        """"""
        if self.context is None:
            self.context = self.get_context()
        conn = SSLConnection(self.context, sock)
        self._environ = self.get_environ()
        return conn
768298
def bind
            conn = Net::LDAP.new :host => @config[:server],
                                 :port => @config[:port],
                                 :base => @config[:base]
            if @config[:encryption]
               conn.encryption @config[:encryption]
            end
            
            raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind])
            
            conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password]
            
            begin
                Timeout::timeout(10){
                    if conn.bind
                        return conn
                    else
                        raise 'Query User Rejected'
                    end
                }
            rescue Timeout::Error
                raise 'Unable to connect to LDAP Server'
            rescue Errno::ECONNRESET
              if @config[:allow_fallback]
                @config[:port] = @config[:allow_fallback]
                @config[:encryption] = false
                return Adauth::Connection.new(@config).bind
              end
            end
        end
597287
def autoconf(self):
        
        nginxInfo = NginxInfo(self._host, self._port,
                                self._user, self._password, 
                                self._statuspath, self._ssl)
        return nginxInfo is not None
826231
def reload_wsgi():
    ""
    pid = run('supervisorctl pid varify-{host}'.format(host=env.host))
    try:
        int(pid)
        sudo('kill -HUP {0}'.format(pid))
    except (TypeError, ValueError):
        pass
914945
def _build_ssh_config(self, config):
        
        ssh_config_injection = ssh_config_template % {
            'host': config.get('host'),
            'hostname': config.get('hostname'),
            'ssh_key_path': config.get('ssh_key_path'),
            'user': config.get('user')
        }
        if config.has('port'):
            ssh_config_injection += "  Port {0}\n".format(config.get('port'))
        return ssh_config_injection
1270313
def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True,
             timeout=5, port=53, **kwargs):
    '''
    
    '''
    res = update(zone, name, ttl, 'A', ip, nameserver, timeout, replace, port,
                 **kwargs)
    if res is False:
        return False

    fqdn = '{0}.{1}.'.format(name, zone)
    parts = ip.split('.')[::-1]
    popped = []

    # Iterate over possible reverse zones
    while len(parts) > 1:
        p = parts.pop(0)
        popped.append(p)
        zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
        name = '.'.join(popped)
        ptr = update(zone, name, ttl, 'PTR', fqdn, nameserver, timeout,
                     replace, port, **kwargs)
        if ptr:
            return True
    return res
12761
def run(self):
        
        try:
            # Go through the list of possible ports, hoping we can find
            # one that is free to use for the WSGI server.
            for index, port in enumerate(self.possible_ports):
                try:
                    self.httpd = self._create_server(port)
                except socket.error as e:
                    if (index + 1 < len(self.possible_ports) and
                            e.error == errno.EADDRINUSE):
                        # This port is already in use, so we go on and try with
                        # the next one in the list.
                        continue
                    else:
                        # Either none of the given ports are free or the error
                        # is something else than "Address already in use". So
                        # we let that error bubble up to the main thread.
                        raise
                else:
                    # A free port was found.
                    self.port = port
                    break

            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
113870
def server_bind(self):
    """"""
    TCPServer.server_bind(self)
    _, self.server_port = self.socket.getsockname()[:2]
505971
def apache_config(config, outputfile):
    '''
        
    '''
    if os.path.exists(outputfile):
        os.rename(outputfile, outputfile + ".old")
        print("Renamed existing Apache config file to " + outputfile + ".old")

    from django.conf import settings
    f = open(outputfile, 'w')
    print("Generating Apache configuration in " + outputfile)
    subdir = (len(settings.HOST_DIR) > 0)
    text = """
    # OpenSubmit Configuration for Apache 2.4
    # These directives are expected to live in some <VirtualHost> block
    """
    if subdir:
        text += "Alias /%s/static/ %s\n" % (settings.HOST_DIR,
                                            settings.STATIC_ROOT)
        text += "    WSGIScriptAlias /%s %s/wsgi.py\n" % (
            settings.HOST_DIR, settings.SCRIPT_ROOT)
    else:
        text += "Alias /static/ %s\n" % (settings.STATIC_ROOT)
        text += "    WSGIScriptAlias / %s/wsgi.py" % (settings.SCRIPT_ROOT)
    text += """
    WSGIPassAuthorization On
    <Directory {static_path}>
         Require all granted
    </Directory>
    <Directory {install_path}>
         <Files wsgi.py>
              Require all granted
         </Files>
    </Directory>
    """.format(static_path=settings.STATIC_ROOT, install_path=settings.SCRIPT_ROOT)

    f.write(text)
    f.close()
1046320
def start_server(self, host='localhost', port=9000, app=None):
        """"""
        from wsgiref.simple_server import make_server
        if app is None:
            app = self.wsgi
        server = make_server(host, port, app)
        server_addr = "%s:%s" % (server.server_name, server.server_port)
        print "Server listening at http://%s/" % server_addr
        server.serve_forever()
477542
def create_port_binding(self, port, host):
        """"""
        if not self.get_instance_type(port):
            return
        for pb_key in self._get_binding_keys(port, host):
            pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
                                  a_const.CREATE)
            self.provision_queue.put(pb_res)
1065247
def ConfigureHostnames(config, external_hostname = None):
  """"""
  if not external_hostname:
    try:
      external_hostname = socket.gethostname()
    except (OSError, IOError):
      print("Sorry, we couldn't guess your hostname.\n")

    external_hostname = RetryQuestion(
        "Please enter your hostname e.g. "
        "grr.example.com", "^[\\.A-Za-z0-9-]+$", external_hostname)

  print("""\n\n-=Server URL=-
The Server URL specifies the URL that the clients will connect to
communicate with the server. For best results this should be publicly
accessible. By default this will be port 8080 with the URL ending in /control.
""")
  frontend_url = RetryQuestion("Frontend URL", "^http://.*/$",
                               "http://%s:8080/" % external_hostname)
  config.Set("Client.server_urls", [frontend_url])

  frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get(
      "Frontend.bind_port")
  config.Set("Frontend.bind_port", frontend_port)

  print("""\n\n-=AdminUI URL=-:
The UI URL specifies where the Administrative Web Interface can be found.
""")
  ui_url = RetryQuestion("AdminUI URL", "^http[s]*://.*$",
                         "http://%s:8000" % external_hostname)
  config.Set("AdminUI.url", ui_url)
  ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get(
      "AdminUI.port")
  config.Set("AdminUI.port", ui_port)
636854
def bind_port(requested_port):
  """"""
  sockets = tornado.netutil.bind_sockets(requested_port)

  if requested_port != 0:
    return sockets, requested_port

  # Get the actual port number.
  for s in sockets:
    host, port = s.getsockname()[:2]
    if host == '0.0.0.0':
      return sockets, port

  raise RuntimeError('Could not determine the bound port.')
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
1240748
def bind(self):
        
        log.debug("Set SO_REUSADDR")
        self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
        
        # we want daemon threads, so we join on abrupt shutdown (applies if multithreaded) 
        self.daemon_threads = True

        self.server_bind()
        self.server_activate()
1345308
def _build_wsgi_env(event, app_name):
    
    gateway = event['parameters']['gateway']
    request = event['parameters']['request']
    ctx = event['rawContext']
    headers = request['header']
    body = six.text_type(json.dumps(request['body']))

    # Render the path correctly so connexion/flask will pass the path params to
    # the handler function correctly.
    # Basically, this replaces "/foo/{param1}/bar/{param2}" with
    # "/foo/123/bar/456".
    path = gateway['resource-path'].format(
        **event['parameters']['request']['path']
    )
    environ = {
        'PATH_INFO': path,
        'QUERY_STRING': urlencode(request['querystring']),
        'REMOTE_ADDR': ctx['identity']['sourceIp'],
        'REQUEST_METHOD': ctx['httpMethod'],
        'SCRIPT_NAME': app_name,
        'SERVER_NAME': app_name,
        'SERVER_PORT': headers.get('X-Forwarded-Port', '80'),
        'SERVER_PROTOCOL': 'HTTP/1.1',
        'wsgi.version': (1, 0),
        'wsgi.url_scheme': headers.get('X-Forwarded-Proto', 'http'),
        'wsgi.input': StringIO(body),
        'wsgi.errors': StringIO(),
        'wsgi.multiprocess': False,
        'wsgi.multithread': False,
        'wsgi.run_once': False,
        'CONTENT_TYPE': headers.get('Content-Type', 'application/json'),
    }
    if ctx['httpMethod'] in ['POST', 'PUT', 'PATCH']:
        environ['CONTENT_LENGTH'] = str(len(body))

    for header_name, header_value in headers.items():
        wsgi_name = 'HTTP_{}'.format(header_name.upper().replace('-', '_'))
        environ[wsgi_name] = str(header_value)

    return environ