Beispiel #1
0
    def StartServer(self, request_data):
        with self._server_state_mutex:
            if self.ServerIsHealthy():
                return

            # Ensure we cleanup all states.
            self._Reset()

            LOGGER.info('Starting clangd: %s', self._clangd_command)
            self._stderr_file = utils.CreateLogfile('clangd_stderr')
            with utils.OpenForStdHandle(self._stderr_file) as stderr:
                self._server_handle = utils.SafePopen(self._clangd_command,
                                                      stdin=subprocess.PIPE,
                                                      stdout=subprocess.PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                LOGGER.error('clangd failed to start, or did not connect '
                             'successfully')
                self.Shutdown()
                return

        LOGGER.info('clangd started')

        self.SendInitialize(request_data)
Beispiel #2
0
    def _SetUpLogging(self):
        def FreeFileFromOtherProcesses(file_object):
            if utils.OnWindows():
                from ctypes import windll
                import msvcrt

                file_handle = msvcrt.get_osfhandle(file_object.fileno())
                windll.kernel32.SetHandleInformation(file_handle,
                                                     HANDLE_FLAG_INHERIT, 0)

        self._client_logfile = utils.CreateLogfile(CLIENT_LOGFILE_FORMAT)

        handler = logging.FileHandler(self._client_logfile)

        # On Windows and Python prior to 3.4, file handles are inherited by child
        # processes started with at least one replaced standard stream, which is the
        # case when we start the ycmd server (we are redirecting all standard
        # outputs into a pipe). These files cannot be removed while the child
        # processes are still up. This is not desirable for a logfile because we
        # want to remove it at Vim exit without having to wait for the ycmd server
        # to be completely shut down. We need to make the logfile handle
        # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
        # details.
        FreeFileFromOtherProcesses(handler.stream)

        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)

        self._logger.addHandler(handler)
Beispiel #3
0
  def _StartServerNoLock( self ):
    if self._ServerIsRunning():
      return

    self._logfile = utils.CreateLogfile( LOGFILE_FORMAT )
    tsserver_log = f'-file { self._logfile } -level {_LogLevel()}'
    # TSServer gets the configuration for the log file through the
    # environment variable 'TSS_LOG'. This seems to be undocumented but
    # looking at the source code it seems like this is the way:
    # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136
    environ = os.environ.copy()
    environ[ 'TSS_LOG' ] = tsserver_log

    LOGGER.info( 'TSServer log file: %s', self._logfile )

    # We need to redirect the error stream to the output one on Windows.
    self._tsserver_handle = utils.SafePopen( self._tsserver_executable,
                                             stdin = subprocess.PIPE,
                                             stdout = subprocess.PIPE,
                                             stderr = subprocess.STDOUT,
                                             env = environ )

    LOGGER.info( "TSServer started with PID %s", self._tsserver_handle.pid )
    self._tsserver_is_running.set()

    utils.StartThread( self._SetServerVersion )
