Coverage for /Syzygy/trace/service/service_main.cc

CoverageLines executed / instrumented / missingexe / inst / missLanguageGroup
42.0%681620.C++source

Line-by-line coverage:

   1    :  // Copyright 2012 Google Inc. All Rights Reserved.
   2    :  //
   3    :  // Licensed under the Apache License, Version 2.0 (the "License");
   4    :  // you may not use this file except in compliance with the License.
   5    :  // You may obtain a copy of the License at
   6    :  //
   7    :  //     http://www.apache.org/licenses/LICENSE-2.0
   8    :  //
   9    :  // Unless required by applicable law or agreed to in writing, software
  10    :  // distributed under the License is distributed on an "AS IS" BASIS,
  11    :  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12    :  // See the License for the specific language governing permissions and
  13    :  // limitations under the License.
  14    :  
  15    :  #include <iostream>
  16    :  
  17    :  #include "base/at_exit.h"
  18    :  #include "base/command_line.h"
  19    :  #include "base/environment.h"
  20    :  #include "base/file_util.h"
  21    :  #include "base/logging.h"
  22    :  #include "base/path_service.h"
  23    :  #include "base/process_util.h"
  24    :  #include "base/string_number_conversions.h"
  25    :  #include "base/string_piece.h"
  26    :  #include "base/string_util.h"
  27    :  #include "base/utf_string_conversions.h"
  28    :  #include "base/files/file_path.h"
  29    :  #include "base/memory/scoped_ptr.h"
  30    :  #include "base/threading/thread.h"
  31    :  #include "sawbuck/common/com_utils.h"
  32    :  #include "syzygy/trace/common/service_util.h"
  33    :  #include "syzygy/trace/protocol/call_trace_defs.h"
  34    :  #include "syzygy/trace/rpc/rpc_helpers.h"
  35    :  #include "syzygy/trace/service/service.h"
  36    :  #include "syzygy/trace/service/service_rpc_impl.h"
  37    :  #include "syzygy/trace/service/trace_file_writer_factory.h"
  38    :  
  39    :  namespace trace {
  40    :  namespace service {
  41    :  namespace {
  42    :  
  43    :  using ::trace::client::CreateRpcBinding;
  44    :  using ::trace::client::InvokeRpc;
  45    :  
  46    :  // Minimum buffer size to allow (1 MB).
  47    :  const int kMinBufferSize = 1024 * 1024;
  48    :  
  49    :  // Minimum number of buffers to allocate.
  50    :  const int kMinBuffers = 16;
  51    :  
  52    :  // A static location to which the current instance id can be saved. We
  53    :  // persist it here so that OnConsoleCtrl can have access to the instance
  54    :  // id when it is invoked on the signal handler thread.
  55    :  wchar_t saved_instance_id[16] = {0};
  56    :  
  57    :  // Forward declaration.
  58    :  bool StopService(const base::StringPiece16& instance_id);
  59    :  
  60    :  // Handler function to be called on exit signals (Ctrl-C, TERM, etc...).
  61  i :  BOOL WINAPI OnConsoleCtrl(DWORD ctrl_type) {
  62  i :    if (ctrl_type != CTRL_LOGOFF_EVENT) {
  63  i :      StopService(saved_instance_id);
  64  i :      return TRUE;
  65    :    }
  66  i :    return FALSE;
  67  i :  }
  68    :  
  69    :  const char* const kInstanceId = "instance-id";
  70    :  
  71    :  const char kUsage[] =
  72    :      "Usage: call_trace_service [OPTIONS] ACTION [-- command]\n"
  73    :      "\n"
  74    :      "Actions:\n"
  75    :      "  start              Start the call trace service. This causes an\n"
  76    :      "                     instance of the service to be launched as a\n"
  77    :      "                     foreground process.\n"
  78    :      "  spawn              Spawns an instance of the call trace service, waits\n"
  79    :      "                     for it to be ready, and returns. The call trace\n"
  80    :      "                     service continues running in the background.\n"
  81    :      "  stop               Stop the call trace service.\n"
  82    :      "\n"
  83    :      "Options:\n"
  84    :      "  --help             Show this help message.\n"
  85    :      "  --trace-dir=PATH   The directory in which to write the trace files.\n"
  86    :      "  --buffer-size=NUM  The size (in bytes) of each buffer to allocate.\n"
  87    :      "  --num-incremental-buffers=NUM\n"
  88    :      "                     The number of buffers by which to grow the buffer\n"
  89    :      "                     pool each time the client exhausts its available\n"
  90    :      "                     buffer space.\n"
  91    :      "  --enable-exits     Enable exit tracing (off by default).\n"
  92    :      "  --verbose          Increase the logging verbosity to also include\n"
  93    :      "                     debug-level information.\n"
  94    :      "  --instance-id=ID   A unique identifier to use for the RPC endpoint.\n"
  95    :      "                     This allows multiple instances of the service to\n"
  96    :      "                     run concurrently. By default this is empty.\n"
  97    :      "\n";
  98    :  
  99  i :  int Usage() {
 100  i :    std::cout << kUsage;
 101  i :    return 1;
 102  i :  }
 103    :  
 104  E :  bool GetInstanceId(const CommandLine* cmd_line, std::wstring* id) {
 105  E :    DCHECK(cmd_line != NULL);
 106  E :    DCHECK(id != NULL);
 107    :  
 108    :    // If not specified, this defaults to the empty string.
 109  E :    *id = cmd_line->GetSwitchValueNative(kInstanceId);
 110    :  
 111  E :    const size_t kMaxLength = arraysize(saved_instance_id) - 1;
 112  E :    if (id->length() > kMaxLength) {
 113  i :      LOG(ERROR) << "The instance id '" << *id << "' is too long. "
 114    :                 << "The max length is " << kMaxLength << " characters.";
 115  i :      return false;
 116    :    }
 117    :  
 118  E :    return true;
 119  E :  }
 120    :  
 121    :  // A helper function which sets the Syzygy RPC instance id environment variable
 122    :  // then runs a given command line to completion.
 123    :  // TODO(etienneb): We should merge common code of logger and call_service.
 124    :  bool RunApp(const CommandLine& command_line,
 125    :              const std::wstring& instance_id,
 126  i :              int* exit_code) {
 127  i :    DCHECK(exit_code != NULL);
 128  i :    scoped_ptr<base::Environment> env(base::Environment::Create());
 129  i :    CHECK(env != NULL);
 130  i :    env->SetVar(kSyzygyRpcInstanceIdEnvVar, WideToUTF8(instance_id));
 131    :  
 132  i :    LOG(INFO) << "Launching '" << command_line.GetProgram().value() << "'.";
 133  i :    VLOG(1) << "Command Line: " << command_line.GetCommandLineString();
 134    :  
 135    :    // Launch a new process in the background.
 136    :    base::ProcessHandle process_handle;
 137  i :    base::LaunchOptions options;
 138  i :    options.start_hidden = false;
 139  i :    if (!base::LaunchProcess(command_line, options, &process_handle)) {
 140  i :      LOG(ERROR)
 141    :          << "Failed to launch '" << command_line.GetProgram().value() << "'.";
 142  i :      return false;
 143    :    }
 144    :  
 145    :    // Wait for and return the processes exit code.
 146    :    // Note that this closes the process handle.
 147  i :    if (!base::WaitForExitCode(process_handle, exit_code)) {
 148  i :      LOG(ERROR) << "Failed to get exit code.";
 149  i :      return false;
 150    :    }
 151    :  
 152  i :    return true;
 153  i :  }
 154    :  
 155    :  bool RunService(const CommandLine* cmd_line,
 156  E :                  const scoped_ptr<CommandLine>* app_cmd_line) {
 157  E :    DCHECK(cmd_line != NULL);
 158  E :    DCHECK(app_cmd_line != NULL);
 159    :  
 160  E :    base::Thread writer_thread("trace-file-writer");
 161    :    if (!writer_thread.StartWithOptions(
 162  E :            base::Thread::Options(MessageLoop::TYPE_IO, 0))) {
 163  i :      LOG(ERROR) << "Failed to start call trace service writer thread.";
 164  i :      return 1;
 165    :    }
 166    :  
 167  E :    MessageLoop* message_loop = writer_thread.message_loop();
 168  E :    TraceFileWriterFactory trace_file_writer_factory(message_loop);
 169  E :    Service call_trace_service(&trace_file_writer_factory);
 170  E :    RpcServiceInstanceManager rpc_instance(&call_trace_service);
 171    :  
 172    :    // Get/set the instance id.
 173  E :    std::wstring instance_id;
 174  E :    if (!GetInstanceId(cmd_line, &instance_id))
 175  i :      return false;
 176    :  
 177  E :    call_trace_service.set_instance_id(instance_id);
 178    :    base::wcslcpy(saved_instance_id,
 179    :                  instance_id.c_str(),
 180  E :                  arraysize(saved_instance_id));
 181    :  
 182    :    // Set up the trace directory.
 183  E :    base::FilePath trace_directory(cmd_line->GetSwitchValuePath("trace-dir"));
 184  E :    if (trace_directory.empty())
 185  E :      trace_directory = base::FilePath(L".");
 186  E :    if (!trace_file_writer_factory.SetTraceFileDirectory(trace_directory))
 187  i :      return false;
 188    :  
 189    :    // Setup the buffer size.
 190  E :    std::wstring buffer_size_str(cmd_line->GetSwitchValueNative("buffer-size"));
 191  E :    if (!buffer_size_str.empty()) {
 192  i :      int num = 0;
 193  i :      if (!base::StringToInt(buffer_size_str, &num) || num < kMinBufferSize) {
 194  i :        LOG(ERROR) << "Buffer size is too small (<" << kMinBufferSize << ").";
 195  i :        return false;
 196    :      }
 197  i :      call_trace_service.set_buffer_size_in_bytes(num);
 198    :    }
 199    :  
 200  E :    if (cmd_line->HasSwitch("enable-exits")) {
 201  i :      call_trace_service.set_flags(TRACE_FLAG_ENTER | TRACE_FLAG_EXIT);
 202    :    }
 203    :  
 204    :    // Setup the number of incremental buffers
 205    :    std::wstring buffers_str(
 206  E :        cmd_line->GetSwitchValueNative("num-incremental-buffers"));
 207  E :    if (!buffers_str.empty()) {
 208  i :      int num = 0;
 209  i :      if (!base::StringToInt(buffers_str, &num) || num < kMinBuffers) {
 210  i :        LOG(ERROR) << "Number of incremental buffers is too small (<"
 211    :                   << kMinBuffers << ").";
 212  i :        return false;
 213    :      }
 214  i :      call_trace_service.set_num_incremental_buffers(num);
 215    :    }
 216    :  
 217  E :    if (app_cmd_line->get() != NULL) {
 218    :      // Run the service in non-blocking mode.
 219  i :      call_trace_service.Start(true);
 220    :  
 221    :      // We have a command to run, so launch that command and when it finishes
 222    :      // stop the logger.
 223  i :      int exit_code = 0;
 224    :      if (!RunApp(*app_cmd_line->get(), instance_id, &exit_code) ||
 225  i :          exit_code != 0) {
 226  i :        return false;
 227    :      }
 228  i :    } else {
 229    :      // Setup the handler for exit signals.
 230  E :      if (!SetConsoleCtrlHandler(&OnConsoleCtrl, TRUE)) {
 231  i :        DWORD error = ::GetLastError();
 232  i :        LOG(ERROR) << "Failed to register shutdown handler: "
 233    :                   << com::LogWe(error) << ".";
 234  i :        return false;
 235    :      }
 236    :  
 237    :      // Run the service in blocking mode. This will not return until the service
 238    :      // has been externally stopped.
 239  E :      call_trace_service.Start(false);
 240    :  
 241    :      // We no longer need to look out for exit signals.
 242  E :      SetConsoleCtrlHandler(&OnConsoleCtrl, FALSE);
 243    :    }
 244    :  
 245    :    // The call trace service will be stopped on destruction.
 246  E :    return true;
 247  E :  }
 248    :  
 249  i :  bool SpawnService(const CommandLine* cmd_line) {
 250    :    // Get the path to ourselves.
 251  i :    base::FilePath self_path;
 252  i :    PathService::Get(base::FILE_EXE, &self_path);
 253    :  
 254    :    // Build a command line for starting a new instance of the service.
 255  i :    CommandLine service_cmd(self_path);
 256  i :    service_cmd.AppendArg("start");
 257    :  
 258    :    // Copy over any other switches.
 259    :    CommandLine::SwitchMap::const_iterator it =
 260  i :        cmd_line->GetSwitches().begin();
 261  i :    for (; it != cmd_line->GetSwitches().end(); ++it)
 262  i :      service_cmd.AppendSwitchNative(it->first, it->second);
 263    :  
 264    :    // Get the instance id.
 265  i :    std::wstring instance_id;
 266  i :    if (!GetInstanceId(cmd_line, &instance_id))
 267  i :      return false;
 268    :  
 269    :    // Launch a new process in the background.
 270  i :    LOG(INFO) << "Launching background call trace service with instance ID \""
 271    :              << instance_id << "\".";
 272    :    base::ProcessHandle service_process;
 273  i :    base::LaunchOptions options;
 274  i :    options.start_hidden = true;
 275  i :    if (!base::LaunchProcess(service_cmd, options, &service_process)) {
 276  i :      LOG(ERROR) << "Failed to launch process.";
 277  i :      return false;
 278    :    }
 279  i :    DCHECK_NE(base::kNullProcessHandle, service_process);
 280    :  
 281    :    // Get the name of the event that will be signaled when the service is up
 282    :    // and running.
 283  i :    std::wstring event_name;
 284  i :    ::GetSyzygyCallTraceRpcEventName(instance_id, &event_name);
 285    :    base::win::ScopedHandle rpc_event(
 286  i :        ::CreateEvent(NULL, TRUE, FALSE, event_name.c_str()));
 287  i :    if (!rpc_event.IsValid()) {
 288  i :      LOG(ERROR) << "Unable to create RPC event for instance id \""
 289    :                 << instance_id << "\".";
 290  i :      return false;
 291    :    }
 292    :  
 293    :    // We wait on both the RPC event and the process, as if the process fails for
 294    :    // any reason, it'll exit and its handle will become signaled.
 295  i :    HANDLE handles[] = { rpc_event.Get(), service_process };
 296    :    if (::WaitForMultipleObjects(arraysize(handles),
 297    :                                 handles,
 298    :                                 FALSE,
 299  i :                                 INFINITE) != WAIT_OBJECT_0) {
 300  i :      LOG(ERROR) << "The spawned call trace service exited in error.";
 301  i :      return false;
 302    :    }
 303    :  
 304  i :    LOG(INFO) << "Background call trace service with instance ID \""
 305    :              << instance_id << "\" is ready.";
 306    :  
 307  i :    return true;
 308  i :  }
 309    :  
 310  E :  bool StopService(const base::StringPiece16& instance_id) {
 311  E :    std::wstring protocol;
 312  E :    std::wstring endpoint;
 313    :  
 314  E :    ::GetSyzygyCallTraceRpcProtocol(&protocol);
 315  E :    ::GetSyzygyCallTraceRpcEndpoint(instance_id, &endpoint);
 316    :  
 317  E :    LOG(INFO) << "Stopping call trace logging service instance at '"
 318    :              << endpoint << "' via " << protocol << '.';
 319    :  
 320  E :    handle_t binding = NULL;
 321  E :    if (!CreateRpcBinding(protocol, endpoint, &binding)) {
 322  i :      LOG(ERROR) << "Failed to connect to call trace logging service.";
 323  i :      return false;
 324    :    }
 325    :  
 326  E :    if (!InvokeRpc(CallTraceClient_Stop, binding).succeeded()) {
 327  i :      LOG(ERROR) << "Failed to stop call trace logging service.";
 328  i :      return false;
 329    :    }
 330    :  
 331    :    // TODO(rogerm): It would be nice to make this blocking until the
 332    :    //    service actually shuts down. Perhaps with retries on the stop
 333    :    //    request.
 334  E :    LOG(INFO) << "Call trace service shutdown has been requested.";
 335  E :    return true;
 336  E :  }
 337    :  
 338  E :  extern "C" int main(int argc, char** argv) {
 339  E :    base::AtExitManager at_exit_manager;
 340  E :    CommandLine::Init(argc, argv);
 341  E :    const int kVlogLevelVerbose = -2;
 342    :    if (!logging::InitLogging(
 343    :            L"",
 344    :            logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
 345    :            logging::DONT_LOCK_LOG_FILE,
 346    :            logging::APPEND_TO_OLD_LOG_FILE,
 347  E :            logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
 348  i :      return 1;
 349    :    }
 350    :  
 351    :    // TODO(rogerm): Turn on ETW logging as well.
 352    :  
 353  E :    CommandLine* cmd_line = CommandLine::ForCurrentProcess();
 354  E :    DCHECK(cmd_line != NULL);
 355    :  
 356  E :    CommandLine calltrace_command_line(CommandLine::NO_PROGRAM);
 357  E :    scoped_ptr<CommandLine> app_command_line;
 358    :    if (!trace::common::SplitCommandLine(
 359    :            cmd_line,
 360    :            &calltrace_command_line,
 361  E :            &app_command_line)) {
 362  i :      LOG(ERROR) << "Failed to split command_line into logger and app parts.";
 363  i :      return false;
 364    :    }
 365    :  
 366    :    // Save the command-line in case we need to spawn.
 367  E :    cmd_line = &calltrace_command_line;
 368    :  
 369  E :    if (cmd_line->HasSwitch("verbose")) {
 370  E :      logging::SetMinLogLevel(kVlogLevelVerbose);
 371    :    }
 372    :  
 373  E :    if (cmd_line->HasSwitch("help") || cmd_line->GetArgs().size() < 1) {
 374  i :      return Usage();
 375    :    }
 376    :  
 377  E :    if (LowerCaseEqualsASCII(cmd_line->GetArgs()[0], "stop")) {
 378  E :      std::wstring id;
 379  E :      return (GetInstanceId(cmd_line, &id) && StopService(id)) ? 0 : 1;
 380    :    }
 381    :  
 382  E :    if (LowerCaseEqualsASCII(cmd_line->GetArgs()[0], "start")) {
 383  E :      return RunService(cmd_line, &app_command_line) ? 0 : 1;
 384    :    }
 385    :  
 386  i :    if (LowerCaseEqualsASCII(cmd_line->GetArgs()[0], "spawn")) {
 387  i :      return SpawnService(cmd_line) ? 0 : 1;
 388    :    }
 389    :  
 390  i :    return Usage();
 391  E :  }
 392    :  
 393    :  }  // namespace
 394    :  }  // namespace service
 395    :  }  // namespace trace

Coverage information generated Thu Jul 04 09:34:53 2013.