Пример #1
0
static void psclient_event(struct obus_bus_event *bus_event, void *user_data)
{
	struct ps_bus_event *event;

	/* get ps bus event */
	event = ps_bus_event_from_obus_event(bus_event);
	if (!event)
		return;

	switch(ps_bus_event_get_type(event)) {
	case PS_BUS_EVENT_CONNECTED:
		diag("client connected !");
	break;
	case PS_BUS_EVENT_DISCONNECTED:
		diag("client disconnected !");
	break;
	case PS_BUS_EVENT_CONNECTION_REFUSED:
		diag("connection refused !");
		stop_client();
	break;

	default:
	break;
	}
}
Пример #2
0
void
F::start ()
{
  int retries = 0;

  std::unique_lock <std::mutex> lock (mutex);

  id = 0;

  start_server();
  BOOST_REQUIRE_MESSAGE (pid > 0, "Error launching mediaserver");

  clientThread = std::thread (std::bind (&F::start_client, this) );

  while (!initialized && retries < MAX_RETRIES) {
    lock.unlock();
    std::this_thread::sleep_for (std::chrono::milliseconds (100 * (retries + 1) ) );
    lock.lock();

    if (!initialized) {
      GST_INFO ("Waiting, %d times", retries);
      retries++;
    }
  }

  if (!initialized) {
    stop_client (lock);
    lock.unlock();

    stop_server ();
  }

  BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server");
}
Пример #3
0
	//Call update on server and/or client
	void Network::update() {
		if (has_server && server)
			if (!server->update())
				stop_server();
		if (has_client && client)
			if (!client->update())
				stop_client();
	}
Пример #4
0
void
F::stop()
{
  std::unique_lock <std::mutex> lock (mutex);

  if (initialized) {
    stop_client (lock);
  }

  initialized = false;

  lock.unlock();

  stop_server ();
}
Пример #5
0
client_t* client_create(server_t* server, int sock, char* address, u_short port)
{
	client_t *client = malloc(sizeof(client_t));
	if(client == NULL)
		return NULL;
	client->server = server;
	client->sock = sock;
	client->running = false;
	client->port = port;
	client->trans_open = false;
	strncpy(client->address, address, 20);
	if(server_register_client(server, client) < 0)
	{
		_log(LVL_WARNING, "Max number of active connections reached : %d\n", server->max_client);
		stop_client(client);
		free(client);
		return NULL;
	}
	return client;
}
Пример #6
0
int stop_server(const int sockfd) {

  stop_client();

  log_message(L_INFO, "server: cleaning...");

  while (client_terminated == false) {
    sleep(3);
  }

  if (remove(FIFO_NAME) != 0) {
    log_message(L_WARN, "server: could not remove the FIFO (%s).",
        strerror(errno));
  }

  close(sockfd);

  munmap(file_memory, MM_PROBE_MAX_NUMBER_PROBES);

  log_message(L_INFO, "server: stopped...");
  return 0;
}
Пример #7
0
// Function main
int main(int argc, char *argv[])
{
    //extern char *optarg;
    char chOpt;

    // Command line
    while ((chOpt = getopt(argc, argv, "h?")) != -1)
    {
	switch (chOpt)
	{
	case '?':
	case 'h':
	default:
	    usage();
	    return(1);
	}
    }

    try
    {
        start();

        stop_client();
    }
    catch(const std::exception& err)
    {
        std::cerr << "\n\nGot error: " << err.what() << "\n"
                  << std::endl;
        klk::cli::Factory::destroy();

        exit(EXIT_FAILURE);
    }

    // free resources
    klk::cli::Factory::destroy();

    return 0;
}
Пример #8
0
void server_stop(server_t* server)
{
	//Stop server
	server->running = false;
	close(server->socket);
	server->socket = -1;
	// Stop clients
	int i;
	for(i = 0; i < server->max_client; i++)
	{
		if(server->clients[i] != NULL)
			stop_client(server->clients[i]);
	}
#ifdef __MINGW32__
	//TODO : Cancel Thread
	if(WSAinit)
	{
		WSACleanup();
		WSAinit = false;
	}
#else
	pthread_cancel(server->thread);
#endif
}
Пример #9
0
 Client::~Client()
 {
     stop_client();
 }