Beispiel #4
0
    def StartServer(self, request_data):
        with self._server_state_mutex:
            LOGGER.info('Starting %s: %s', self.GetServerName(),
                        self.GetCommandLine())

            self._stderr_file = utils.CreateLogfile('{}_stderr'.format(
                utils.MakeSafeFileNameString(self.GetServerName())))

            with utils.OpenForStdHandle(self._stderr_file) as stderr:
                self._server_handle = utils.SafePopen(self.GetCommandLine(),
                                                      stdin=subprocess.PIPE,
                                                      stdout=subprocess.PIPE,
                                                      stderr=stderr)

            self._connection = (lsc.StandardIOLanguageServerConnection(
                self._server_handle.stdin, self._server_handle.stdout,
                self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except lsc.LanguageServerConnectionTimeout:
                LOGGER.error(
                    '%s failed to start, or did not connect successfully',
                    self.GetServerName())
                self.Shutdown()
                return False

        LOGGER.info('%s started', self.GetServerName())

        return True
Beispiel #5
0
    def _StartServer(self):
        with self._tsserver_lock:
            if self._ServerIsRunning():
                return

            self._logfile = utils.CreateLogfile(LOGFILE_FORMAT)
            tsserver_log = '-file {path} -level {level}'.format(
                path=self._logfile, level=_LogLevel())
            # TSServer gets the configuration for the log file through the
            # environment variable 'TSS_LOG'. This seems to be undocumented but
            # looking at the source code it seems like this is the way:
            # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136
            environ = os.environ.copy()
            utils.SetEnviron(environ, 'TSS_LOG', tsserver_log)

            _logger.info('TSServer log file: {0}'.format(self._logfile))

            # We need to redirect the error stream to the output one on Windows.
            self._tsserver_handle = utils.SafePopen(PATH_TO_TSSERVER,
                                                    stdin=subprocess.PIPE,
                                                    stdout=subprocess.PIPE,
                                                    stderr=subprocess.STDOUT,
                                                    env=environ)

            self._tsserver_is_running.set()

            utils.StartThread(self._SetServerVersion)
Beispiel #6
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self._ServerIsRunning():
                return

            LOGGER.info('Starting OmniSharp server')
            LOGGER.info('Loading solution file %s', self._solution_path)

            self._ChooseOmnisharpPort()

            # Roslyn fails unless you open it in shell in Window on Python 2
            # Shell isn't preferred, but I don't see any other way to resolve
            shell_required = PY2 and utils.OnWindows()

            command = [
                PATH_TO_ROSLYN_OMNISHARP_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                str(self._solution_path)
            ]

            if (not utils.OnWindows()
                    and PATH_TO_ROSLYN_OMNISHARP_BINARY.endswith('.exe')):
                command.insert(0, 'mono')

            LOGGER.info('Starting OmniSharp server with: %s', command)

            solutionfile = os.path.basename(self._solution_path)
            self._filename_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stdout'))
            self._filename_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stderr'))

            with utils.OpenForStdHandle(self._filename_stderr) as fstderr:
                with utils.OpenForStdHandle(self._filename_stdout) as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(
                        command,
                        stdout=fstdout,
                        stderr=fstderr,
                        shell=shell_required)

            LOGGER.info('Started OmniSharp server')
Beispiel #7
0
    def _SetupServer(self):
        self._available_completers = {}
        self._user_notified_about_crash = False
        self._filetypes_with_keywords_loaded = set()
        self._server_is_ready_with_cache = False

        server_port = utils.GetUnusedLocalhostPort()
        # The temp options file is deleted by ycmd during startup
        with NamedTemporaryFile(delete=False, mode='w+') as options_file:
            hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
            options_dict = dict(self._user_options)
            options_dict['hmac_secret'] = utils.ToUnicode(
                base64.b64encode(hmac_secret))
            options_dict['server_keep_logfiles'] = self._user_options[
                'keep_logfiles']
            json.dump(options_dict, options_file)
            options_file.flush()

            args = [
                paths.PathToPythonInterpreter(),
                paths.PathToServerScript(), '--port={0}'.format(server_port),
                '--options_file={0}'.format(options_file.name),
                '--log={0}'.format(self._user_options['log_level']),
                '--idle_suicide_seconds={0}'.format(
                    SERVER_IDLE_SUICIDE_SECONDS)
            ]

            self._server_stdout = utils.CreateLogfile(
                SERVER_LOGFILE_FORMAT.format(port=server_port, std='stdout'))
            self._server_stderr = utils.CreateLogfile(
                SERVER_LOGFILE_FORMAT.format(port=server_port, std='stderr'))
            args.append('--stdout={0}'.format(self._server_stdout))
            args.append('--stderr={0}'.format(self._server_stderr))

            if self._user_options['keep_logfiles']:
                args.append('--keep_logfiles')

            self._server_popen = utils.SafePopen(args,
                                                 stdin_windows=PIPE,
                                                 stdout=PIPE,
                                                 stderr=PIPE)
            BaseRequest.server_location = 'http://127.0.0.1:' + str(
                server_port)
            BaseRequest.hmac_secret = hmac_secret

        self._NotifyUserIfServerCrashed()
Beispiel #8
0
    def _StartServer(self, request_data):
        with self._server_state_mutex:
            if self._server_started:
                return

            self._server_started = True

            _logger.info('Starting jdt.ls Language Server...')

            self._project_dir = _FindProjectDir(
                os.path.dirname(request_data['filepath']))
            self._workspace_path = _WorkspaceDirForProject(
                self._project_dir, self._use_clean_workspace)

            command = [
                PATH_TO_JAVA,
                '-Dfile.encoding=UTF-8',
                '-Declipse.application=org.eclipse.jdt.ls.core.id1',
                '-Dosgi.bundles.defaultStartLevel=4',
                '-Declipse.product=org.eclipse.jdt.ls.core.product',
                '-Dlog.level=ALL',
                '-jar',
                self._launcher_path,
                '-configuration',
                self._launcher_config,
                '-data',
                self._workspace_path,
            ]

            _logger.debug('Starting java-server with the following command: '
                          '{0}'.format(' '.join(command)))

            self._server_stderr = utils.CreateLogfile('jdt.ls_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                _logger.error('jdt.ls failed to start, or did not connect '
                              'successfully')
                self._StopServer()
                return

        _logger.info('jdt.ls Language Server started')

        self.SendInitialize(request_data)
Beispiel #9
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self._ServerIsRunning():
                return

            self._logger.info('Starting OmniSharp server')

            path_to_solutionfile = self._solution_path
            self._logger.info(
                u'Loading solution file {0}'.format(path_to_solutionfile))

            self._ChooseOmnisharpPort()

            command = [
                PATH_TO_OMNISHARP_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                u'{0}'.format(path_to_solutionfile)
            ]

            if not utils.OnWindows() and not utils.OnCygwin():
                command.insert(0, 'mono')

            if utils.OnCygwin():
                command.extend(['--client-path-mode', 'Cygwin'])

            solutionfile = os.path.basename(path_to_solutionfile)
            self._filename_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stdout'))
            self._filename_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stderr'))

            with utils.OpenForStdHandle(self._filename_stderr) as fstderr:
                with utils.OpenForStdHandle(self._filename_stdout) as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(command,
                                                              stdout=fstdout,
                                                              stderr=fstderr)

            self._solution_path = path_to_solutionfile
Beispiel #10
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self._ServerIsRunning():
                return

            LOGGER.info('Starting OmniSharp server')
            LOGGER.info('Loading solution file %s', self._solution_path)

            self._ChooseOmnisharpPort()

            command = [
                PATH_TO_OMNISHARP_ROSLYN_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                str(self._solution_path)
            ]

            if (not utils.OnWindows() and self._roslyn_path.endswith('.exe')):
                command.insert(0, 'mono')

            LOGGER.info('Starting OmniSharp server with: %s', command)

            solutionfile = os.path.basename(self._solution_path)
            self._filename_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stdout'))
            self._filename_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stderr'))

            with utils.OpenForStdHandle(self._filename_stderr) as fstderr:
                with utils.OpenForStdHandle(self._filename_stdout) as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(command,
                                                              stdout=fstdout,
                                                              stderr=fstderr)

            LOGGER.info('Started OmniSharp server')
Beispiel #11
0
    def _StartServer(self):
        with self._server_state_lock:
            self._racerd_port = utils.GetUnusedLocalhostPort()
            self._hmac_secret = self._CreateHmacSecret()

            # racerd will delete the secret_file after it's done reading it
            with tempfile.NamedTemporaryFile(delete=False) as secret_file:
                secret_file.write(self._hmac_secret)
                args = [
                    self._racerd_binary, 'serve', '--port',
                    str(self._racerd_port), '-l', '--secret-file',
                    secret_file.name
                ]

            # Enable logging of crashes
            env = os.environ.copy()
            SetEnviron(env, 'RUST_BACKTRACE', '1')

            if self._rust_source_path:
                args.extend(['--rust-src-path', self._rust_source_path])

            self._server_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._racerd_port, std='stdout'))
            self._server_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._racerd_port, std='stderr'))

            with utils.OpenForStdHandle(self._server_stderr) as fstderr:
                with utils.OpenForStdHandle(self._server_stdout) as fstdout:
                    self._racerd_phandle = utils.SafePopen(args,
                                                           stdout=fstdout,
                                                           stderr=fstderr,
                                                           env=env)

            self._racerd_host = 'http://127.0.0.1:{0}'.format(
                self._racerd_port)
            if not self._ServerIsRunning():
                raise RuntimeError('Failed to start racerd!')
            _logger.info('Racerd started on: ' + self._racerd_host)
