1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/test/chromedriver/chrome/devtools_client_impl.h"
8 #include "base/json/json_reader.h"
9 #include "base/json/json_writer.h"
10 #include "base/logging.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/values.h"
13 #include "chrome/test/chromedriver/chrome/devtools_event_listener.h"
14 #include "chrome/test/chromedriver/chrome/log.h"
15 #include "chrome/test/chromedriver/chrome/status.h"
16 #include "chrome/test/chromedriver/chrome/util.h"
17 #include "chrome/test/chromedriver/net/sync_websocket.h"
18 #include "chrome/test/chromedriver/net/url_request_context_getter.h"
22 const char kInspectorContextError[] =
23 "Execution context with given id not found.";
25 Status ParseInspectorError(const std::string& error_json) {
26 scoped_ptr<base::Value> error(base::JSONReader::Read(error_json));
27 base::DictionaryValue* error_dict;
28 if (!error || !error->GetAsDictionary(&error_dict))
29 return Status(kUnknownError, "inspector error with no error message");
30 std::string error_message;
31 if (error_dict->GetString("message", &error_message) &&
32 error_message == kInspectorContextError) {
33 return Status(kNoSuchExecutionContext);
35 return Status(kUnknownError, "unhandled inspector error: " + error_json);
38 class ScopedIncrementer {
40 explicit ScopedIncrementer(int* count) : count_(count) {
43 ~ScopedIncrementer() {
51 Status ConditionIsMet(bool* is_condition_met) {
52 *is_condition_met = true;
56 Status FakeCloseFrontends() {
64 InspectorEvent::InspectorEvent() {}
66 InspectorEvent::~InspectorEvent() {}
68 InspectorCommandResponse::InspectorCommandResponse() {}
70 InspectorCommandResponse::~InspectorCommandResponse() {}
72 } // namespace internal
74 const char DevToolsClientImpl::kBrowserwideDevToolsClientId[] = "browser";
76 DevToolsClientImpl::DevToolsClientImpl(
77 const SyncWebSocketFactory& factory,
78 const std::string& url,
79 const std::string& id)
80 : socket_(factory.Run().Pass()),
84 frontend_closer_func_(base::Bind(&FakeCloseFrontends)),
85 parser_func_(base::Bind(&internal::ParseInspectorMessage)),
86 unnotified_event_(NULL),
90 DevToolsClientImpl::DevToolsClientImpl(
91 const SyncWebSocketFactory& factory,
92 const std::string& url,
93 const std::string& id,
94 const FrontendCloserFunc& frontend_closer_func)
95 : socket_(factory.Run().Pass()),
99 frontend_closer_func_(frontend_closer_func),
100 parser_func_(base::Bind(&internal::ParseInspectorMessage)),
101 unnotified_event_(NULL),
105 DevToolsClientImpl::DevToolsClientImpl(
106 const SyncWebSocketFactory& factory,
107 const std::string& url,
108 const std::string& id,
109 const FrontendCloserFunc& frontend_closer_func,
110 const ParserFunc& parser_func)
111 : socket_(factory.Run().Pass()),
115 frontend_closer_func_(frontend_closer_func),
116 parser_func_(parser_func),
117 unnotified_event_(NULL),
121 DevToolsClientImpl::~DevToolsClientImpl() {}
123 void DevToolsClientImpl::SetParserFuncForTesting(
124 const ParserFunc& parser_func) {
125 parser_func_ = parser_func;
128 const std::string& DevToolsClientImpl::GetId() {
132 bool DevToolsClientImpl::WasCrashed() {
136 Status DevToolsClientImpl::ConnectIfNecessary() {
138 return Status(kUnknownError, "cannot connect when nested");
140 if (socket_->IsConnected())
143 if (!socket_->Connect(url_)) {
144 // Try to close devtools frontend and then reconnect.
145 Status status = frontend_closer_func_.Run();
146 if (status.IsError())
148 if (!socket_->Connect(url_))
149 return Status(kDisconnected, "unable to connect to renderer");
152 unnotified_connect_listeners_ = listeners_;
153 unnotified_event_listeners_.clear();
154 response_info_map_.clear();
156 // Notify all listeners of the new connection. Do this now so that any errors
157 // that occur are reported now instead of later during some unrelated call.
158 // Also gives listeners a chance to send commands before other clients.
159 return EnsureListenersNotifiedOfConnect();
162 Status DevToolsClientImpl::SendCommand(
163 const std::string& method,
164 const base::DictionaryValue& params) {
165 scoped_ptr<base::DictionaryValue> result;
166 return SendCommandInternal(method, params, &result);
169 Status DevToolsClientImpl::SendCommandAndGetResult(
170 const std::string& method,
171 const base::DictionaryValue& params,
172 scoped_ptr<base::DictionaryValue>* result) {
173 scoped_ptr<base::DictionaryValue> intermediate_result;
174 Status status = SendCommandInternal(method, params, &intermediate_result);
175 if (status.IsError())
177 if (!intermediate_result)
178 return Status(kUnknownError, "inspector response missing result");
179 result->reset(intermediate_result.release());
183 void DevToolsClientImpl::AddListener(DevToolsEventListener* listener) {
185 listeners_.push_back(listener);
188 Status DevToolsClientImpl::HandleReceivedEvents() {
189 return HandleEventsUntil(base::Bind(&ConditionIsMet), base::TimeDelta());
192 Status DevToolsClientImpl::HandleEventsUntil(
193 const ConditionalFunc& conditional_func, const base::TimeDelta& timeout) {
194 if (!socket_->IsConnected())
195 return Status(kDisconnected, "not connected to DevTools");
197 base::TimeTicks deadline = base::TimeTicks::Now() + timeout;
198 base::TimeDelta next_message_timeout = timeout;
200 if (!socket_->HasNextMessage()) {
201 bool is_condition_met = false;
202 Status status = conditional_func.Run(&is_condition_met);
203 if (status.IsError())
205 if (is_condition_met)
209 Status status = ProcessNextMessage(-1, next_message_timeout);
210 if (status.IsError())
212 next_message_timeout = deadline - base::TimeTicks::Now();
216 DevToolsClientImpl::ResponseInfo::ResponseInfo(const std::string& method)
217 : state(kWaiting), method(method) {}
219 DevToolsClientImpl::ResponseInfo::~ResponseInfo() {}
221 Status DevToolsClientImpl::SendCommandInternal(
222 const std::string& method,
223 const base::DictionaryValue& params,
224 scoped_ptr<base::DictionaryValue>* result) {
225 if (!socket_->IsConnected())
226 return Status(kDisconnected, "not connected to DevTools");
228 int command_id = next_id_++;
229 base::DictionaryValue command;
230 command.SetInteger("id", command_id);
231 command.SetString("method", method);
232 command.Set("params", params.DeepCopy());
233 std::string message = SerializeValue(&command);
235 VLOG(1) << "DEVTOOLS COMMAND " << method << " (id=" << command_id << ") "
236 << FormatValueForDisplay(params);
238 if (!socket_->Send(message))
239 return Status(kDisconnected, "unable to send message to renderer");
241 linked_ptr<ResponseInfo> response_info =
242 make_linked_ptr(new ResponseInfo(method));
243 response_info_map_[command_id] = response_info;
244 while (response_info->state == kWaiting) {
245 Status status = ProcessNextMessage(
246 command_id, base::TimeDelta::FromMinutes(10));
247 if (status.IsError()) {
248 if (response_info->state == kReceived)
249 response_info_map_.erase(command_id);
253 if (response_info->state == kBlocked) {
254 response_info->state = kIgnored;
255 return Status(kUnexpectedAlertOpen);
257 CHECK_EQ(response_info->state, kReceived);
258 internal::InspectorCommandResponse& response = response_info->response;
259 if (!response.result)
260 return ParseInspectorError(response.error);
261 *result = response.result.Pass();
265 Status DevToolsClientImpl::ProcessNextMessage(
267 const base::TimeDelta& timeout) {
268 ScopedIncrementer increment_stack_count(&stack_count_);
270 Status status = EnsureListenersNotifiedOfConnect();
271 if (status.IsError())
273 status = EnsureListenersNotifiedOfEvent();
274 if (status.IsError())
276 status = EnsureListenersNotifiedOfCommandResponse();
277 if (status.IsError())
280 // The command response may have already been received (in which case it will
281 // have been deleted from |response_info_map_|) or blocked while notifying
283 if (expected_id != -1) {
284 ResponseInfoMap::iterator iter = response_info_map_.find(expected_id);
285 if (iter == response_info_map_.end() || iter->second->state != kWaiting)
290 return Status(kTabCrashed);
293 switch (socket_->ReceiveNextMessage(&message, timeout)) {
294 case SyncWebSocket::kOk:
296 case SyncWebSocket::kDisconnected: {
297 std::string err = "Unable to receive message from renderer";
299 return Status(kDisconnected, err);
301 case SyncWebSocket::kTimeout: {
303 "Timed out receiving message from renderer: " +
304 base::StringPrintf("%.3lf", timeout.InSecondsF());
306 return Status(kTimeout, err);
313 internal::InspectorMessageType type;
314 internal::InspectorEvent event;
315 internal::InspectorCommandResponse response;
316 if (!parser_func_.Run(message, expected_id, &type, &event, &response)) {
317 LOG(ERROR) << "Bad inspector message: " << message;
318 return Status(kUnknownError, "bad inspector message: " + message);
321 if (type == internal::kEventMessageType)
322 return ProcessEvent(event);
323 CHECK_EQ(type, internal::kCommandResponseMessageType);
324 return ProcessCommandResponse(response);
327 Status DevToolsClientImpl::ProcessEvent(const internal::InspectorEvent& event) {
329 VLOG(1) << "DEVTOOLS EVENT " << event.method << " "
330 << FormatValueForDisplay(*event.params);
332 unnotified_event_listeners_ = listeners_;
333 unnotified_event_ = &event;
334 Status status = EnsureListenersNotifiedOfEvent();
335 unnotified_event_ = NULL;
336 if (status.IsError())
338 if (event.method == "Inspector.detached")
339 return Status(kDisconnected, "received Inspector.detached event");
340 if (event.method == "Inspector.targetCrashed") {
342 return Status(kTabCrashed);
344 if (event.method == "Page.javascriptDialogOpening") {
345 // A command may have opened the dialog, which will block the response.
346 // To find out which one (if any), do a round trip with a simple command
347 // to the renderer and afterwards see if any of the commands still haven't
348 // received a response.
349 // This relies on the fact that DevTools commands are processed
350 // sequentially. This may break if any of the commands are asynchronous.
351 // If for some reason the round trip command fails, mark all the waiting
352 // commands as blocked and return the error. This is better than risking
354 int max_id = next_id_;
355 base::DictionaryValue enable_params;
356 enable_params.SetString("purpose", "detect if alert blocked any cmds");
357 Status enable_status = SendCommand("Inspector.enable", enable_params);
358 for (ResponseInfoMap::const_iterator iter = response_info_map_.begin();
359 iter != response_info_map_.end(); ++iter) {
360 if (iter->first > max_id)
362 if (iter->second->state == kWaiting)
363 iter->second->state = kBlocked;
365 if (enable_status.IsError())
371 Status DevToolsClientImpl::ProcessCommandResponse(
372 const internal::InspectorCommandResponse& response) {
373 ResponseInfoMap::iterator iter = response_info_map_.find(response.id);
375 std::string method, result;
376 if (iter != response_info_map_.end())
377 method = iter->second->method;
379 result = FormatValueForDisplay(*response.result);
381 result = response.error;
382 VLOG(1) << "DEVTOOLS RESPONSE " << method << " (id=" << response.id
386 if (iter == response_info_map_.end())
387 return Status(kUnknownError, "unexpected command response");
389 linked_ptr<ResponseInfo> response_info = response_info_map_[response.id];
390 response_info_map_.erase(response.id);
392 if (response_info->state != kIgnored) {
393 response_info->state = kReceived;
394 response_info->response.id = response.id;
395 response_info->response.error = response.error;
397 response_info->response.result.reset(response.result->DeepCopy());
400 if (response.result) {
401 unnotified_cmd_response_listeners_ = listeners_;
402 unnotified_cmd_response_info_ = response_info;
403 Status status = EnsureListenersNotifiedOfCommandResponse();
404 unnotified_cmd_response_info_.reset();
405 if (status.IsError())
411 Status DevToolsClientImpl::EnsureListenersNotifiedOfConnect() {
412 while (unnotified_connect_listeners_.size()) {
413 DevToolsEventListener* listener = unnotified_connect_listeners_.front();
414 unnotified_connect_listeners_.pop_front();
415 Status status = listener->OnConnected(this);
416 if (status.IsError())
422 Status DevToolsClientImpl::EnsureListenersNotifiedOfEvent() {
423 while (unnotified_event_listeners_.size()) {
424 DevToolsEventListener* listener = unnotified_event_listeners_.front();
425 unnotified_event_listeners_.pop_front();
426 Status status = listener->OnEvent(
427 this, unnotified_event_->method, *unnotified_event_->params);
428 if (status.IsError())
434 Status DevToolsClientImpl::EnsureListenersNotifiedOfCommandResponse() {
435 while (unnotified_cmd_response_listeners_.size()) {
436 DevToolsEventListener* listener =
437 unnotified_cmd_response_listeners_.front();
438 unnotified_cmd_response_listeners_.pop_front();
440 listener->OnCommandSuccess(this, unnotified_cmd_response_info_->method);
441 if (status.IsError())
449 bool ParseInspectorMessage(
450 const std::string& message,
452 InspectorMessageType* type,
453 InspectorEvent* event,
454 InspectorCommandResponse* command_response) {
455 scoped_ptr<base::Value> message_value(base::JSONReader::Read(message));
456 base::DictionaryValue* message_dict;
457 if (!message_value || !message_value->GetAsDictionary(&message_dict))
461 if (!message_dict->HasKey("id")) {
463 if (!message_dict->GetString("method", &method))
465 base::DictionaryValue* params = NULL;
466 message_dict->GetDictionary("params", ¶ms);
468 *type = kEventMessageType;
469 event->method = method;
471 event->params.reset(params->DeepCopy());
473 event->params.reset(new base::DictionaryValue());
475 } else if (message_dict->GetInteger("id", &id)) {
476 base::DictionaryValue* unscoped_error = NULL;
477 base::DictionaryValue* unscoped_result = NULL;
478 *type = kCommandResponseMessageType;
479 command_response->id = id;
480 // As per Chromium issue 392577, DevTools does not necessarily return a
481 // "result" dictionary for every valid response. In particular,
482 // Tracing.start and Tracing.end command responses do not contain one.
483 // So, if neither "error" nor "result" keys are present, just provide
484 // a blank result dictionary.
485 if (message_dict->GetDictionary("result", &unscoped_result))
486 command_response->result.reset(unscoped_result->DeepCopy());
487 else if (message_dict->GetDictionary("error", &unscoped_error))
488 base::JSONWriter::Write(unscoped_error, &command_response->error);
490 command_response->result.reset(new base::DictionaryValue());
496 } // namespace internal