Пример #10
0
int start_server(const int sockfd, char* enabledProbes, int logDecoderFormat) {
  int i = 0;
  struct sockaddr_storage their_addr; // connector's address information
  socklen_t sin_size = 0;
  struct sigaction sa;
  char s[INET6_ADDRSTRLEN];

  char VersionString[MMPROBE_VERSION_STING_MAX_LEN] = "\0"; // Version string

  // Reception buffer.
  unsigned char buf[MM_PROBE_MAX_DATA_RECEIVE_SIZE] = {0};
  int nbytes = 0;
  int retval;
  threadInputData_t input;

  // Maximum file descriptor number
  int highsock = sockfd;
  // Newly accepted socket descriptor
  int new_fd = -1;
  // Master file descriptor
  fd_set socks;
  // Temporary file descriptor list for select()
  fd_set read_fds;

  struct timeval tv;

  // Get Version from ME
  MMPROBE_GetVersionString(VersionString);

  //are we running mmprobe standalone without LogDecoder?
  if (enabledProbes != NULL) {
    char* token = NULL;
    int probeId = 0;

    disable_all_probes();

    //need a sleep for handle_clients have time process
    usleep(10000);

    //Start the handle client thread
    pthread_t thread;
    input.logDecoderFormat = logDecoderFormat;
    input.clientfd = -1;
    input.enabledProbes = enabledProbes;
    pthread_create(&thread, NULL, handle_clients, (void*) &input);

    //need a sleep for handle_clients have time process
    usleep(10000);
    int fd = -1;

    if ((fd = open(FIFO_NAME, O_WRONLY | O_NONBLOCK)) == -1) {
      log_message(L_WARN, "server: could not open FIFO: (%s).",
      strerror(errno));
    } else {
      //Set probes will be stored locally on phone
      char location_buf[MMPROBE_SHORT_MESSAGE_SIZE] = {0};

      sprintf(location_buf, "Phone");
      if (!write(fd, location_buf, sizeof(location_buf)) > 0) {
        log_message(L_WARN, "server: Phone could not send to FIFO (%s).",
        strerror(errno));
      }
    }
    close(fd);
    //need a sleep for handle_clients have time process
    usleep(10000);

    if ((fd = open(FIFO_NAME, O_WRONLY | O_NONBLOCK)) == -1) {
      log_message(L_WARN, "server: could not open FIFO: (%s).",
      strerror(errno));
    } else {
      //Set path
      char location_buf[MMPROBE_SHORT_MESSAGE_SIZE] = {0};

      sprintf(location_buf, "Path");
      if (!write(fd, location_buf, sizeof(location_buf)) > 0) {
        log_message(L_WARN, "server: Path could not send to FIFO (%s).",
        strerror(errno));
      }
    }
    close(fd);
    //need a sleep for handle_clients have time to process and create files
    sleep(1);

    //parse all probes activated
    token = strtok(enabledProbes, " ,");
    while (token != NULL) {
      probeId = atoi(token);
      enable_probe(probeId);
      token = strtok(NULL, " ,");
      usleep(2000);
    }

    while (true) {
      sleep(1);
    }
  }

  // Reap all dead processes
  sa.sa_handler = sigchld_handler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;
  if (sigaction(SIGCHLD, &sa, NULL) == -1) {
    log_message(L_ERR, "server: sigaction failed: %s.", strerror(errno));
    return 1;
  }

  // Build the select list.
  FD_ZERO(&socks);
  FD_ZERO(&read_fds);

  // Add the listener to the master set
  FD_SET(sockfd, &socks);

  log_message(L_INFO, "server: waiting for new connections...");

  while (true) { // main accept() loop;
    read_fds = socks;

    // if (select(highsock + 1, &read_fds, NULL, NULL, &tv) == -1) {
      // log_message(L_ERR, "server: select failed: %s.", strerror(errno));
      // continue;
    // }
    // Wait up to five seconds.
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    retval = select(highsock + 1, &read_fds, NULL, NULL, &tv);

    if (retval == -1) {
      log_message(L_ERR, "server: select failed: %s.", strerror(errno));
      continue;
    } else if (retval) {
      for (i = 0; i <= highsock; i++) {
        if (FD_ISSET(i, &read_fds)) {
          if (i == sockfd) {
            // A new connection is detected.
            sin_size = sizeof(their_addr);

            new_fd = accept(sockfd, (struct sockaddr *)&their_addr,
                    &sin_size);

            if (new_fd == -1) {
              log_message(L_ERR, "server: accept failed: %s",
                  strerror(errno));
              continue;
            } else {

              // Check if a client already is connected
              if (connected == true) {
                log_message(L_ERR,
                    "server: a client is already connected.");
                close(new_fd);
                new_fd = -1;
                continue;
              }

              // Add the new connection to the master set.
              FD_SET(new_fd, &socks);

              // Adds the new fd as top most.
              if (new_fd > highsock) {
                highsock = new_fd;
              }

              inet_ntop(their_addr.ss_family,
                  get_in_addr((struct sockaddr *)&their_addr),
                  s,
                  sizeof(s));

              log_message(L_INFO,"server: got connection from %s.", s);

              disable_all_probes();
              //Start the handle client thread
              pthread_t thread;
              input.logDecoderFormat = logDecoderFormat;
              input.clientfd = new_fd;
              input.enabledProbes = NULL;
              pthread_create(&thread, NULL, handle_clients, (void*) &input);

              connected = true;
            }
          } else {
            if ((nbytes = recv(i, buf, sizeof(buf), 0)) <= 0) {
              log_message(L_INFO,
                  "server: client disconnect detected.");

              if (server_client_suspended == 0) {
                stop_client();
              }

              close(i);
              FD_CLR(i, &socks);

              connected = false;
            } else {
              log_message(L_INFO, "server: client sent %d bytes", nbytes);

              int j = 0;

              while (j < nbytes) {
                switch (buf[j]) {
                  case MM_PROBE_REQUEST_ME_VERSION:
                  {
                    log_message(L_INFO, "server: client sent MM_PROBE_REQUEST_ME_VERSION, Returning: %s",VersionString);
                    j += sizeof(MM_ProbeGetME_VersionCmd_t);

                    send(new_fd, VersionString, MMPROBE_VERSION_STING_MAX_LEN, 0);
                    break;
                  }

                  case MM_PROBE_SET_PROBE_STATUS:
                  {
                    MM_ProbeSetStatusCmd_t *cmd = (MM_ProbeSetStatusCmd_t*)&buf[j];

                    if (cmd->ProbeStatus == MM_PROBE_STATUS_ENABLED)
                      enable_probe(cmd->ProbeId);
                    else
                      disable_probe(cmd->ProbeId);

                    j += sizeof(MM_ProbeSetStatusCmd_t);
                    break;
                  }

                  case MM_PROBE_SET_PROBE_STATUS_V2:
                  {
                    MM_ProbeSetStatusCmd_V2_t *cmd = (MM_ProbeSetStatusCmd_V2_t*)&buf[j];

                    if (cmd->ProbeStatus == MM_PROBE_STATUS_ENABLED)
                      enable_probe(cmd->ProbeId);
                    else
                      disable_probe(cmd->ProbeId);

                    j += sizeof(MM_ProbeSetStatusCmd_V2_t);
                    break;
                  }

                  case MM_PROBE_SEND_DATA:
                    log_message(L_INFO, "server: client sent MM_PROBE_SEND_DATA");

                    if (nbytes < sizeof(MM_ProbeSendDataCmd_t)) {
                      log_message(L_INFO, "server: received %d bytes but expected %d bytes", nbytes, sizeof(MM_ProbeSendDataCmd_t));
                      while(nbytes < sizeof(MM_ProbeSendDataCmd_t)) {
                        char* tmp = (char*) buf + nbytes;
                        nbytes += recv(i, tmp, sizeof(buf), 0);
                        log_message(L_INFO, "server: received extra bytes");
                      }
                    }

                    MM_ProbeSendDataCmd_t *cmd = (MM_ProbeSendDataCmd_t*)&buf[j];

                    MM_ProbeSubscriberID_t subscriber_id = cmd->SubscriberId; //Read from message
                    int fd = -1;

                    j += sizeof(MM_ProbeSendDataCmd_t);

                    if (subscriber_id < MM_PROBE_MAX_NUMBER_SUBSCRIBERS) {
                      log_message(L_INFO, "server: got subscriber_id=%d", subscriber_id);
                      fd = subscriber_list[subscriber_id];

                    } else {
                      log_message(L_ERR, "server: invalid subscriber id=%d", subscriber_id);
                      break;
                    }

                    if (fd > 0) {
                      int t = 0;
                      log_message(L_INFO, "server: proxy subscriber_id=%d", subscriber_id);

                      if ((t = send(fd, cmd->Data, cmd->DataSize, 0)) < 0)
                        log_message(L_ERR, "server: failed writing to fd=%d", fd);
                      else
                        log_message(L_INFO, "server: sent %d bytes to fd=%d", t, fd);
                    } else {
                      log_message(L_ERR, "server: invalid subscriber fd=%d", fd);
                      break;
                    }

                    break;

                  case MM_PROBE_SET_LOGGING_LOCATION:
                  {
                    int fd = -1;
                    char location_buf[MMPROBE_SHORT_MESSAGE_SIZE] = {0};
                    MM_ProbeSetLoggingLocation_t *cmd = (MM_ProbeSetLoggingLocation_t*)&buf[j];
                    log_message(L_INFO, "server: MM_PROBE_SET_LOGGING_LOCATION received...Location=%d", cmd->Location);

                    if ((fd = open(FIFO_NAME, O_WRONLY | O_NONBLOCK)) == -1) {
                      log_message(L_WARN, "server: could not open FIFO: (%s).",
                      strerror(errno));
                    } else {
                      // Write store location to the FIFO
                      if (cmd->Location == 1) {
                        sprintf(location_buf, "Phone");
                      } else {
                        sprintf(location_buf, "PC");
                      }
                      if (!write(fd, location_buf, sizeof(location_buf)) > 0) {
                        log_message(L_WARN, "server: could not send to FIFO (%s).",
                        strerror(errno));
                      }
                    }
                    close(fd);

                    j += sizeof(MM_ProbeSetLoggingLocation_t);
                    break;
                  }

                  case MM_PROBE_SUSPEND:
                  {
                    log_message(L_INFO, "server: MM_PROBE_SUSPEND received...");
                    server_client_suspended = 1;
                    connected = false;
                    j += sizeof(MM_ProbeSuspendCmd_t);
                    break;
                  }

                  case MM_PROBE_SET_PATH:
                  {
                    int fd = -1;
                    char location_buf[MMPROBE_SHORT_MESSAGE_SIZE] = {0};
                    FILE *file;
                    MM_ProbeSetPath_t *cmd = (MM_ProbeSetPath_t*)&buf[j];
                    log_message(L_INFO, "server: MM_PROBE_SET_PATH received... Path=%s", cmd->Path);
                    file = fopen(MMPROBETXT, "w");
                    if (file != NULL) {
                      fwrite(cmd->Path, 1, strlen(cmd->Path), file);
                      fclose(file);
                    } else {
                      log_message(L_ERR, "server: MM_PROBE_SET_PATH could not open file:%s for writing", MMPROBETXT);
                    }

                    if ((fd = open(FIFO_NAME, O_WRONLY | O_NONBLOCK)) == -1) {
                      log_message(L_WARN, "server: could not open FIFO: (%s).",
                      strerror(errno));
                    } else {
                      // Write store Path to the FIFO
                      sprintf(location_buf, "Path");
                      if (!write(fd, location_buf, sizeof(location_buf)) > 0) {
                        log_message(L_WARN, "server: could not send to FIFO (%s).",
                        strerror(errno));
                      }
                    }
                    close(fd);
                    j+=sizeof(MM_ProbeSetPath_t);
                    break;
                  }

                  case MM_PROBE_REQUEST_MMPROBE_VERSION:
                  {
                    log_message(L_INFO, "server: client sent MM_PROBE_REQUEST_MMPROBE_VERSION, Returning: %s", MM_PROBE_PROBING_VERSION);
                    j += sizeof(MM_ProbeGetMM_ProbeVersionCmd_t);

                    send(new_fd, MM_PROBE_PROBING_VERSION, MMPROBE_VERSION_STING_MAX_LEN, 0);
                    break;
                  }
                  default:
                    buf[nbytes] = '\0';
                    log_message(L_INFO, "server: client sent bogus data: %s.", buf);
                    j = nbytes;
                    break;
                }

              }
            }
          }
        }
      }
    }
  }

  log_message(L_INFO, "server : shutdown");
  return 0;
}
Пример #11
0
void handle_user_input(connection_info *connection) {
	char input[255];
	fgets(input, 255, stdin);
	trim_newline(input);

	if (strcmp(input, "/q") == 0 || strmp(input, "/quit") == 0) {
		stop_client(connection);
	} else if (strcmp(input, "/l") == 0 || strcmp(input, "/quit") == 0) {
		message msg;
		msg.type = GET_USERS;

		if (send(connection->socket, &msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	} else if (strcmp(input, "/h") == 0 || strcmp(input, "/help") == 0) {
		puts("/quit or /q: Exit the program");
		puts("/help or /h: Displays help information");
		puts("/list or /l: Displays list of users in chatroom");
		puts("/m <username> <message> Send a private message to <username>");
	} else if (strcmp(input, "/m", 2) == 0) {
		message msg;
		msg.type = PRIVATE_MESSAGE;

		char * toUsername, *chatMsg;

		toUsername = strtok(input+3, " ");

		if (toUsername == NULL) {
			puts(KRED, "Format for private messages is: /, <username> <message" RESET);
			return;
		}
		if (toUsername == 0) {
			puts(KRED, "You must enter a username for a private message" RESET);
			return;
		}
		if (toUsername > 20) {
			puts(KRED, "The username must be between 1 and 20 characters" RESET);
			return;
		}

		chatMsg = strtok(NULL, "");

		if (chatMsg == NULL) {
			puts(KRED, "You must enter a message to send to the specified user" RESET);
			return;
		}
		strncpy(msg.username, toUsername, 20);
		strncpy(msg.data, chatMsg, 255);

		if (send(connection->socket, $msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	} else {
		// Regular public message
		message msg;
		msg.type = PUBLIC_MESSAGE;
		strncpy(msg.username, connection->username, 20);

		if (strlen(input) == 0);

		// Send the data
		if (send(connection->socket, &msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	}
}
Пример #12
0
	void Network::start_client() {
		stop_client();	//just in case
		client = new Client("127.0.0.1", 5555,"127.0.0.1");
		has_client = true;
		client->start();
	}
Пример #13
0
	Network::~Network() {
		stop_client();
		stop_server();
	}
Пример #14
0
// Signals handler
static void termh(int x)
{
    stop_client();
}
int do_autotest_regression_streaming_transcode_negative(int argc, const char* argv[])
{
    int rv = VPL_OK;
    u32 retry = 0;
    u32 photoAlbumNum = 0;
    u32 photoNum = 0;
    u32 expectedPhotoNum = 0;
    std::string photosToStream = "-1";       // meaning no limit
    int cloudPCId = 1;
    int clientPCId = 2;
    std::string CloudPC_alias = "CloudPC";
    std::string MD_alias = "MD";
    std::string osVersion;
    const char* TEST_TRANSCODE2_STR = "SdkTranscodeStreamingPositive";

    bool full = false;

    if (argc == 6 && (strcmp(argv[5], "-f") == 0 || strcmp(argv[5], "--fulltest") == 0) ) {
        full = true;
    }

    if (checkHelp(argc, argv) || (argc < 5) || (argc == 6 && !full)) {
        printf("AutoTest %s <username> <password> <expectedPhotoNum> [<fulltest>(-f/--fulltest)]\n", argv[0]);
        return 0;   // No arguments needed 
    }

    LOG_ALWAYS("AutoTest Transcode Streaming: Domain(%s) User(%s) Password(%s) ExpectedPhotoNum(%s)",
               argv[1], argv[2], argv[3], argv[4]);

    // Does a hard stop for all ccds
    {
        const char *testArg[] = { "StopCCD" };
        stop_ccd_hard(ARRAY_ELEMENT_COUNT(testArg), testArg);
    }

    expectedPhotoNum = static_cast<u32>(atoi(argv[4]));

    VPLFile_Delete("dumpfile");

    LOG_ALWAYS("\n\n==== Launching Cloud PC CCD (instanceId %d) ====", cloudPCId);
	SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv);
    if (rv < 0) {
		setCcdTestInstanceNum(cloudPCId);
    }

	CHECK_LINK_REMOTE_AGENT(CloudPC_alias, TEST_TRANSCODE2_STR, rv);

	START_CCD(TEST_TRANSCODE2_STR, rv);
    START_CLOUDPC(argv[2], argv[3], TEST_TRANSCODE2_STR, true, rv);

    VPLThread_Sleep(VPLTIME_FROM_MILLISEC(1000));

    LOG_ALWAYS("\n\n==== Launching MD CCD (instanceId %d) ====", clientPCId);
    SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv);
    if (rv < 0) {
        setCcdTestInstanceNum(clientPCId);
    }

    CHECK_LINK_REMOTE_AGENT(MD_alias, TEST_TRANSCODE2_STR, rv);

    QUERY_TARGET_OSVERSION(osVersion, TEST_TRANSCODE2_STR, rv);

    START_CCD(TEST_TRANSCODE2_STR, rv);

    UPDATE_APP_STATE(TEST_TRANSCODE2_STR, rv);

    START_CLIENT(argv[2], argv[3], TEST_TRANSCODE2_STR, true, rv);

    VPLThread_Sleep(VPLTIME_FROM_MILLISEC(1000));

    // make sure both cloudpc/client has the device linked info updated
    LOG_ALWAYS("\n\n== Checking cloudpc and Client device link status ==");
    {
		std::vector<u64> deviceIds;
        u64 userId = 0;
        u64 cloudPCDeviceId = 0;
        u64 MDDeviceId = 0;
        const char *testCloudStr = "CheckCloudPCDeviceLinkStatus";
        const char *testMDStr = "CheckMDDeviceLinkStatus";

        SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv);
        if (rv < 0) {
            setCcdTestInstanceNum(cloudPCId);
        }

        rv = getUserIdBasic(&userId);
        if (rv != 0) {
            LOG_ERROR("Fail to get user id:%d", rv);
            CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv);
        }

        rv = getDeviceId(&cloudPCDeviceId);
        if (rv != 0) {
            LOG_ERROR("Fail to get CloudPC device id:%d", rv);
            CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv);
       }

        SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv);
        if (rv < 0) {
            setCcdTestInstanceNum(cloudPCId);
        }

        rv = getDeviceId(&MDDeviceId);
        if (rv != 0) {
            LOG_ERROR("Fail to get MD device id:%d", rv);
            CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testMDStr, rv);
        }


        deviceIds.push_back(cloudPCDeviceId);
        LOG_ALWAYS("Add Device Id "FMTu64, cloudPCDeviceId);
        deviceIds.push_back(MDDeviceId);
        LOG_ALWAYS("Add Device Id "FMTu64, MDDeviceId);

        rv = wait_for_devices_to_be_online_by_alias(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), cloudPCId, userId, deviceIds, 20);
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv);
        rv = wait_for_devices_to_be_online_by_alias(TEST_TRANSCODE2_STR, MD_alias.c_str(), clientPCId, userId, deviceIds, 20);
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testMDStr, rv);

        SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv);
        if (rv < 0) {
            setCcdTestInstanceNum(clientPCId);
        }

        rv = wait_for_cloudpc_get_accesshandle(userId, cloudPCDeviceId, 20);
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CheckCloudPCGetAccessHandle", rv);
	}

    LOG_ALWAYS("\n\n==== Testing ClearMetadata (CloudPC) ====");
	SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv);
    if (rv < 0) {
		setCcdTestInstanceNum(cloudPCId);
    }

    {
        const char *testStr = "ClearMetadata";
        const char *testArg[] = { testStr };
        rv = msa_delete_catalog(ARRAY_ELEMENT_COUNT(testArg), testArg);
        if(rv != 0) {
            LOG_ERROR("RegressionStreaming_ClearMetadata failed!");
        }
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testStr, rv);
    }

#if defined(CLOUDNODE)
    LOG_ALWAYS("\n\n==== Testing CloudMedia CloudnodeAddPhoto (ClientPC) ====");
    SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv);
    if (rv < 0) {
        setCcdTestInstanceNum(clientPCId);
    }

    {
        std::string dxroot;
        std::string photoSetPath;
        rv = getDxRootPath(dxroot);
        if (rv != VPL_OK) {
            LOG_ERROR("Fail to set %s root path", argv[0]);
            goto exit;
        }
        photoSetPath.assign(dxroot.c_str());
        const char *testStr1 = "CloudMedia";
        const char *testStr2 = "CloudnodeAddPhoto";
        photoSetPath.append("/GoldenTest/image_transcode_negative_test_1");
        const char *testArg4[] = { testStr1, testStr2, photoSetPath.c_str() };
        rv = cloudmedia_commands(3, testArg4);
        if (rv != VPL_OK) {
            LOG_ERROR("SdkTranscodeStreaming2_CloudMedia_CloudnodeAddPhoto failed!");
        }
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CloudMedia_CloudnodeAddPhoto", rv);
    }
#endif // CLOUDNODE

    LOG_ALWAYS("\n\n==== Testing CloudMedia AddPhoto (CloudPC) ====");
    SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv);
    if (rv < 0) {
        setCcdTestInstanceNum(cloudPCId);
    }

    {
        std::string dxroot;
        std::string photoSetPath;
        rv = getDxRootPath(dxroot);
        if (rv != VPL_OK) {
            LOG_ERROR("Fail to set %s root path", argv[0]);
            goto exit;
        }
        photoSetPath.assign(dxroot.c_str());
        const char *testStr1 = "CloudMedia";
        const char *testStr2 = "AddPhoto";
        photoSetPath.append("/GoldenTest/image_transcode_negative_test_1");
        const char *testArg4[] = { testStr1, testStr2, photoSetPath.c_str() };
        rv = cloudmedia_commands(3, testArg4);
        if (rv != VPL_OK) {
            LOG_ERROR("SdkTranscodeStreaming2_CloudMedia_AddPhoto failed!");
        }
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CloudMedia_AddPhoto", rv);
    }

    // Verify if the metadata is synced
    retry = 0;
    SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv);
    if (rv < 0) {
        setCcdTestInstanceNum(clientPCId);
    }

    LOG_ALWAYS("\n\n==== List Metadata (ClientPC) ====");
    {
        VPLTime_t startTime = VPLTime_GetTimeStamp();
        while(1) {
            rv = mca_get_photo_object_num(photoAlbumNum, photoNum);
            if(rv != VPL_OK) {
                LOG_ERROR("Cannot get photo count from metadata");
            }
            else if(photoNum == expectedPhotoNum) {
                u64 elapsedTime = VPLTIME_TO_SEC(VPLTime_GetTimeStamp() - startTime);
                LOG_ALWAYS("Retry (%d) times waited ("FMTu64") seconds for photo to be synced.", retry, elapsedTime);
                break;
            }
            if(retry++ > METADATA_SYNC_TIMEOUT) {
                u64 elapsedTime = VPLTIME_TO_SEC(VPLTime_GetTimeStamp() - startTime);
                LOG_ERROR("Timeout retry (%d) waiting for metadata to sync; waited for ("FMTu64") seconds.", retry, elapsedTime);
                rv = -1;
                break;
            } else {
                LOG_ALWAYS("Waiting (cnt %d) photoNum (%d) photoAlbumNum (%d)", retry, photoNum, photoAlbumNum);
            }
            VPLThread_Sleep(VPLTIME_FROM_SEC(1));
        }
        LOG_ALWAYS("Photo added by CloudPC: %d; Expected photo: %d", photoNum, expectedPhotoNum);
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "Verify_Uploaded_Photo_Num1", rv);
    }

    LOG_ALWAYS("\n\n==== SetupStreamTest to generate dump file ====");
    {
        const char *testStr = "SetupStreamTest";
        const char *testArg[] = { testStr, "-d", "dumpfile", "-f", "2", "-M", photosToStream.c_str() };
        rv = setup_stream_test(ARRAY_ELEMENT_COUNT(testArg), testArg);
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "SetupStreamTest_dumpfile", rv);
    }

    // Negative Test - Scale an invalid photo to 800x800
    LOG_ALWAYS("\n\n==== Negative Test, scale an invalid photo to 800x800 ====");
    {
        const char *testStr = "TimeStreamDownload";
        const char *testArg[] = { testStr, "-d", "dumpfile", "-R", "800,800", "-f", "JPG" };
        rv = time_stream_download(ARRAY_ELEMENT_COUNT(testArg), testArg);
        if (rv == -1) {
            rv = 0;
        } else if (rv == 0) {
            if(osVersion == OS_LINUX) {
                rv = -1;
                CHECK_AND_PRINT_EXPECTED_TO_FAIL(TEST_TRANSCODE2_STR, "NegativeTest_InvalidImage", rv, "13344");
                rv = 0;
                goto exit;
            }
        } else {
            LOG_ERROR("Expected -1, but got %d", rv);
            rv = -1;
        }
        CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "NegativeTest_InvalidImage", rv);
    }

exit:
    LOG_ALWAYS("\n\n== Freeing Client ==");
    if(set_target_machine(MD_alias.c_str()) < 0)
        setCcdTestInstanceNum(clientPCId);
    {
        const char *testArg[] = { "StopClient" };
        stop_client(ARRAY_ELEMENT_COUNT(testArg), testArg);
    }

    if (isWindows(osVersion) || osVersion.compare(OS_LINUX) == 0) {
        const char *testArg[] = { "StopCCD" };
        stop_ccd_soft(ARRAY_ELEMENT_COUNT(testArg), testArg);
    }

    LOG_ALWAYS("\n\n== Freeing Cloud PC ==");
    if(set_target_machine(CloudPC_alias.c_str()) < 0)
        setCcdTestInstanceNum(cloudPCId);
    {
        const char *testArg[] = { "StopCloudPC" };
        stop_cloudpc(ARRAY_ELEMENT_COUNT(testArg), testArg);
    }

    {
        const char *testArg[] = { "StopCCD" };
        stop_ccd_soft(ARRAY_ELEMENT_COUNT(testArg), testArg);
    }

    return rv;
}