Beispiel #12
0
    def _StartServer(self, request_data, project_directory=None):
        with self._server_state_mutex:
            if self._server_started:
                return

            self._server_started = True

            _logger.info('Starting dart Language Server...')

            if project_directory:
                self._project_dir = project_directory
            else:
                self._project_dir = _FindProjectDir(
                    os.path.dirname(request_data['filepath']))

            self._workspace_path = self._project_dir

            command = [
                PATH_TO_DART,
                '--force_trace_level=verbose',
            ]

            _logger.debug('Starting dart-server with the following command: '
                          '{0}'.format(' '.join(command)))

            self._server_stderr = utils.CreateLogfile('dart_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                _logger.error('dart failed to start, or did not connect '
                              'successfully')
                self._StopServer()
                return

        _logger.info('dart Language Server started')

        self.SendInitialize(request_data)
Beispiel #13
0
    def _StartServer(self, request_data):
        with self._server_state_mutex:
            if self._server_started:
                return

            self._server_started = True
            _logger.info('Starting Vue Language Server')

            command = [LANGUAGE_SERVER_HOME, '--stdio']

            self._server_stderr = utils.CreateLogfile('vls_stderr_')

            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            if not self._ServerIsRunning():
                _logger.error('Vue Language Server failed to start')
                return

            _logger.info('Vue Language Server started')

            self._connection = language_server_completer.StandardIOLanguageServerConnection(
                self._server_handle.stdin, self._server_handle.stdout,
                self.GetDefaultNotificationHandler())

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                _logger.error(
                    'Vue Language Server failed to start, or did not connect successfully'
                )
                self._StopServer()
                return

            self.SendInitialize(request_data)
Beispiel #14
0
    def _SetUpServer(self):
        self._available_completers = {}
        self._user_notified_about_crash = False
        self._filetypes_with_keywords_loaded = set()
        self._server_is_ready_with_cache = False
        self._message_poll_requests = {}

        self._latest_completion_request = None
        self._latest_signature_help_request = None
        self._signature_help_available_requests = SigHelpAvailableByFileType()
        self._latest_command_reqeust = None

        self._signature_help_state = signature_help.SignatureHelpState()
        self._user_options = base.GetUserOptions(self._default_options)
        self._omnicomp = OmniCompleter(self._user_options)
        self._buffers = BufferDict(self._user_options)

        self._SetLogLevel()

        hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
        options_dict = dict(self._user_options)
        options_dict['hmac_secret'] = utils.ToUnicode(
            base64.b64encode(hmac_secret))
        options_dict['server_keep_logfiles'] = self._user_options[
            'keep_logfiles']

        # The temp options file is deleted by ycmd during startup.
        with NamedTemporaryFile(delete=False, mode='w+') as options_file:
            json.dump(options_dict, options_file)

        server_port = utils.GetUnusedLocalhostPort()

        BaseRequest.server_location = 'http://127.0.0.1:' + str(server_port)
        BaseRequest.hmac_secret = hmac_secret

        try:
            python_interpreter = paths.PathToPythonInterpreter()
        except RuntimeError as error:
            error_message = (
                f"Unable to start the ycmd server. { str( error ).rstrip( '.' ) }. "
                "Correct the error then restart the server "
                "with ':YcmRestartServer'.")
            self._logger.exception(error_message)
            vimsupport.PostVimMessage(error_message)
            return

        args = [
            python_interpreter,
            paths.PathToServerScript(), f'--port={ server_port }',
            f'--options_file={ options_file.name }',
            f'--log={ self._user_options[ "log_level" ] }',
            f'--idle_suicide_seconds={ SERVER_IDLE_SUICIDE_SECONDS }'
        ]

        self._server_stdout = utils.CreateLogfile(
            SERVER_LOGFILE_FORMAT.format(port=server_port, std='stdout'))
        self._server_stderr = utils.CreateLogfile(
            SERVER_LOGFILE_FORMAT.format(port=server_port, std='stderr'))
        args.append(f'--stdout={ self._server_stdout }')
        args.append(f'--stderr={ self._server_stderr }')

        if self._user_options['keep_logfiles']:
            args.append('--keep_logfiles')

        if 'YCM_WITH_PTVSD' in os.environ:
            args[1:1] = [
                '-m', 'ptvsd', '--host', 'localhost', '--port', '1234',
                '--wait', '--no-subprocesses'
            ]

        self._logger.debug('Starting ycmd with: %s', args)

        self._server_popen = utils.SafePopen(args,
                                             stdin_windows=PIPE,
                                             stdout=PIPE,
                                             stderr=PIPE)
Beispiel #15
0
    def StartServer(self, request_data, project_directory=None):
        with self._server_state_mutex:
            if self._server_started:
                return

            # We have to get the settings before starting the server, as this call
            # might throw UnknownExtraConf.
            extra_conf_dir = self._GetSettingsFromExtraConf(request_data)

            self._server_started = True

            LOGGER.info('Starting jdt.ls Language Server...')

            if project_directory:
                self._java_project_dir = project_directory
            else:
                self._java_project_dir = _FindProjectDir(
                    os.path.dirname(request_data['filepath']))

            self._workspace_path = _WorkspaceDirForProject(
                self._java_project_dir, self._use_clean_workspace)

            command = [
                PATH_TO_JAVA,
                '-Dfile.encoding=UTF-8',
                '-Declipse.application=org.eclipse.jdt.ls.core.id1',
                '-Dosgi.bundles.defaultStartLevel=4',
                '-Declipse.product=org.eclipse.jdt.ls.core.product',
                '-Dlog.level=ALL',
                '-jar',
                self._launcher_path,
                '-configuration',
                self._launcher_config,
                '-data',
                self._workspace_path,
            ]

            LOGGER.debug('Starting java-server with the following command: %s',
                         command)

            self._server_stderr = utils.CreateLogfile('jdt.ls_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                LOGGER.error('jdt.ls failed to start, or did not connect '
                             'successfully')
                self._StopServer()
                return

        LOGGER.info('jdt.ls Language Server started')

        self.SendInitialize(request_data, extra_conf_dir=extra_conf_dir)
