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

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

Source:OneShotNode.java Github

copy

Full Screen

...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 Secret registrationSecret;85 private final URI gridUri;86 private final UUID slotId = UUID.randomUUID();87 private RemoteWebDriver driver;88 private SessionId sessionId;89 private HttpClient client;90 private Capabilities capabilities;91 private Instant sessionStart = Instant.EPOCH;92 private OneShotNode(93 Tracer tracer,94 EventBus events,95 Secret registrationSecret,96 NodeId id,97 URI uri,98 URI gridUri,99 Capabilities stereotype,100 WebDriverInfo driverInfo) {101 super(tracer, id, uri, registrationSecret);102 this.registrationSecret = registrationSecret;103 this.events = Require.nonNull("Event bus", events);104 this.gridUri = Require.nonNull("Public Grid URI", gridUri);105 this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype));106 this.driverInfo = Require.nonNull("Driver info", driverInfo);107 }108 public static Node create(Config config) {109 LoggingOptions loggingOptions = new LoggingOptions(config);110 EventBusOptions eventOptions = new EventBusOptions(config);111 BaseServerOptions serverOptions = new BaseServerOptions(config);112 NodeOptions nodeOptions = new NodeOptions(config);113 Map<String, Object> raw = new Json().toType(114 config.get("k8s", "stereotype")115 .orElseThrow(() -> new ConfigException("Unable to find node stereotype")),116 MAP_TYPE);117 Capabilities stereotype = new ImmutableCapabilities(raw);118 Optional<String> driverName = config.get("k8s", "driver_name").map(String::toLowerCase);119 // Find the webdriver info corresponding to the driver name120 WebDriverInfo driverInfo = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)121 .filter(info -> info.isSupporting(stereotype))122 .filter(info -> driverName.map(name -> name.equals(info.getDisplayName().toLowerCase())).orElse(true))123 .findFirst()124 .orElseThrow(() -> new ConfigException(125 "Unable to find matching driver for %s and %s", stereotype, driverName.orElse("any driver")));126 LOG.info(String.format("Creating one-shot node for %s with stereotype %s", driverInfo, stereotype));127 LOG.info("Grid URI is: " + nodeOptions.getPublicGridUri());128 return new OneShotNode(129 loggingOptions.getTracer(),130 eventOptions.getEventBus(),131 serverOptions.getRegistrationSecret(),132 new NodeId(UUID.randomUUID()),133 serverOptions.getExternalUri(),134 nodeOptions.getPublicGridUri().orElseThrow(() -> new ConfigException("Unable to determine public grid address")),135 stereotype,136 driverInfo);137 }138 @Override139 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {140 if (driver != null) {141 throw new IllegalStateException("Only expected one session at a time");142 }143 Optional<WebDriver> driver = driverInfo.createDriver(sessionRequest.getCapabilities());144 if (!driver.isPresent()) {145 return Optional.empty();146 }147 if (!(driver.get() instanceof RemoteWebDriver)) {148 driver.get().quit();149 return Optional.empty();150 }151 this.driver = (RemoteWebDriver) driver.get();152 this.sessionId = this.driver.getSessionId();153 this.client = extractHttpClient(this.driver);154 this.capabilities = rewriteCapabilities(this.driver);155 this.sessionStart = Instant.now();156 LOG.info("Encoded response: " + JSON.toJson(ImmutableMap.of(157 "value", ImmutableMap.of(158 "sessionId", sessionId,159 "capabilities", capabilities))));160 events.fire(new NodeDrainStarted(getId()));161 return Optional.of(162 new CreateSessionResponse(163 getSession(sessionId),164 JSON.toJson(ImmutableMap.of(165 "value", ImmutableMap.of(166 "sessionId", sessionId,167 "capabilities", capabilities))).getBytes(UTF_8)));168 }169 private HttpClient extractHttpClient(RemoteWebDriver driver) {170 CommandExecutor executor = driver.getCommandExecutor();171 try {172 Field client = null;173 Class<?> current = executor.getClass();174 while (client == null && (current != null || Object.class.equals(current))) {175 client = findClientField(current);176 current = current.getSuperclass();177 }178 if (client == null) {179 throw new IllegalStateException("Unable to find client field in " + executor.getClass());180 }181 if (!HttpClient.class.isAssignableFrom(client.getType())) {182 throw new IllegalStateException("Client field is not assignable to http client");183 }184 client.setAccessible(true);185 return (HttpClient) client.get(executor);186 } catch (ReflectiveOperationException e) {187 throw new IllegalStateException(e);188 }189 }190 private Field findClientField(Class<?> clazz) {191 try {192 return clazz.getDeclaredField("client");193 } catch (NoSuchFieldException e) {194 return null;195 }196 }197 private Capabilities rewriteCapabilities(RemoteWebDriver driver) {198 // Rewrite the se:options if necessary199 Object rawSeleniumOptions = driver.getCapabilities().getCapability("se:options");200 if (rawSeleniumOptions == null || rawSeleniumOptions instanceof Map) {201 @SuppressWarnings("unchecked") Map<String, Object> original = (Map<String, Object>) rawSeleniumOptions;202 Map<String, Object> updated = new TreeMap<>(original == null ? new HashMap<>() : original);203 String cdpPath = String.format("/session/%s/se/cdp", driver.getSessionId());204 updated.put("cdp", rewrite(cdpPath));205 return new PersistentCapabilities(driver.getCapabilities()).setCapability("se:options", updated);206 }207 return ImmutableCapabilities.copyOf(driver.getCapabilities());208 }209 private URI rewrite(String path) {210 try {211 return new URI(212 gridUri.getScheme(),213 gridUri.getUserInfo(),214 gridUri.getHost(),215 gridUri.getPort(),216 path,217 null,218 null);219 } catch (URISyntaxException e) {220 throw new RuntimeException(e);221 }222 }223 @Override224 public HttpResponse executeWebDriverCommand(HttpRequest req) {225 LOG.info("Executing " + req);226 HttpResponse res = client.execute(req);227 if (DELETE.equals(req.getMethod()) && req.getUri().equals("/session/" + sessionId)) {228 // Ensure the response is sent before we viciously kill the node229 new Thread(230 () -> {231 try {232 Thread.sleep(500);233 } catch (InterruptedException e) {234 Thread.currentThread().interrupt();235 throw new RuntimeException(e);236 }237 LOG.info("Stopping session: " + sessionId);238 stop(sessionId);239 },240 "Node clean up: " + getId())241 .start();242 }243 return res;244 }245 @Override246 public Session getSession(SessionId id) throws NoSuchSessionException {247 if (!isSessionOwner(id)) {248 throw new NoSuchSessionException("Unable to find session with id: " + id);249 }250 return new Session(251 sessionId,252 getUri(),253 stereotype,254 capabilities,255 sessionStart); }256 @Override257 public HttpResponse uploadFile(HttpRequest req, SessionId id) {258 return null;259 }260 @Override261 public void stop(SessionId id) throws NoSuchSessionException {262 LOG.info("Stop has been called: " + id);263 Require.nonNull("Session ID", id);264 if (!isSessionOwner(id)) {265 throw new NoSuchSessionException("Unable to find session " + id);266 }267 LOG.info("Quitting session " + id);268 try {269 driver.quit();270 } catch (Exception e) {271 // It's possible that the driver has already quit.272 }273 events.fire(new SessionClosedEvent(id));274 LOG.info("Firing node drain complete message");275 events.fire(new NodeDrainComplete(getId()));276 }277 @Override278 public boolean isSessionOwner(SessionId id) {279 return driver != null && sessionId.equals(id);280 }281 @Override282 public boolean isSupporting(Capabilities capabilities) {283 return driverInfo.isSupporting(capabilities);284 }285 @Override286 public NodeStatus getStatus() {287 return new NodeStatus(288 getId(),289 getUri(),290 1,291 ImmutableSet.of(292 new Slot(293 new SlotId(getId(), slotId),294 stereotype,295 Instant.EPOCH,296 driver == null ?297 Optional.empty() :298 Optional.of(new Session(sessionId, getUri(), stereotype, capabilities, Instant.now())))),299 isDraining() ? DRAINING : UP,300 registrationSecret);301 }302 @Override303 public void drain() {304 events.fire(new NodeDrainStarted(getId()));305 draining = true;306 }307 @Override...

Full Screen

Full Screen

Source:GridModel.java Github

copy

Full Screen

...27import org.openqa.selenium.grid.data.NodeStatusEvent;28import org.openqa.selenium.grid.data.Session;29import org.openqa.selenium.grid.data.SessionClosedEvent;30import org.openqa.selenium.grid.data.Slot;31import org.openqa.selenium.grid.data.SlotId;32import org.openqa.selenium.grid.security.Secret;33import org.openqa.selenium.internal.Require;34import org.openqa.selenium.remote.SessionId;35import java.time.Instant;36import java.util.HashSet;37import java.util.Iterator;38import java.util.Map;39import java.util.Objects;40import java.util.Optional;41import java.util.Set;42import java.util.concurrent.ConcurrentHashMap;43import java.util.concurrent.locks.Lock;44import java.util.concurrent.locks.ReadWriteLock;45import java.util.concurrent.locks.ReentrantReadWriteLock;46import java.util.logging.Logger;47import static org.openqa.selenium.grid.data.Availability.DOWN;48import static org.openqa.selenium.grid.data.Availability.DRAINING;49import static org.openqa.selenium.grid.data.Availability.UP;50public class GridModel {51 private static final Logger LOG = Logger.getLogger(GridModel.class.getName());52 private static final SessionId RESERVED = new SessionId("reserved");53 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);54 private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();55 private final EventBus events;56 public GridModel(EventBus events, Secret registrationSecret) {57 this.events = Require.nonNull("Event bus", events);58 events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));59 events.addListener(NodeDrainComplete.listener(this::remove));60 events.addListener(NodeRemovedEvent.listener(this::remove));61 events.addListener(NodeStatusEvent.listener(status -> refresh(registrationSecret, status)));62 events.addListener(SessionClosedEvent.listener(this::release));63 }64 public GridModel add(NodeStatus node) {65 Require.nonNull("Node", node);66 Lock writeLock = lock.writeLock();67 writeLock.lock();68 try {69 // If we've already added the node, remove it.70 for (Set<NodeStatus> nodes : nodes.values()) {71 Iterator<NodeStatus> iterator = nodes.iterator();72 while (iterator.hasNext()) {73 NodeStatus next = iterator.next();74 // If the ID is the same, we're re-adding a node. If the URI is the same a node probably restarted75 if (next.getId().equals(node.getId()) || next.getUri().equals(node.getUri())) {76 LOG.info(String.format("Re-adding node with id %s and URI %s.", node.getId(), node.getUri()));77 iterator.remove();78 }79 }80 }81 // Nodes are initially added in the "down" state until something changes their availability82 nodes(DOWN).add(node);83 } finally {84 writeLock.unlock();85 }86 return this;87 }88 public GridModel refresh(Secret registrationSecret, NodeStatus status) {89 Require.nonNull("Node status", status);90 Secret statusSecret = status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret());91 if (!Objects.equals(registrationSecret, statusSecret)) {92 LOG.severe(String.format("Node at %s failed to send correct registration secret. Node NOT refreshed.", status.getUri()));93 events.fire(new NodeRejectedEvent(status.getUri()));94 return this;95 }96 Lock writeLock = lock.writeLock();97 writeLock.lock();98 try {99 AvailabilityAndNode availabilityAndNode = findNode(status.getId());100 if (availabilityAndNode == null) {101 return this;102 }103 // if the node was marked as "down", keep it down until a healthcheck passes:104 // just because the node can hit the event bus doesn't mean it's reachable105 if (DOWN.equals(availabilityAndNode.availability)) {106 nodes(DOWN).remove(availabilityAndNode.status);107 nodes(DOWN).add(status);108 return this;109 }110 // But do trust the node if it tells us it's draining111 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);112 nodes(status.getAvailability()).add(status);113 return this;114 } finally {115 writeLock.unlock();116 }117 }118 public GridModel remove(NodeId id) {119 Require.nonNull("Node ID", id);120 Lock writeLock = lock.writeLock();121 writeLock.lock();122 try {123 AvailabilityAndNode availabilityAndNode = findNode(id);124 if (availabilityAndNode == null) {125 return this;126 }127 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);128 return this;129 } finally {130 writeLock.unlock();131 }132 }133 public Availability setAvailability(NodeId id, Availability availability) {134 Require.nonNull("Node ID", id);135 Require.nonNull("Availability", availability);136 Lock writeLock = lock.writeLock();137 writeLock.lock();138 try {139 AvailabilityAndNode availabilityAndNode = findNode(id);140 if (availabilityAndNode == null) {141 return DOWN;142 }143 if (availability.equals(availabilityAndNode.availability)) {144 return availability;145 }146 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);147 nodes(availability).add(availabilityAndNode.status);148 LOG.info(String.format(149 "Switching node %s (uri: %s) from %s to %s",150 id,151 availabilityAndNode.status.getUri(),152 availabilityAndNode.availability,153 availability));154 return availabilityAndNode.availability;155 } finally {156 writeLock.unlock();157 }158 }159 public boolean reserve(SlotId slotId) {160 Lock writeLock = lock.writeLock();161 writeLock.lock();162 try {163 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());164 if (node == null) {165 LOG.warning(String.format("Asked to reserve slot on node %s, but unable to find node", slotId.getOwningNodeId()));166 return false;167 }168 if (!UP.equals(node.availability)) {169 LOG.warning(String.format(170 "Asked to reserve a slot on node %s, but not is %s",171 slotId.getOwningNodeId(),172 node.availability));173 return false;174 }175 Optional<Slot> maybeSlot = node.status.getSlots().stream()176 .filter(slot -> slotId.equals(slot.getId()))177 .findFirst();178 if (!maybeSlot.isPresent()) {179 LOG.warning(String.format(180 "Asked to reserve slot on node %s, but no slot with id %s found",181 node.status.getId(),182 slotId));183 return false;184 }185 reserve(node.status, maybeSlot.get());186 return true;187 } finally {188 writeLock.unlock();189 }190 }191 public Set<NodeStatus> getSnapshot() {192 Lock readLock = this.lock.readLock();193 readLock.lock();194 try {195 ImmutableSet.Builder<NodeStatus> snapshot = ImmutableSet.builder();196 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {197 entry.getValue().stream()198 .map(status -> rewrite(status, entry.getKey()))199 .forEach(snapshot::add);200 }201 return snapshot.build();202 } finally {203 readLock.unlock();204 }205 }206 private Set<NodeStatus> nodes(Availability availability) {207 return nodes.computeIfAbsent(availability, ignored -> new HashSet<>());208 }209 private AvailabilityAndNode findNode(NodeId id) {210 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {211 for (NodeStatus nodeStatus : entry.getValue()) {212 if (id.equals(nodeStatus.getId())) {213 return new AvailabilityAndNode(entry.getKey(), nodeStatus);214 }215 }216 }217 return null;218 }219 private NodeStatus rewrite(NodeStatus status, Availability availability) {220 return new NodeStatus(221 status.getId(),222 status.getUri(),223 status.getMaxSessionCount(),224 status.getSlots(),225 availability,226 status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret()));227 }228 private void release(SessionId id) {229 if (id == null) {230 return;231 }232 Lock writeLock = lock.writeLock();233 writeLock.lock();234 try {235 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {236 for (NodeStatus node : entry.getValue()) {237 for (Slot slot : node.getSlots()) {238 if (!slot.getSession().isPresent()) {239 continue;240 }241 if (id.equals(slot.getSession().get().getId())) {242 Slot released = new Slot(243 slot.getId(),244 slot.getStereotype(),245 slot.getLastStarted(),246 Optional.empty());247 amend(entry.getKey(), node, released);248 return;249 }250 }251 }252 }253 } finally {254 writeLock.unlock();255 }256 }257 private void reserve(NodeStatus status, Slot slot) {258 Instant now = Instant.now();259 Slot reserved = new Slot(260 slot.getId(),261 slot.getStereotype(),262 now,263 Optional.of(new Session(264 RESERVED,265 status.getUri(),266 slot.getStereotype(),267 slot.getStereotype(),268 now)));269 amend(UP, status, reserved);270 }271 public void setSession(SlotId slotId, Session session) {272 Require.nonNull("Slot ID", slotId);273 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());274 if (node == null) {275 LOG.warning("Grid model and reality have diverged. Unable to find node " + slotId.getOwningNodeId());276 return;277 }278 Optional<Slot> maybeSlot = node.status.getSlots().stream()279 .filter(slot -> slotId.equals(slot.getId()))280 .findFirst();281 if (!maybeSlot.isPresent()) {282 LOG.warning("Grid model and reality have diverged. Unable to find slot " + slotId);283 return;284 }285 Slot slot = maybeSlot.get();...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...33import org.openqa.selenium.grid.data.NodeRemovedEvent;34import org.openqa.selenium.grid.data.NodeStatus;35import org.openqa.selenium.grid.data.NodeStatusEvent;36import org.openqa.selenium.grid.data.Slot;37import org.openqa.selenium.grid.data.SlotId;38import org.openqa.selenium.grid.distributor.Distributor;39import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;40import org.openqa.selenium.grid.log.LoggingOptions;41import org.openqa.selenium.grid.node.HealthCheck;42import org.openqa.selenium.grid.node.Node;43import org.openqa.selenium.grid.node.remote.RemoteNode;44import org.openqa.selenium.grid.security.Secret;45import org.openqa.selenium.grid.server.BaseServerOptions;46import org.openqa.selenium.grid.server.EventBusOptions;47import org.openqa.selenium.grid.server.NetworkOptions;48import org.openqa.selenium.grid.sessionmap.SessionMap;49import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;50import org.openqa.selenium.internal.Require;51import org.openqa.selenium.remote.http.HttpClient;52import org.openqa.selenium.remote.tracing.Tracer;53import org.openqa.selenium.status.HasReadyState;54import java.time.Duration;55import java.util.ArrayList;56import java.util.HashMap;57import java.util.List;58import java.util.Map;59import java.util.Objects;60import java.util.Optional;61import java.util.Set;62import java.util.concurrent.locks.Lock;63import java.util.concurrent.locks.ReadWriteLock;64import java.util.concurrent.locks.ReentrantReadWriteLock;65import java.util.function.Supplier;66import java.util.logging.Level;67import java.util.logging.Logger;68import static com.google.common.collect.ImmutableSet.toImmutableSet;69import static org.openqa.selenium.grid.data.Availability.DOWN;70import static org.openqa.selenium.grid.data.Availability.DRAINING;71public class LocalDistributor extends Distributor {72 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());73 private final Tracer tracer;74 private final EventBus bus;75 private final HttpClient.Factory clientFactory;76 private final SessionMap sessions;77 private final Regularly hostChecker = new Regularly("distributor host checker");78 private final Map<NodeId, Runnable> allChecks = new HashMap<>();79 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);80 private final GridModel model;81 private final Map<NodeId, Node> nodes;82 public LocalDistributor(83 Tracer tracer,84 EventBus bus,85 HttpClient.Factory clientFactory,86 SessionMap sessions,87 Secret registrationSecret) {88 super(tracer, clientFactory, new DefaultSlotSelector(), sessions, registrationSecret);89 this.tracer = Require.nonNull("Tracer", tracer);90 this.bus = Require.nonNull("Event bus", bus);91 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);92 this.sessions = Require.nonNull("Session map", sessions);93 this.model = new GridModel(bus, registrationSecret);94 this.nodes = new HashMap<>();95 bus.addListener(NodeStatusEvent.listener(status -> register(registrationSecret, status)));96 bus.addListener(NodeStatusEvent.listener(status -> model.refresh(registrationSecret, status)));97 bus.addListener(NodeDrainComplete.listener(this::remove));98 }99 public static Distributor create(Config config) {100 Tracer tracer = new LoggingOptions(config).getTracer();101 EventBus bus = new EventBusOptions(config).getEventBus();102 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);103 SessionMap sessions = new SessionMapOptions(config).getSessionMap();104 BaseServerOptions serverOptions = new BaseServerOptions(config);105 return new LocalDistributor(tracer, bus, clientFactory, sessions, serverOptions.getRegistrationSecret());106 }107 @Override108 public boolean isReady() {109 try {110 return ImmutableSet.of(bus, sessions).parallelStream()111 .map(HasReadyState::isReady)112 .reduce(true, Boolean::logicalAnd);113 } catch (RuntimeException e) {114 return false;115 }116 }117 private void register(Secret registrationSecret, NodeStatus status) {118 Require.nonNull("Node", status);119 Secret nodeSecret = status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret());120 if (!Objects.equals(registrationSecret, nodeSecret)) {121 LOG.severe(String.format("Node at %s failed to send correct registration secret. Node NOT registered.", status.getUri()));122 bus.fire(new NodeRejectedEvent(status.getUri()));123 return;124 }125 Lock writeLock = lock.writeLock();126 writeLock.lock();127 try {128 if (nodes.containsKey(status.getId())) {129 return;130 }131 Set<Capabilities> capabilities = status.getSlots().stream()132 .map(Slot::getStereotype)133 .map(ImmutableCapabilities::copyOf)134 .collect(toImmutableSet());135 // A new node! Add this as a remote node, since we've not called add136 RemoteNode remoteNode = new RemoteNode(137 tracer,138 clientFactory,139 status.getId(),140 status.getUri(),141 registrationSecret,142 capabilities);143 add(remoteNode);144 } finally {145 writeLock.unlock();146 }147 }148 @Override149 public LocalDistributor add(Node node) {150 Require.nonNull("Node", node);151 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));152 nodes.put(node.getId(), node);153 model.add(node.getStatus());154 // Extract the health check155 Runnable runnableHealthCheck = asRunnableHealthCheck(node);156 allChecks.put(node.getId(), runnableHealthCheck);157 hostChecker.submit(runnableHealthCheck, Duration.ofMinutes(5), Duration.ofSeconds(30));158 bus.fire(new NodeAddedEvent(node.getId()));159 return this;160 }161 private Runnable asRunnableHealthCheck(Node node) {162 HealthCheck healthCheck = node.getHealthCheck();163 NodeId id = node.getId();164 return () -> {165 HealthCheck.Result result;166 try {167 result = healthCheck.check();168 } catch (Exception e) {169 LOG.log(Level.WARNING, "Unable to process node " + id, e);170 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");171 }172 Lock writeLock = lock.writeLock();173 writeLock.lock();174 try {175 model.setAvailability(id, result.getAvailability());176 } finally {177 writeLock.unlock();178 }179 };180 }181 @Override182 public boolean drain(NodeId nodeId) {183 Node node = nodes.get(nodeId);184 if (node == null) {185 LOG.info("Asked to drain unregistered node " + nodeId);186 return false;187 }188 Lock writeLock = lock.writeLock();189 writeLock.lock();190 try {191 node.drain();192 model.setAvailability(nodeId, DRAINING);193 } finally {194 writeLock.unlock();195 }196 return node.isDraining();197 }198 public void remove(NodeId nodeId) {199 Lock writeLock = lock.writeLock();200 writeLock.lock();201 try {202 model.remove(nodeId);203 Runnable runnable = allChecks.remove(nodeId);204 if (runnable != null) {205 hostChecker.remove(runnable);206 }207 } finally {208 writeLock.unlock();209 bus.fire(new NodeRemovedEvent(nodeId));210 }211 }212 @Override213 public DistributorStatus getStatus() {214 Lock readLock = this.lock.readLock();215 readLock.lock();216 try {217 return new DistributorStatus(model.getSnapshot());218 } finally {219 readLock.unlock();220 }221 }222 @Beta223 public void refresh() {224 List<Runnable> allHealthChecks = new ArrayList<>();225 Lock readLock = this.lock.readLock();226 readLock.lock();227 try {228 allHealthChecks.addAll(allChecks.values());229 } finally {230 readLock.unlock();231 }232 allHealthChecks.parallelStream().forEach(Runnable::run);233 }234 @Override235 protected Set<NodeStatus> getAvailableNodes() {236 Lock readLock = this.lock.readLock();237 readLock.lock();238 try {239 return model.getSnapshot().stream()240 .filter(node -> !DOWN.equals(node.getAvailability()))241 .collect(toImmutableSet());242 } finally {243 readLock.unlock();244 }245 }246 @Override247 protected Supplier<CreateSessionResponse> reserve(SlotId slotId, CreateSessionRequest request) {248 Require.nonNull("Slot ID", slotId);249 Require.nonNull("New Session request", request);250 Lock writeLock = this.lock.writeLock();251 writeLock.lock();252 try {253 Node node = nodes.get(slotId.getOwningNodeId());254 if (node == null) {255 return () -> {256 throw new SessionNotCreatedException("Unable to find node");257 };258 }259 model.reserve(slotId);260 return () -> {261 Optional<CreateSessionResponse> response = node.newSession(request);...

Full Screen

Full Screen

Source:RemoteDistributor.java Github

copy

Full Screen

...20import org.openqa.selenium.grid.data.CreateSessionResponse;21import org.openqa.selenium.grid.data.DistributorStatus;22import org.openqa.selenium.grid.data.NodeId;23import org.openqa.selenium.grid.data.NodeStatus;24import org.openqa.selenium.grid.data.SlotId;25import org.openqa.selenium.grid.distributor.Distributor;26import org.openqa.selenium.grid.node.Node;27import org.openqa.selenium.grid.security.Secret;28import org.openqa.selenium.grid.sessionmap.NullSessionMap;29import org.openqa.selenium.grid.web.Values;30import org.openqa.selenium.internal.Require;31import org.openqa.selenium.remote.http.HttpClient;32import org.openqa.selenium.remote.http.HttpHandler;33import org.openqa.selenium.remote.http.HttpRequest;34import org.openqa.selenium.remote.http.HttpResponse;35import org.openqa.selenium.remote.tracing.HttpTracing;36import org.openqa.selenium.remote.tracing.Tracer;37import java.net.URL;38import java.util.Set;39import java.util.function.Supplier;40import java.util.logging.Logger;41import static org.openqa.selenium.remote.http.Contents.asJson;42import static org.openqa.selenium.remote.http.HttpMethod.DELETE;43import static org.openqa.selenium.remote.http.HttpMethod.GET;44import static org.openqa.selenium.remote.http.HttpMethod.POST;45public class RemoteDistributor extends Distributor {46 private static final Logger LOG = Logger.getLogger("Selenium Distributor (Remote)");47 private final HttpHandler client;48 public RemoteDistributor(Tracer tracer, HttpClient.Factory factory, URL url, Secret registrationSecret) {49 super(50 tracer,51 factory,52 (caps, nodes) -> {throw new UnsupportedOperationException("host selection");},53 new NullSessionMap(tracer),54 registrationSecret);55 this.client = factory.createClient(url);56 }57 @Override58 public boolean isReady() {59 try {60 return client.execute(new HttpRequest(GET, "/readyz")).isSuccessful();61 } catch (Exception e) {62 return false;63 }64 }65 @Override66 public CreateSessionResponse newSession(HttpRequest request)67 throws SessionNotCreatedException {68 HttpRequest upstream = new HttpRequest(POST, "/se/grid/distributor/session");69 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);70 upstream.setContent(request.getContent());71 HttpResponse response = client.execute(upstream);72 return Values.get(response, CreateSessionResponse.class);73 }74 @Override75 public RemoteDistributor add(Node node) {76 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node");77 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);78 request.setContent(asJson(node.getStatus()));79 HttpResponse response = client.execute(request);80 Values.get(response, Void.class);81 LOG.info(String.format("Added node %s.", node.getId()));82 return this;83 }84 @Override85 public boolean drain(NodeId nodeId) {86 Require.nonNull("Node ID", nodeId);87 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node/" + nodeId + "/drain");88 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);89 request.setContent(asJson(nodeId));90 HttpResponse response = client.execute(request);91 return Values.get(response, Boolean.class);92 }93 @Override94 public void remove(NodeId nodeId) {95 Require.nonNull("Node ID", nodeId);96 HttpRequest request = new HttpRequest(DELETE, "/se/grid/distributor/node/" + nodeId);97 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);98 HttpResponse response = client.execute(request);99 Values.get(response, Void.class);100 }101 @Override102 public DistributorStatus getStatus() {103 HttpRequest request = new HttpRequest(GET, "/se/grid/distributor/status");104 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);105 HttpResponse response = client.execute(request);106 return Values.get(response, DistributorStatus.class);107 }108 @Override109 protected Set<NodeStatus> getAvailableNodes() {110 throw new UnsupportedOperationException("getModel is not required for remote sessions");111 }112 @Override113 protected Supplier<CreateSessionResponse> reserve(SlotId slot, CreateSessionRequest request) {114 throw new UnsupportedOperationException("reserve is not required for remote sessions");115 }116}...

