How to use NodeDrainStarted class of org.openqa.selenium.grid.data package

Best Selenium code snippet using org.openqa.selenium.grid.data.NodeDrainStarted

Source:OneShotNode.java Github

copy

Full Screen

...28import org.openqa.selenium.grid.config.ConfigException;29import org.openqa.selenium.grid.data.CreateSessionRequest;30import org.openqa.selenium.grid.data.CreateSessionResponse;31import org.openqa.selenium.grid.data.NodeDrainComplete;32import org.openqa.selenium.grid.data.NodeDrainStarted;33import org.openqa.selenium.grid.data.NodeId;34import org.openqa.selenium.grid.data.NodeStatus;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionClosedEvent;37import org.openqa.selenium.grid.data.Slot;38import org.openqa.selenium.grid.data.SlotId;39import org.openqa.selenium.grid.log.LoggingOptions;40import org.openqa.selenium.grid.node.HealthCheck;41import org.openqa.selenium.grid.node.Node;42import org.openqa.selenium.grid.node.config.NodeOptions;43import org.openqa.selenium.grid.security.Secret;44import org.openqa.selenium.grid.server.BaseServerOptions;45import org.openqa.selenium.grid.server.EventBusOptions;46import org.openqa.selenium.internal.Require;47import org.openqa.selenium.json.Json;48import org.openqa.selenium.remote.CommandExecutor;49import org.openqa.selenium.remote.RemoteWebDriver;50import org.openqa.selenium.remote.SessionId;51import org.openqa.selenium.remote.http.HttpClient;52import org.openqa.selenium.remote.http.HttpRequest;53import org.openqa.selenium.remote.http.HttpResponse;54import org.openqa.selenium.remote.tracing.Tracer;55import java.lang.reflect.Field;56import java.net.URI;57import java.net.URISyntaxException;58import java.time.Instant;59import java.util.HashMap;60import java.util.Map;61import java.util.Optional;62import java.util.ServiceLoader;63import java.util.TreeMap;64import java.util.UUID;65import java.util.logging.Logger;66import java.util.stream.StreamSupport;67import static java.nio.charset.StandardCharsets.UTF_8;68import static org.openqa.selenium.grid.data.Availability.DRAINING;69import static org.openqa.selenium.grid.data.Availability.UP;70import static org.openqa.selenium.json.Json.MAP_TYPE;71import static org.openqa.selenium.remote.http.HttpMethod.DELETE;72/**73 * An implementation of {@link Node} that marks itself as draining immediately74 * after starting, and which then shuts down after usage. This will allow an75 * appropriately configured Kubernetes cluster to start a new node once the76 * session is finished.77 */78public class OneShotNode extends Node {79 private static final Logger LOG = Logger.getLogger(OneShotNode.class.getName());80 private static final Json JSON = new Json();81 private final EventBus events;82 private final WebDriverInfo driverInfo;83 private final Capabilities stereotype;84 private final URI gridUri;85 private final UUID slotId = UUID.randomUUID();86 private RemoteWebDriver driver;87 private SessionId sessionId;88 private HttpClient client;89 private Capabilities capabilities;90 private Instant sessionStart = Instant.EPOCH;91 private OneShotNode(92 Tracer tracer,93 EventBus events,94 Secret registrationSecret,95 NodeId id,96 URI uri,97 URI gridUri,98 Capabilities stereotype,99 WebDriverInfo driverInfo) {100 super(tracer, id, uri, registrationSecret);101 this.events = Require.nonNull("Event bus", events);102 this.gridUri = Require.nonNull("Public Grid URI", gridUri);103 this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype));104 this.driverInfo = Require.nonNull("Driver info", driverInfo);105 }106 public static Node create(Config config) {107 LoggingOptions loggingOptions = new LoggingOptions(config);108 EventBusOptions eventOptions = new EventBusOptions(config);109 BaseServerOptions serverOptions = new BaseServerOptions(config);110 NodeOptions nodeOptions = new NodeOptions(config);111 Map<String, Object> raw = new Json().toType(112 config.get("k8s", "stereotype")113 .orElseThrow(() -> new ConfigException("Unable to find node stereotype")),114 MAP_TYPE);115 Capabilities stereotype = new ImmutableCapabilities(raw);116 Optional<String> driverName = config.get("k8s", "driver_name").map(String::toLowerCase);117 // Find the webdriver info corresponding to the driver name118 WebDriverInfo driverInfo = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)119 .filter(info -> info.isSupporting(stereotype))120 .filter(info -> driverName.map(name -> name.equals(info.getDisplayName().toLowerCase())).orElse(true))121 .findFirst()122 .orElseThrow(() -> new ConfigException(123 "Unable to find matching driver for %s and %s", stereotype, driverName.orElse("any driver")));124 LOG.info(String.format("Creating one-shot node for %s with stereotype %s", driverInfo, stereotype));125 LOG.info("Grid URI is: " + nodeOptions.getPublicGridUri());126 return new OneShotNode(127 loggingOptions.getTracer(),128 eventOptions.getEventBus(),129 serverOptions.getRegistrationSecret(),130 new NodeId(UUID.randomUUID()),131 serverOptions.getExternalUri(),132 nodeOptions.getPublicGridUri().orElseThrow(() -> new ConfigException("Unable to determine public grid address")),133 stereotype,134 driverInfo);135 }136 @Override137 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {138 if (driver != null) {139 throw new IllegalStateException("Only expected one session at a time");140 }141 Optional<WebDriver> driver = driverInfo.createDriver(sessionRequest.getCapabilities());142 if (!driver.isPresent()) {143 return Optional.empty();144 }145 if (!(driver.get() instanceof RemoteWebDriver)) {146 driver.get().quit();147 return Optional.empty();148 }149 this.driver = (RemoteWebDriver) driver.get();150 this.sessionId = this.driver.getSessionId();151 this.client = extractHttpClient(this.driver);152 this.capabilities = rewriteCapabilities(this.driver);153 this.sessionStart = Instant.now();154 LOG.info("Encoded response: " + JSON.toJson(ImmutableMap.of(155 "value", ImmutableMap.of(156 "sessionId", sessionId,157 "capabilities", capabilities))));158 events.fire(new NodeDrainStarted(getId()));159 return Optional.of(160 new CreateSessionResponse(161 getSession(sessionId),162 JSON.toJson(ImmutableMap.of(163 "value", ImmutableMap.of(164 "sessionId", sessionId,165 "capabilities", capabilities))).getBytes(UTF_8)));166 }167 private HttpClient extractHttpClient(RemoteWebDriver driver) {168 CommandExecutor executor = driver.getCommandExecutor();169 try {170 Field client = null;171 Class<?> current = executor.getClass();172 while (client == null && (current != null || Object.class.equals(current))) {173 client = findClientField(current);174 current = current.getSuperclass();175 }176 if (client == null) {177 throw new IllegalStateException("Unable to find client field in " + executor.getClass());178 }179 if (!HttpClient.class.isAssignableFrom(client.getType())) {180 throw new IllegalStateException("Client field is not assignable to http client");181 }182 client.setAccessible(true);183 return (HttpClient) client.get(executor);184 } catch (ReflectiveOperationException e) {185 throw new IllegalStateException(e);186 }187 }188 private Field findClientField(Class<?> clazz) {189 try {190 return clazz.getDeclaredField("client");191 } catch (NoSuchFieldException e) {192 return null;193 }194 }195 private Capabilities rewriteCapabilities(RemoteWebDriver driver) {196 // Rewrite the se:options if necessary197 Object rawSeleniumOptions = driver.getCapabilities().getCapability("se:options");198 if (rawSeleniumOptions == null || rawSeleniumOptions instanceof Map) {199 @SuppressWarnings("unchecked") Map<String, Object> original = (Map<String, Object>) rawSeleniumOptions;200 Map<String, Object> updated = new TreeMap<>(original == null ? new HashMap<>() : original);201 String cdpPath = String.format("/session/%s/se/cdp", driver.getSessionId());202 updated.put("cdp", rewrite(cdpPath));203 return new PersistentCapabilities(driver.getCapabilities()).setCapability("se:options", updated);204 }205 return ImmutableCapabilities.copyOf(driver.getCapabilities());206 }207 private URI rewrite(String path) {208 try {209 return new URI(210 gridUri.getScheme(),211 gridUri.getUserInfo(),212 gridUri.getHost(),213 gridUri.getPort(),214 path,215 null,216 null);217 } catch (URISyntaxException e) {218 throw new RuntimeException(e);219 }220 }221 @Override222 public HttpResponse executeWebDriverCommand(HttpRequest req) {223 LOG.info("Executing " + req);224 HttpResponse res = client.execute(req);225 if (DELETE.equals(req.getMethod()) && req.getUri().equals("/session/" + sessionId)) {226 // Ensure the response is sent before we viciously kill the node227 new Thread(228 () -> {229 try {230 Thread.sleep(500);231 } catch (InterruptedException e) {232 Thread.currentThread().interrupt();233 throw new RuntimeException(e);234 }235 LOG.info("Stopping session: " + sessionId);236 stop(sessionId);237 },238 "Node clean up: " + getId())239 .start();240 }241 return res;242 }243 @Override244 public Session getSession(SessionId id) throws NoSuchSessionException {245 if (!isSessionOwner(id)) {246 throw new NoSuchSessionException("Unable to find session with id: " + id);247 }248 return new Session(249 sessionId,250 getUri(),251 stereotype,252 capabilities,253 sessionStart); }254 @Override255 public HttpResponse uploadFile(HttpRequest req, SessionId id) {256 return null;257 }258 @Override259 public void stop(SessionId id) throws NoSuchSessionException {260 LOG.info("Stop has been called: " + id);261 Require.nonNull("Session ID", id);262 if (!isSessionOwner(id)) {263 throw new NoSuchSessionException("Unable to find session " + id);264 }265 LOG.info("Quitting session " + id);266 try {267 driver.quit();268 } catch (Exception e) {269 // It's possible that the driver has already quit.270 }271 events.fire(new SessionClosedEvent(id));272 LOG.info("Firing node drain complete message");273 events.fire(new NodeDrainComplete(getId()));274 }275 @Override276 public boolean isSessionOwner(SessionId id) {277 return driver != null && sessionId.equals(id);278 }279 @Override280 public boolean isSupporting(Capabilities capabilities) {281 return driverInfo.isSupporting(capabilities);282 }283 @Override284 public NodeStatus getStatus() {285 return new NodeStatus(286 getId(),287 getUri(),288 1,289 ImmutableSet.of(290 new Slot(291 new SlotId(getId(), slotId),292 stereotype,293 Instant.EPOCH,294 driver == null ?295 Optional.empty() :296 Optional.of(new Session(sessionId, getUri(), stereotype, capabilities, Instant.now())))),297 isDraining() ? DRAINING : UP);298 }299 @Override300 public void drain() {301 events.fire(new NodeDrainStarted(getId()));302 draining = true;303 }304 @Override305 public HealthCheck getHealthCheck() {306 return () -> new HealthCheck.Result(isDraining() ? DRAINING : UP, "Everything is fine");307 }308 @Override309 public boolean isReady() {310 return events.isReady();311 }312}...

Full Screen

Full Screen

Source:GridModel.java Github

copy

Full Screen

...18import com.google.common.collect.ImmutableSet;19import org.openqa.selenium.events.EventBus;20import org.openqa.selenium.grid.data.Availability;21import org.openqa.selenium.grid.data.NodeDrainComplete;22import org.openqa.selenium.grid.data.NodeDrainStarted;23import org.openqa.selenium.grid.data.NodeId;24import org.openqa.selenium.grid.data.NodeRemovedEvent;25import org.openqa.selenium.grid.data.NodeStatus;26import org.openqa.selenium.grid.data.NodeStatusEvent;27import org.openqa.selenium.grid.data.Session;28import org.openqa.selenium.grid.data.SessionClosedEvent;29import org.openqa.selenium.grid.data.Slot;30import org.openqa.selenium.grid.data.SlotId;31import org.openqa.selenium.grid.security.Secret;32import org.openqa.selenium.internal.Require;33import org.openqa.selenium.remote.SessionId;34import java.time.Instant;35import java.util.HashSet;36import java.util.Iterator;37import java.util.Map;38import java.util.Optional;39import java.util.Set;40import java.util.concurrent.ConcurrentHashMap;41import java.util.concurrent.locks.Lock;42import java.util.concurrent.locks.ReadWriteLock;43import java.util.concurrent.locks.ReentrantReadWriteLock;44import java.util.logging.Logger;45import static org.openqa.selenium.grid.data.Availability.DOWN;46import static org.openqa.selenium.grid.data.Availability.DRAINING;47import static org.openqa.selenium.grid.data.Availability.UP;48public class GridModel {49 private static final Logger LOG = Logger.getLogger(GridModel.class.getName());50 private static final SessionId RESERVED = new SessionId("reserved");51 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);52 private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();53 private final EventBus events;54 public GridModel(EventBus events, Secret registrationSecret) {55 this.events = Require.nonNull("Event bus", events);56 Require.nonNull("Registration secret", registrationSecret);57 events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));58 events.addListener(NodeDrainComplete.listener(this::remove));59 events.addListener(NodeRemovedEvent.listener(this::remove));60 events.addListener(NodeStatusEvent.listener(status -> refresh(status)));61 events.addListener(SessionClosedEvent.listener(this::release));62 }63 public GridModel add(NodeStatus node) {64 Require.nonNull("Node", node);65 Lock writeLock = lock.writeLock();66 writeLock.lock();67 try {68 // If we've already added the node, remove it.69 for (Set<NodeStatus> nodes : nodes.values()) {70 Iterator<NodeStatus> iterator = nodes.iterator();71 while (iterator.hasNext()) {...

Full Screen

Full Screen

Source:NodeDrainStarted.java Github

copy

Full Screen

...19import org.openqa.selenium.events.EventListener;20import org.openqa.selenium.events.EventName;21import org.openqa.selenium.internal.Require;22import java.util.function.Consumer;23public class NodeDrainStarted extends Event {24 private static final EventName NODE_DRAIN_STARTED = new EventName("node-drain-started");25 public NodeDrainStarted(NodeId id) {26 super(NODE_DRAIN_STARTED, id);27 }28 public static EventListener<NodeId> listener(Consumer<NodeId> handler) {29 Require.nonNull("Handler", handler);30 return new EventListener<>(NODE_DRAIN_STARTED, NodeId.class, handler);31 }32}...

Full Screen

Full Screen

NodeDrainStarted

Using AI Code Generation

copy

Full Screen

1NodeDrainStarted nodeDrainStarted = new NodeDrainStarted(nodeId);2NodeDrainComplete nodeDrainComplete = new NodeDrainComplete(nodeId);3NodeDrainCancelled nodeDrainCancelled = new NodeDrainCancelled(nodeId);4NodeDrainStartedEvent nodeDrainStartedEvent = new NodeDrainStartedEvent(nodeDrainStarted);5NodeDrainCompleteEvent nodeDrainCompleteEvent = new NodeDrainCompleteEvent(nodeDrainComplete);6NodeDrainCancelledEvent nodeDrainCancelledEvent = new NodeDrainCancelledEvent(nodeDrainCancelled);7NodeDrainStartedEvent nodeDrainStartedEvent = new NodeDrainStartedEvent(nodeId);8NodeDrainCompleteEvent nodeDrainCompleteEvent = new NodeDrainCompleteEvent(nodeId);9NodeDrainCancelledEvent nodeDrainCancelledEvent = new NodeDrainCancelledEvent(nodeId);10NodeDrainStartedEvent nodeDrainStartedEvent = new NodeDrainStartedEvent(nodeId, timestamp);11NodeDrainCompleteEvent nodeDrainCompleteEvent = new NodeDrainCompleteEvent(nodeId, timestamp);12NodeDrainCancelledEvent nodeDrainCancelledEvent = new NodeDrainCancelledEvent(nodeId, timestamp);13NodeDrainStartedEvent nodeDrainStartedEvent = new NodeDrainStartedEvent(nodeId, timestamp, duration);

Full Screen

Full Screen

NodeDrainStarted

Using AI Code Generation

copy

Full Screen

1NodeDrainStarted event = new NodeDrainStarted(nodeId, Instant.now());2NodeDrainComplete event = new NodeDrainComplete(nodeId, Instant.now());3NodeDrainStopped event = new NodeDrainStopped(nodeId, Instant.now());4NodeDrainFailed event = new NodeDrainFailed(nodeId, Instant.now(), "error message");5NodeDrainCancelled event = new NodeDrainCancelled(nodeId, Instant.now());6NodeDrainStarted event = new NodeDrainStarted(nodeId, Instant.now());7NodeDrainComplete event = new NodeDrainComplete(nodeId, Instant.now());8NodeDrainStopped event = new NodeDrainStopped(nodeId, Instant.now());9NodeDrainFailed event = new NodeDrainFailed(nodeId, Instant.now(), "error message");10NodeDrainCancelled event = new NodeDrainCancelled(nodeId, Instant.now());11NodeDrainStarted event = new NodeDrainStarted(nodeId, Instant.now());12NodeDrainComplete event = new NodeDrainComplete(nodeId, Instant.now());13NodeDrainStopped event = new NodeDrainStopped(nodeId, Instant.now());14NodeDrainFailed event = new NodeDrainFailed(nodeId, Instant.now(), "error message");15NodeDrainCancelled event = new NodeDrainCancelled(nodeId, Instant.now());

Full Screen

Full Screen

NodeDrainStarted

Using AI Code Generation

copy

Full Screen

1NodeDrainStarted event = new NodeDrainStarted(nodeId);2NodeDrainComplete event = new NodeDrainComplete(nodeId);3NodeDrainStopped event = new NodeDrainStopped(nodeId);4NodeDrainStarted event = new NodeDrainStarted(nodeId);5NodeDrainComplete event = new NodeDrainComplete(nodeId);6NodeDrainStopped event = new NodeDrainStopped(nodeId);7NodeDrainStarted event = new NodeDrainStarted(nodeId);8NodeDrainComplete event = new NodeDrainComplete(nodeId);9NodeDrainStopped event = new NodeDrainStopped(nodeId);10NodeDrainStarted event = new NodeDrainStarted(nodeId);11NodeDrainComplete event = new NodeDrainComplete(nodeId);12NodeDrainStopped event = new NodeDrainStopped(nodeId);13NodeDrainStarted event = new NodeDrainStarted(nodeId);14NodeDrainComplete event = new NodeDrainComplete(nodeId);15NodeDrainStopped event = new NodeDrainStopped(nodeId);16NodeDrainStarted event = new NodeDrainStarted(nodeId);

Full Screen

Full Screen

NodeDrainStarted

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NodeDrainStarted;2import org.openqa.selenium.grid.data.NodeDrainStopped;3import org.openqa.selenium.grid.data.NodeDrainStatus;4import org.openqa.selenium.grid.data.NodeId;5import org.openqa.selenium.grid.data.NodeStatus;6import org.openqa.selenium.grid.data.NodeStatusEvent;7import org.openqa.selenium.grid.data.NodeStatusEventId;8import org.openqa.selenium.grid.data.NodeStatusEventSummary;9import org.openqa.selenium.grid.data.NodeSummary;10import org.openqa.selenium.grid.data.NodeUnregistered;11import org.openqa.selenium.grid.data.NodeUpdated;12import org.openqa.selenium.grid.data.NodeUsageRecord;13import org.openqa.selenium.grid.data.NodeUsageRecordId;14import org.openqa.selenium.grid.data.NodeUsageRecordSummary;15import org.openqa.selenium.grid.data.NodeUsageRecords;16import org.openqa.selenium.grid.data.NodeUsageRecordsCreated;17import org.openqa.selenium.grid.data.NodeUsageRecordsDeleted;18import org.openqa.selenium.grid.data.NodeUsageRecordsUpdated;19import org.openqa.selenium.grid.data.NodeUsageRecordUpdated;

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in NodeDrainStarted

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful