Esempio n. 1
0
void
PeerConnectionMedia::ShutdownMediaTransport_s()
{
  ASSERT_ON_THREAD(mSTSThread);

  CSFLogDebug(LOGTAG, "%s: ", __FUNCTION__);

  disconnect_all();
  mTransportFlows.clear();

#if !defined(MOZILLA_EXTERNAL_LINKAGE)
  NrIceStats stats = mIceCtxHdlr->Destroy();

  CSFLogDebug(LOGTAG, "Ice Telemetry: stun (retransmits: %d)"
                      "   turn (401s: %d   403s: %d   438s: %d)",
              stats.stun_retransmits, stats.turn_401s, stats.turn_403s,
              stats.turn_438s);

  Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_NICER_STUN_RETRANSMITS,
                       stats.stun_retransmits);
  Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_NICER_TURN_401S,
                       stats.turn_401s);
  Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_NICER_TURN_403S,
                       stats.turn_403s);
  Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_NICER_TURN_438S,
                       stats.turn_438s);
#endif

  mIceCtxHdlr = nullptr;

  // we're holding a ref to 'this' that's released by SelfDestruct_m
  mMainThread->Dispatch(WrapRunnable(this, &PeerConnectionMedia::SelfDestruct_m),
                        NS_DISPATCH_NORMAL);
}
void
PeerConnectionMedia::ShutdownMediaTransport_s()
{
  ASSERT_ON_THREAD(mSTSThread);

  CSFLogDebug(logTag, "%s: ", __FUNCTION__);

  // Here we access m{Local|Remote}SourceStreams off the main thread.
  // That's OK because by here PeerConnectionImpl has forgotten about us,
  // so there is no chance of getting a call in here from outside.
  // The dispatches from SelfDestruct() and to SelfDestruct_m() provide
  // memory barriers that protect us from badness.
  for (uint32_t i=0; i < mLocalSourceStreams.Length(); ++i) {
    mLocalSourceStreams[i]->DetachTransport_s();
  }

  for (uint32_t i=0; i < mRemoteSourceStreams.Length(); ++i) {
    mRemoteSourceStreams[i]->DetachTransport_s();
  }

  disconnect_all();
  mTransportFlows.clear();
  mIceCtxHdlr = nullptr;

  mMainThread->Dispatch(WrapRunnable(this, &PeerConnectionMedia::SelfDestruct_m),
                        NS_DISPATCH_NORMAL);
}
Esempio n. 3
0
static void
sig_session_save(void)
{
	/* We don't support /UPGRADE, so disconnect all servers
	 * before performing it. */
	disconnect_all();
}
void
PeerConnectionMedia::ShutdownMediaTransport()
{
  disconnect_all();
  mTransportFlows.clear();
  mIceStreams.clear();
  mIceCtx = NULL;
}
Esempio n. 5
0
void
xmpp_servers_deinit(void)
{
	/* disconnect all servers before unloading the module */
	disconnect_all();

	signal_remove("server connected", sig_connected);
	signal_remove("server disconnected", server_cleanup);
	signal_remove("server connect failed", server_cleanup);
	signal_remove("server quit", sig_server_quit);
	signal_remove("session save", sig_session_save);
}
void
PeerConnectionMedia::ShutdownMediaTransport_s()
{
  ASSERT_ON_THREAD(mSTSThread);

  CSFLogDebug(logTag, "%s: ", __FUNCTION__);

  for (uint32_t i=0; i < mLocalSourceStreams.Length(); ++i) {
    mLocalSourceStreams[i]->DetachTransport_s();
  }

  for (uint32_t i=0; i < mRemoteSourceStreams.Length(); ++i) {
    mRemoteSourceStreams[i]->DetachTransport_s();
  }

  disconnect_all();
  mTransportFlows.clear();
  mIceStreams.clear();
  mIceCtx = nullptr;

  mMainThread->Dispatch(WrapRunnable(this, &PeerConnectionMedia::SelfDestruct_m),
                        NS_DISPATCH_NORMAL);
}
Esempio n. 7
0
int main(int argc, char **argv) {
  int status;

  /* 
   * seed random number generator
   * TODO: what uses this?
   */ 
  srandom((unsigned int) time(0) % getpid());

  /*
   * iquest_fuse data that will be passed in to FUSE operations
   */
  static iquest_fuse_t iquest_fuse;
  memset(&iquest_fuse, 0, sizeof(iquest_fuse));

  static iquest_fuse_conf_t iquest_fuse_conf;
  memset(&iquest_fuse_conf, 0, sizeof(iquest_fuse_conf));
  iquest_fuse.conf = &iquest_fuse_conf;

  static rodsEnv myRodsEnv;
  iquest_fuse.rods_env = &myRodsEnv;

  iquest_fuse_t *iqf = &iquest_fuse;
  
  /*
   * Use FUSE option processing to process argc/argv
   */
  struct fuse_args args = FUSE_ARGS_INIT(argc, argv);

  /*
   * Set defaults for dynamically allocated conf fields that have not been set by options
   */
  if(iqf->conf->indicator == NULL) {
    int bufsize = strlen(IQF_DEFAULT_INDICATOR)+1;
    iqf->conf->indicator = malloc(bufsize);
    if(iqf->conf->indicator == NULL) {
      fprintf(stderr, "main: malloc(%d) setting default for iqf->conf->indicator\n", bufsize);
      exit(2);
    }
    strncpy(iqf->conf->indicator, IQF_DEFAULT_INDICATOR, bufsize);
  }
  
  if(iqf->conf->slash_remap == NULL) {
    int bufsize = strlen(IQF_DEFAULT_SLASH_REMAP)+1;
    iqf->conf->slash_remap = malloc(bufsize);
    if(iqf->conf->slash_remap == NULL) {
      fprintf(stderr, "main: malloc(%d) setting default for iqf->conf->slash_remap\n", bufsize);
      exit(2);
    }
    strncpy(iqf->conf->slash_remap, IQF_DEFAULT_SLASH_REMAP, bufsize);
  }
  
  /*
   * Set configuration in iquest_fuse_conf from command-line options and 
   * call iquest_fuse_opt_proc for other options
   */
  fuse_opt_parse(&args, &iquest_fuse_conf, iquest_fuse_opts, iquest_fuse_opt_proc);

  
  if(iqf->conf->irods_cwd != NULL) {
    rodsLog(LOG_NOTICE, "using iRODS cwd %s", iqf->conf->irods_cwd);
    status = setenv("irodsCwd", iqf->conf->irods_cwd, 1);
    if( status < 0) {
      rodsLog(LOG_ERROR, "main: could not set irodsCwd environment variable");
    }
  }
  
  if(iqf->conf->base_query != NULL) {
    rodsLog(LOG_NOTICE, "using base query %s", iqf->conf->base_query);
  }
  
  if(iqf->conf->indicator != NULL) {
    rodsLog(LOG_NOTICE, "using indicator %s", iqf->conf->indicator);
  }
  
  if(iqf->conf->slash_remap != NULL) {
    rodsLog(LOG_NOTICE, "remapping slashes [/] in metadata to [%s]", iqf->conf->slash_remap);
  }

  if(iqf->conf->show_indicator > 0) {
    rodsLog(LOG_SYS_WARNING, "showing query indicator (%s) in directory listings -- you must not attempt to recursively list directories (e.g. don't use find, du, ls -R, etc)", iqf->conf->indicator);
  }
  

#ifdef CACHE_FILE_FOR_READ
  if (setAndMkFileCacheDir () < 0) exit(3);
#endif
  
  /*
   * get iRODS configuration from environment and conf file (~/.irods/.irodsEnv)
   */
  status = getRodsEnv(iqf->rods_env);
  if( status < 0 ) {
    rodsLogError(LOG_ERROR, status, "main: getRodsEnv error. ");
    exit(1);
  }


  /* 
   * override irodsLogLevel if debug_level is greater
   */
  if(iqf->conf->debug_level > iqf->rods_env->rodsLogLevel) {
    fprintf(stderr, "overriding rodsLogLevel to debug_level=%d\n", iqf->conf->debug_level);
    rodsLogLevel(iqf->conf->debug_level);
    iqf->rods_env->rodsLogLevel = iqf->conf->debug_level;
  }
  
  initPathCache ();
  initIFuseDesc ();
  

  /*
   * Pass control to FUSE (which will call iquest_fuse_init and then start event loop 
   */
  rodsLog(LOG_DEBUG, "calling fuse_main");
  status = fuse_main (args.argc, args.argv, &iquest_fuse_operations, &iquest_fuse);
  rodsLog(LOG_DEBUG, "back from fuse_main");
  
  disconnect_all(iqf);
  
  if (status < 0) {
    rodsLogError(LOG_ERROR, status, "fuse_main");
    exit(5);
  } else {
    exit(0);
  }
}
Esempio n. 8
0
bool
PostureMerge::init() {
  init_startable(this);

  shmcntr_.install_connect_method([this](const std::string path){return connect(path);},
                                  [this](const std::string path){return disconnect(path);},
                                  [this](){return disconnect_all();},
                                  [this](const std::string caps ){return can_sink_caps(caps);},
                                  8);

  calibration_path_prop_ =
      custom_props_->make_string_property("calibration_path",
                                          "Path to the calibration file",
                                          calibration_path_.c_str(),
                                          (GParamFlags) G_PARAM_READWRITE,
                                          PostureMerge::set_calibration_path,
                                          PostureMerge::get_calibration_path,
                                          this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            calibration_path_prop_, "calibration_path",
                            "Path to the calibration file");

  devices_path_prop_ = custom_props_->make_string_property("devices_path",
                                                           "Path to the devices description file",
                                                           devices_path_.c_str
                                                           (), (GParamFlags)
                                                           G_PARAM_READWRITE,
                                                           PostureMerge::set_devices_path,
                                                           PostureMerge::get_devices_path,
                                                           this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            devices_path_prop_, "devices",
                            "Path to the devices description file");

  compress_cloud_prop_ = custom_props_->make_boolean_property("compress_cloud",
                                           "Compress the cloud if true",
                                           compress_cloud_,
                                           (GParamFlags) G_PARAM_READWRITE,
                                           PostureMerge::set_compress_cloud,
                                           PostureMerge::get_compress_cloud,
                                           this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            compress_cloud_prop_, "compress_cloud",
                            "Compress the cloud if true");

  reload_calibration_prop_ = custom_props_->make_boolean_property("reload_calibration",
                                "Reload calibration at each frame",
                                reload_calibration_,
                                (GParamFlags) G_PARAM_READWRITE,
                                PostureMerge::set_reload_calibration,
                                PostureMerge::get_reload_calibration,
                                this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            reload_calibration_prop_, "reload_calibration",
                            "Reload calibration at each frame");

  save_cloud_prop_ = custom_props_->make_boolean_property("save_cloud",
                                           "Save the current cloud if true",
                                           save_cloud_,
                                           (GParamFlags) G_PARAM_READWRITE,
                                           PostureMerge::set_save_cloud,
                                           PostureMerge::get_save_cloud,
                                           this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            save_cloud_prop_, "save_cloud",
                            "Save the current cloud if true");

  downsample_prop_ = custom_props_->make_boolean_property("downsample",
                                "Activate the cloud downsampling",
                                downsample_,
                                (GParamFlags) G_PARAM_READWRITE,
                                PostureMerge::set_downsample_active,
                                PostureMerge::get_downsample_active,
                                this);
  install_property_by_pspec(custom_props_->get_gobject(),
                            downsample_prop_, "downsample",
                            "Activate the cloud downsampling");

  return true;
}
Esempio n. 9
0
bool PostureMerge::init() {
  init_startable(this);

  shmcntr_.install_connect_method([this](const std::string path) { return connect(path); },
                                  [this](const std::string path) { return disconnect(path); },
                                  [this]() { return disconnect_all(); },
                                  [this](const std::string caps) { return can_sink_caps(caps); },
                                  8);

  pmanage<MPtr(&PContainer::make_string)>(
      "calibration_path",
      [this](const std::string& val) {
        calibration_path_ = val;
        if (calibration_reader_) {
          calibration_reader_->loadCalibration(calibration_path_);
          merger_->setCalibration(calibration_reader_->getCalibrationParams());
        }
        return true;
      },
      [this]() { return calibration_path_; },
      "Calibration path",
      "Path to the calibration file",
      calibration_path_);

  pmanage<MPtr(&PContainer::make_bool)>("compress_cloud",
                                        [this](const bool& val) {
                                          compress_cloud_ = val;
                                          return true;
                                        },
                                        [this]() { return compress_cloud_; },
                                        "Compression",
                                        "Compress the cloud if true",
                                        compress_cloud_);

  pmanage<MPtr(&PContainer::make_bool)>("reload_calibration",
                                        [this](const bool& val) {
                                          reload_calibration_ = val;
                                          return true;
                                        },
                                        [this]() { return reload_calibration_; },
                                        "Reload calibration",
                                        "Reload calibration at each frame",
                                        reload_calibration_);

  pmanage<MPtr(&PContainer::make_bool)>("save_cloud",
                                        [this](const bool& val) {
                                          save_cloud_ = val;
                                          return true;
                                        },
                                        [this]() { return save_cloud_; },
                                        "Save current cloud",
                                        "Save the current cloud if true",
                                        save_cloud_);

  pmanage<MPtr(&PContainer::make_bool)>(
      "downsample",
      [this](const bool& active) {
        if (downsample_ != active && active == true) {
          downsample_ = active;
          downsample_resolution_id_ = pmanage<MPtr(&PContainer::make_double)>(
              "downsample_resolution",
              [this](const double& val) {
                downsample_resolution_ = val;
                if (merger_ != nullptr)
                  merger_->setDownsampling(downsample_, downsample_resolution_);
                return true;
              },
              [this]() { return downsample_resolution_; },
              "Resampling resolution",
              "Resampling resolution",
              downsample_resolution_,
              0.01,
              1.0);
        } else if (downsample_ != active && active == false) {
          downsample_ = false;
          pmanage<MPtr(&PContainer::remove)>(downsample_resolution_id_);
        }
        if (merger_ != nullptr) merger_->setDownsampling(downsample_, downsample_resolution_);
        return true;
      },
      [this]() { return downsample_; },
      "Downsample",
      "Activate the cloud downsampling",
      downsample_);
  return true;
}
Esempio n. 10
0
 inline ~connections() { disconnect_all(true); }
Esempio n. 11
0
// This is all-or-nothing.
nsresult TransportFlow::PushLayers(nsAutoPtr<std::queue<TransportLayer *> > layers) {
  MOZ_ASSERT(!layers->empty());
  if (layers->empty()) {
    MOZ_MTLOG(PR_LOG_ERROR, id_ << ": Can't call PushLayers with empty layers");
    return NS_ERROR_INVALID_ARG;
  }

  // Don't allow pushes once we are in error state.
  if (state_ == TransportLayer::TS_ERROR) {
    MOZ_MTLOG(PR_LOG_ERROR, id_ << ": Can't call PushLayers in error state for flow ");
    return NS_ERROR_FAILURE;
  }

  nsresult rv = NS_OK;

  // Disconnect all the old signals.
  disconnect_all();

  TransportLayer *layer;

  while (!layers->empty()) {
    TransportLayer *old_layer = layers_.empty() ? nullptr : layers_.front();
    layer = layers->front();

    rv = layer->Init();
    if (NS_FAILED(rv)) {
      MOZ_MTLOG(PR_LOG_ERROR, id_ << ": Layer initialization failed; invalidating flow ");
      break;
    }

    // Push the layer onto the queue.
    layers_.push_front(layer);
    layers->pop();
    layer->Inserted(this, old_layer);
  }

  if (NS_FAILED(rv)) {
    // Destroy any layers we could not push.
    while (!layers->empty()) {
      delete layers->front();
      layers->pop();
    }

    // Now destroy the rest of the flow, because it's no longer
    // in an acceptable state.
    while (!layers_.empty()) {
      delete layers_.front();
      layers_.pop_front();
    }

    // Set ourselves to have failed.
    StateChangeInt(TransportLayer::TS_ERROR);

    // Return failure.
    return rv;
  }

  // Finally, attach ourselves to the top layer.
  layer->SignalStateChange.connect(this, &TransportFlow::StateChange);
  layer->SignalPacketReceived.connect(this, &TransportFlow::PacketReceived);
  StateChangeInt(layer->state());  // Signals if the state changes.

  return NS_OK;
}
Esempio n. 12
0
int
main(int argc, char **argv)
{
	int			c;
	int			is_init_mode = 0;		/* initialize mode? */
	int			is_no_vacuum = 0;		/* no vacuum at all before testing? */
	int			is_full_vacuum = 0;		/* do full vacuum before testing? */
	int			debug = 0;		/* debug flag */
	int			ttype = 0;		/* transaction type. 0: TPC-B, 1: SELECT only,
								 * 2: skip update of branches and tellers */
	char	   *filename = NULL;

	CState	   *state;			/* status of clients */

	struct timeval tv1;			/* start up time */
	struct timeval tv2;			/* after establishing all connections to the
								 * backend */
	struct timeval tv3;			/* end time */

	int			i;

	fd_set		input_mask;
	int			nsocks;			/* return from select(2) */
	int			maxsock;		/* max socket number to be waited */

#ifdef HAVE_GETRLIMIT
	struct rlimit rlim;
#endif

	PGconn	   *con;
	PGresult   *res;
	char	   *env;

	char		val[64];

	if ((env = getenv("PGHOST")) != NULL && *env != '\0')
		pghost = env;
	if ((env = getenv("PGPORT")) != NULL && *env != '\0')
		pgport = env;
	else if ((env = getenv("PGUSER")) != NULL && *env != '\0')
		login = env;

	state = (CState *) malloc(sizeof(CState));
	if (state == NULL)
	{
		fprintf(stderr, "Couldn't allocate memory for state\n");
		exit(1);
	}

	memset(state, 0, sizeof(*state));

	while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:U:P:CNSlf:D:")) != -1)
	{
		switch (c)
		{
			case 'i':
				is_init_mode++;
				break;
			case 'h':
				pghost = optarg;
				break;
			case 'n':
				is_no_vacuum++;
				break;
			case 'v':
				is_full_vacuum++;
				break;
			case 'p':
				pgport = optarg;
				break;
			case 'd':
				debug++;
				break;
			case 'S':
				ttype = 1;
				break;
			case 'N':
				ttype = 2;
				break;
			case 'c':
				nclients = atoi(optarg);
				if (nclients <= 0 || nclients > MAXCLIENTS)
				{
					fprintf(stderr, "invalid number of clients: %d\n", nclients);
					exit(1);
				}
#ifdef HAVE_GETRLIMIT
#ifdef RLIMIT_NOFILE			/* most platforms use RLIMIT_NOFILE */
				if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
#else							/* but BSD doesn't ... */
				if (getrlimit(RLIMIT_OFILE, &rlim) == -1)
#endif   /* RLIMIT_NOFILE */
				{
					fprintf(stderr, "getrlimit failed: %s\n", strerror(errno));
					exit(1);
				}
				if (rlim.rlim_cur <= (nclients + 2))
				{
					fprintf(stderr, "You need at least %d open files but you are only allowed to use %ld.\n", nclients + 2, (long) rlim.rlim_cur);
					fprintf(stderr, "Use limit/ulimit to increase the limit before using pgbench.\n");
					exit(1);
				}
#endif /* HAVE_GETRLIMIT */
				break;
			case 'C':
				is_connect = 1;
				break;
			case 's':
				scale = atoi(optarg);
				if (scale <= 0)
				{
					fprintf(stderr, "invalid scaling factor: %d\n", scale);
					exit(1);
				}
				break;
			case 't':
				nxacts = atoi(optarg);
				if (nxacts <= 0)
				{
					fprintf(stderr, "invalid number of transactions: %d\n", nxacts);
					exit(1);
				}
				break;
			case 'U':
				login = optarg;
				break;
			case 'P':
				pwd = optarg;
				break;
			case 'l':
				use_log = true;
				break;
			case 'f':
				ttype = 3;
				filename = optarg;
				if (process_file(filename) == false || *sql_files[num_files - 1] == NULL)
					exit(1);
				break;
			case 'D':
				{
					char	   *p;

					if ((p = strchr(optarg, '=')) == NULL || p == optarg || *(p + 1) == '\0')
					{
						fprintf(stderr, "invalid variable definition: %s\n", optarg);
						exit(1);
					}

					*p++ = '\0';
					if (putVariable(&state[0], optarg, p) == false)
					{
						fprintf(stderr, "Couldn't allocate memory for variable\n");
						exit(1);
					}
				}
				break;
			default:
				usage();
				exit(1);
				break;
		}
	}

	if (argc > optind)
		dbName = argv[optind];
	else
	{
		if ((env = getenv("PGDATABASE")) != NULL && *env != '\0')
			dbName = env;
		else if (login != NULL && *login != '\0')
			dbName = login;
		else
			dbName = "";
	}

	if (is_init_mode)
	{
		init();
		exit(0);
	}

	remains = nclients;

	if (getVariable(&state[0], "scale") == NULL)
	{
		snprintf(val, sizeof(val), "%d", scale);
		if (putVariable(&state[0], "scale", val) == false)
		{
			fprintf(stderr, "Couldn't allocate memory for variable\n");
			exit(1);
		}
	}

	if (nclients > 1)
	{
		state = (CState *) realloc(state, sizeof(CState) * nclients);
		if (state == NULL)
		{
			fprintf(stderr, "Couldn't allocate memory for state\n");
			exit(1);
		}

		memset(state + 1, 0, sizeof(*state) * (nclients - 1));

		snprintf(val, sizeof(val), "%d", scale);

		for (i = 1; i < nclients; i++)
		{
			int			j;

			for (j = 0; j < state[0].nvariables; j++)
			{
				if (putVariable(&state[i], state[0].variables[j].name, state[0].variables[j].value) == false)
				{
					fprintf(stderr, "Couldn't allocate memory for variable\n");
					exit(1);
				}
			}

			if (putVariable(&state[i], "scale", val) == false)
			{
				fprintf(stderr, "Couldn't allocate memory for variable\n");
				exit(1);
			}
		}
	}

	if (use_log)
	{
		char		logpath[64];

		snprintf(logpath, 64, "pgbench_log.%d", getpid());
		LOGFILE = fopen(logpath, "w");

		if (LOGFILE == NULL)
		{
			fprintf(stderr, "Couldn't open logfile \"%s\": %s", logpath, strerror(errno));
			exit(1);
		}
	}

	if (debug)
	{
		printf("pghost: %s pgport: %s nclients: %d nxacts: %d dbName: %s\n",
			   pghost, pgport, nclients, nxacts, dbName);
	}

	/* opening connection... */
	con = doConnect();
	if (con == NULL)
		exit(1);

	if (PQstatus(con) == CONNECTION_BAD)
	{
		fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
		fprintf(stderr, "%s", PQerrorMessage(con));
		exit(1);
	}

	if (ttype != 3)
	{
		/*
		 * get the scaling factor that should be same as count(*) from
		 * branches if this is not a custom query
		 */
		res = PQexec(con, "select count(*) from branches");
		if (PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(stderr, "%s", PQerrorMessage(con));
			exit(1);
		}
		scale = atoi(PQgetvalue(res, 0, 0));
		if (scale < 0)
		{
			fprintf(stderr, "count(*) from branches invalid (%d)\n", scale);
			exit(1);
		}
		PQclear(res);

		snprintf(val, sizeof(val), "%d", scale);
		if (putVariable(&state[0], "scale", val) == false)
		{
			fprintf(stderr, "Couldn't allocate memory for variable\n");
			exit(1);
		}

		if (nclients > 1)
		{
			for (i = 1; i < nclients; i++)
			{
				if (putVariable(&state[i], "scale", val) == false)
				{
					fprintf(stderr, "Couldn't allocate memory for variable\n");
					exit(1);
				}
			}
		}
	}

	if (!is_no_vacuum)
	{
		fprintf(stderr, "starting vacuum...");
		res = PQexec(con, "vacuum branches");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "%s", PQerrorMessage(con));
			exit(1);
		}
		PQclear(res);

		res = PQexec(con, "vacuum tellers");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "%s", PQerrorMessage(con));
			exit(1);
		}
		PQclear(res);

		res = PQexec(con, "delete from history");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "%s", PQerrorMessage(con));
			exit(1);
		}
		PQclear(res);
		res = PQexec(con, "vacuum history");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "%s", PQerrorMessage(con));
			exit(1);
		}
		PQclear(res);

		fprintf(stderr, "end.\n");

		if (is_full_vacuum)
		{
			fprintf(stderr, "starting full vacuum...");
			res = PQexec(con, "vacuum analyze accounts");
			if (PQresultStatus(res) != PGRES_COMMAND_OK)
			{
				fprintf(stderr, "%s", PQerrorMessage(con));
				exit(1);
			}
			PQclear(res);
			fprintf(stderr, "end.\n");
		}
	}
	PQfinish(con);

	/* set random seed */
	gettimeofday(&tv1, NULL);
	srandom((unsigned int) tv1.tv_usec);

	/* get start up time */
	gettimeofday(&tv1, NULL);

	if (is_connect == 0)
	{
		/* make connections to the database */
		for (i = 0; i < nclients; i++)
		{
			state[i].id = i;
			if ((state[i].con = doConnect()) == NULL)
				exit(1);
		}
	}

	/* time after connections set up */
	gettimeofday(&tv2, NULL);

	/* process bultin SQL scripts */
	switch (ttype)
	{
		case 0:
			sql_files[0] = process_builtin(tpc_b);
			num_files = 1;
			break;

		case 1:
			sql_files[0] = process_builtin(select_only);
			num_files = 1;
			break;

		case 2:
			sql_files[0] = process_builtin(simple_update);
			num_files = 1;
			break;

		default:
			break;
	}

	/* send start up queries in async manner */
	for (i = 0; i < nclients; i++)
	{
		Command   **commands = sql_files[state[i].use_file];
		int			prev_ecnt = state[i].ecnt;

		state[i].use_file = getrand(0, num_files - 1);
		doCustom(state, i, debug);

		if (state[i].ecnt > prev_ecnt && commands[state[i].state]->type == META_COMMAND)
		{
			fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, state[i].state);
			remains--;			/* I've aborted */
			PQfinish(state[i].con);
			state[i].con = NULL;
		}
	}

	for (;;)
	{
		if (remains <= 0)
		{						/* all done ? */
			disconnect_all(state);
			/* get end time */
			gettimeofday(&tv3, NULL);
			printResults(ttype, state, &tv1, &tv2, &tv3);
			if (LOGFILE)
				fclose(LOGFILE);
			exit(0);
		}

		FD_ZERO(&input_mask);

		maxsock = -1;
		for (i = 0; i < nclients; i++)
		{
			Command   **commands = sql_files[state[i].use_file];

			if (state[i].con && commands[state[i].state]->type != META_COMMAND)
			{
				int			sock = PQsocket(state[i].con);

				if (sock < 0)
				{
					disconnect_all(state);
					exit(1);
				}
				FD_SET(sock, &input_mask);
				if (maxsock < sock)
					maxsock = sock;
			}
		}

		if (maxsock != -1)
		{
			if ((nsocks = select(maxsock + 1, &input_mask, (fd_set *) NULL,
							  (fd_set *) NULL, (struct timeval *) NULL)) < 0)
			{
				if (errno == EINTR)
					continue;
				/* must be something wrong */
				disconnect_all(state);
				fprintf(stderr, "select failed: %s\n", strerror(errno));
				exit(1);
			}
			else if (nsocks == 0)
			{					/* timeout */
				fprintf(stderr, "select timeout\n");
				for (i = 0; i < nclients; i++)
				{
					fprintf(stderr, "client %d:state %d cnt %d ecnt %d listen %d\n",
							i, state[i].state, state[i].cnt, state[i].ecnt, state[i].listen);
				}
				exit(0);
			}
		}

		/* ok, backend returns reply */
		for (i = 0; i < nclients; i++)
		{
			Command   **commands = sql_files[state[i].use_file];
			int			prev_ecnt = state[i].ecnt;

			if (state[i].con && (FD_ISSET(PQsocket(state[i].con), &input_mask)
						  || commands[state[i].state]->type == META_COMMAND))
			{
				doCustom(state, i, debug);
			}

			if (state[i].ecnt > prev_ecnt && commands[state[i].state]->type == META_COMMAND)
			{
				fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, state[i].state);
				remains--;		/* I've aborted */
				PQfinish(state[i].con);
				state[i].con = NULL;
			}
		}
	}
}