Full Screen

Full Screen

SlotId

Using AI Code Generation

copy

Full Screen

1SlotId slotId = new SlotId(UUID.randomUUID());2SessionId sessionId = new SessionId(UUID.randomUUID());3NodeId nodeId = new NodeId(UUID.randomUUID());4NodeStatus nodeStatus = new NodeStatus(nodeId, 1, 5, 1, 5, 1);5NodeStatusEvent nodeStatusEvent = new NodeStatusEvent(nodeId, 1, 5, 1, 5, 1);6NodeStatusListener nodeStatusListener = new NodeStatusListener() {7 public void onSessionCreated(SessionId sessionId, SlotId slotId) {8 }9 public void onSessionClosed(SessionId sessionId) {10 }11 public void onSlotCreated(SlotId slotId) {12 }13 public void onSlotDeleted(SlotId slotId) {14 }15};16NodeStatusEvent.Listener nodeStatusEventListener = new NodeStatusEvent.Listener() {17 public void onEvent(NodeStatusEvent event) {

Full Screen

Full Screen

SlotId

Using AI Code Generation

copy

Full Screen

1SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));2SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));3SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));4SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));5SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));6SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));7SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));8SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));9SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));10SlotId slotId = new SlotId(UUID.fromString("6a4c1f0d-4c7a-4a4d-9d2d-0a0a0a0a0a0a"));

Full Screen

Full Screen
copy
1 @Override2 public void failure(RetrofitError error){3 if(error.getResponse().getStatus()==201){4 LogUtil.INSTANCE.debug("Success : " + error.toString());5 callback.success(error.getResponse().getBody);6 }else{7 LogUtil.INSTANCE.debug("failure: " + error.toString());8 callback.failure(error);9 }10 }11
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 popular Stackoverflow questions on SlotId

Most used methods in SlotId

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