Path: blob/trunk/rb/lib/selenium/webdriver/common/socket_lock.rb
1865 views
# frozen_string_literal: true12# Licensed to the Software Freedom Conservancy (SFC) under one3# or more contributor license agreements. See the NOTICE file4# distributed with this work for additional information5# regarding copyright ownership. The SFC licenses this file6# to you under the Apache License, Version 2.0 (the7# "License"); you may not use this file except in compliance8# with the License. You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing,13# software distributed under the License is distributed on an14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15# KIND, either express or implied. See the License for the16# specific language governing permissions and limitations17# under the License.1819module Selenium20module WebDriver21#22# @api private23#2425class SocketLock26def initialize(port, timeout)27@port = port28@server = nil29@timeout = timeout30end3132#33# Attempt to acquire a lock on the given port. Control is yielded to an34# execution block if the lock could be successfully obtained.35#3637def locked38lock3940begin41yield42ensure43release44end45end4647private4849def lock50max_time = current_time + @timeout5152sleep 0.1 until can_lock? || current_time >= max_time5354return if did_lock?5556raise Error::WebDriverError, "unable to bind to locking port #{@port} within #{@timeout} seconds"57end5859def current_time60Process.clock_gettime(Process::CLOCK_MONOTONIC)61end6263def release64@server&.close65end6667def can_lock?68@server = TCPServer.new(Platform.localhost, @port)69@server.close_on_exec = true70true71rescue SocketError, Errno::EADDRINUSE, Errno::EBADF => e72WebDriver.logger.debug("#{self}: #{e.message}", id: :driver_service)73false74end7576def did_lock?77!@server.nil?78end79end # SocketLock80end # WebDriver81end # Selenium828384