Beispiel #16
0
    def _SetUpServer(self):
        self._available_completers = {}
        self._user_notified_about_crash = False
        self._filetypes_with_keywords_loaded = set()
        self._server_is_ready_with_cache = False
        self._message_poll_requests = {}

        self._user_options = base.GetUserOptions()
        self._omnicomp = OmniCompleter(self._user_options)
        self._buffers = BufferDict(self._user_options)

        self._SetLogLevel()

        hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
        options_dict = dict(self._user_options)
        options_dict['hmac_secret'] = utils.ToUnicode(
            base64.b64encode(hmac_secret))
        options_dict['server_keep_logfiles'] = self._user_options[
            'keep_logfiles']

        # The temp options file is deleted by ycmd during startup.
        with NamedTemporaryFile(delete=False, mode='w+') as options_file:
            json.dump(options_dict, options_file)

        server_port = utils.GetUnusedLocalhostPort()

        BaseRequest.server_location = 'http://127.0.0.1:' + str(server_port)
        BaseRequest.hmac_secret = hmac_secret

        try:
            python_interpreter = paths.PathToPythonInterpreter()
        except RuntimeError as error:
            error_message = ("Unable to start the ycmd server. {0}. "
                             "Correct the error then restart the server "
                             "with ':YcmRestartServer'.".format(
                                 str(error).rstrip('.')))
            self._logger.exception(error_message)
            vimsupport.PostVimMessage(error_message)
            return

        args = [
            python_interpreter,
            paths.PathToServerScript(), '--port={0}'.format(server_port),
            '--options_file={0}'.format(options_file.name),
            '--log={0}'.format(self._user_options['log_level']),
            '--idle_suicide_seconds={0}'.format(SERVER_IDLE_SUICIDE_SECONDS)
        ]

        self._server_stdout = utils.CreateLogfile(
            SERVER_LOGFILE_FORMAT.format(port=server_port, std='stdout'))
        self._server_stderr = utils.CreateLogfile(
            SERVER_LOGFILE_FORMAT.format(port=server_port, std='stderr'))
        args.append('--stdout={0}'.format(self._server_stdout))
        args.append('--stderr={0}'.format(self._server_stderr))

        if self._user_options['keep_logfiles']:
            args.append('--keep_logfiles')

        self._server_popen = utils.SafePopen(args,
                                             stdin_windows=PIPE,
                                             stdout=PIPE,
                                             stderr=PIPE)
Beispiel #17
0
    def StartServer(self,
                    request_data,
                    project_directory=None,
                    wipe_workspace=False,
                    wipe_config=False):
        with self._server_state_mutex:
            LOGGER.info('Starting jdt.ls Language Server...')

            if project_directory:
                self._java_project_dir = project_directory
            else:
                self._java_project_dir = _FindProjectDir(
                    os.path.dirname(request_data['filepath']))

            self._workspace_path = _WorkspaceDirForProject(
                self._workspace_root_path, self._java_project_dir,
                self._use_clean_workspace)

            if not self._use_clean_workspace and wipe_workspace:
                if os.path.isdir(self._workspace_path):
                    LOGGER.info('Wiping out workspace {0}'.format(
                        self._workspace_path))
                    shutil.rmtree(self._workspace_path)

            self._launcher_config = _LauncherConfiguration(
                self._workspace_root_path, wipe_config)

            command = [
                PATH_TO_JAVA,
                '-Dfile.encoding=UTF-8',
                '-Declipse.application=org.eclipse.jdt.ls.core.id1',
                '-Dosgi.bundles.defaultStartLevel=4',
                '-Declipse.product=org.eclipse.jdt.ls.core.product',
                '-Dlog.level=ALL',
                '-jar',
                self._launcher_path,
                '-configuration',
                self._launcher_config,
                '-data',
                self._workspace_path,
            ]

            LOGGER.debug('Starting java-server with the following command: %s',
                         command)

            self._server_stderr = utils.CreateLogfile('jdt.ls_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                LOGGER.error('jdt.ls failed to start, or did not connect '
                             'successfully')
                self.Shutdown()
                return False

        LOGGER.info('jdt.ls Language Server started')

        return True