Beispiel #1
0
Status FirehoseLogForwarder::setUp() {
  // Set up client
  Status s = makeAWSClient<Aws::Firehose::FirehoseClient>(client_);
  if (!s.ok()) {
    return s;
  }

  if (FLAGS_aws_firehose_stream.empty()) {
    return Status(1,
                  "Stream name must be specified with --aws_firehose_stream");
  }

  // Make sure we can connect to designated stream
  Aws::Firehose::Model::DescribeDeliveryStreamRequest r;
  r.SetDeliveryStreamName(FLAGS_aws_firehose_stream);

  auto outcome = client_->DescribeDeliveryStream(r);
  if (!outcome.IsSuccess()) {
    return Status(
        1, "Could not find Firehose stream: " + FLAGS_aws_firehose_stream);
  }
  VLOG(1) << "Firehose logging initialized with stream: "
          << FLAGS_aws_firehose_stream;
  return Status(0);
}
/**
 * Creates an alias for an AWS account, based on command line input
 */
int main(int argc, char** argv)
{
    if(argc != 2) {
        std::cout << "Usage: iam_create_account_alias <alias_name>" <<
            std::endl;
        return 1;
    }

    Aws::String alias_name(argv[1]);
    Aws::SDKOptions options;
    Aws::InitAPI(options);

    {
        Aws::IAM::IAMClient iam;
        Aws::IAM::Model::CreateAccountAliasRequest request;
        request.SetAccountAlias(alias_name);

        auto outcome = iam.CreateAccountAlias(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Error creating account alias " << alias_name << ": "
                << outcome.GetError().GetMessage() << std::endl;
        } else {
            std::cout << "Successfully created account alias " << alias_name <<
                std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
void CreateAlarmAndEnableActions(
    const Aws::String& alarm_name, const Aws::String& instanceId,
    const Aws::String& actionArn)
{
    Aws::CloudWatch::CloudWatchClient cw;
    Aws::CloudWatch::Model::PutMetricAlarmRequest request;
    request.SetAlarmName(alarm_name);
    request.SetComparisonOperator(
        Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
    request.SetEvaluationPeriods(1);
    request.SetMetricName("CPUUtilization");
    request.SetNamespace("AWS/EC2");
    request.SetPeriod(60);
    request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
    request.SetThreshold(70.0);
    request.SetActionsEnabled(false);
    request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
    request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);
    request.AddAlarmActions(actionArn);

    Aws::CloudWatch::Model::Dimension dimension;
    dimension.SetName("InstanceId");
    dimension.SetValue(instanceId);
    request.AddDimensions(dimension);

    auto outcome = cw.PutMetricAlarm(request);
    if (!outcome.IsSuccess())
    {
        std::cout << "Failed to create cloudwatch alarm:" <<
            outcome.GetError().GetMessage() << std::endl;
        return;
    }

    Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request;
    enable_request.AddAlarmNames(alarm_name);

    auto enable_outcome = cw.EnableAlarmActions(enable_request);
    if (!enable_outcome.IsSuccess())
    {
        std::cout << "Failed to enable alarm actions:" <<
            enable_outcome.GetError().GetMessage() << std::endl;
        return;
    }

    std::cout << "Successfully created alarm " << alarm_name <<
        " and enabled actions on it." << std::endl;
}
    ReplicationTransportSPtr ReplicaManagerWrapper::CreateTransport(REConfigSPtr const & config)
    {
        auto transport = ReplicationTransport::Create(config->ReplicatorListenAddress);

        auto errorCode = transport->Start(L"localhost:0");
        ASSERT_IFNOT(errorCode.IsSuccess(), "Failed to start: {0}", errorCode);

        return transport;
    }
/*
 * Load snapshot data
 */
void Engine::LoadFromSnapshot() {
  if (!current_snapshot_.Valid()) {
    LOGI("Snapshot is not valid!");
    EnableUI(true);
    return;
  }
  LOGI("Opening file");
  service_->Snapshots()
      .Open(current_snapshot_.FileName(),
            gpg::SnapshotConflictPolicy::MANUAL,
            [this](gpg::SnapshotManager::OpenResponse const & response) {
    LOGI("Opened file");
    if (IsSuccess(response.status)) {
      //Do need conflict resolution?
      if (response.data.Valid() == false) {
        if (response.conflict_id != "") {
          LOGI("Need conflict resolution");
          bool b = ResolveConflicts(response, 0);
          if (!b) {
            LOGI("Failed resolving conflicts");
            EnableUI(true);
            return;
          }
        } else {
          EnableUI(true);
          return;
        }
      }

      LOGI("Reading file");
      gpg::SnapshotManager::ReadResponse responseRead =
          service_->Snapshots().ReadBlocking(response.data);
      if (IsSuccess(responseRead.status)) {
        LOGI("Parsing data");
        ParseSnapshotData(responseRead.data);
        ndk_helper::JNIHelper::GetInstance()->RunOnUiThread([this]() {
          UpdateGameUI();
        });
      }
    }

    EnableUI(true);
  });
}
Beispiel #6
0
ICCItem *CMission::GetProperty (const CString &sName)

//	GetProperty
//
//	Returns a property

{
    CCodeChain &CC = g_pUniverse->GetCC();

    if (strEquals(sName, PROPERTY_IS_ACTIVE))
        return CC.CreateBool(IsActive());

    else if (strEquals(sName, PROPERTY_IS_COMPLETED))
        return CC.CreateBool(IsCompleted());

    else if (strEquals(sName, PROPERTY_IS_DEBRIEFED))
        return CC.CreateBool(m_fDebriefed);

    else if (strEquals(sName, PROPERTY_IS_DECLINED))
        return CC.CreateBool(m_fDeclined);

    else if (strEquals(sName, PROPERTY_IS_FAILURE))
        return CC.CreateBool(IsFailure());

    else if (strEquals(sName, PROPERTY_IS_INTRO_SHOWN))
        return CC.CreateBool(m_fIntroShown);

    else if (strEquals(sName, PROPERTY_IS_OPEN))
        return CC.CreateBool(m_iStatus == statusOpen);

    else if (strEquals(sName, PROPERTY_IS_RECORDED))
        return CC.CreateBool(IsRecorded());

    else if (strEquals(sName, PROPERTY_IS_SUCCESS))
        return CC.CreateBool(IsSuccess());

    else if (strEquals(sName, PROPERTY_IS_UNAVAILABLE))
        return CC.CreateBool(IsUnavailable());

    else if (strEquals(sName, PROPERTY_NODE_ID))
        return (m_sNodeID.IsBlank() ? CC.CreateNil() : CC.CreateString(m_sNodeID));

    else if (strEquals(sName, PROPERTY_OWNER_ID))
    {
        if (m_pOwner.GetID() == OBJID_NULL)
            return CC.CreateNil();
        else
            return CC.CreateInteger(m_pOwner.GetID());
    }

    else if (strEquals(sName, PROPERTY_UNID))
        return CC.CreateInteger(m_pType->GetUNID());

    else
        return CSpaceObject::GetProperty(sName);
}
bool doesBucketExists(ClientPtrType client, String bucketName)
{
    auto objectReq = Aws::S3::Model::HeadBucketRequest();
    auto objectRes = client->HeadBucket(objectReq.WithBucket(bucketName));
    if (objectRes.IsSuccess())
    {
        return true;
    }
    return false;
}
std::tuple<bool, Map> doesObjectExists(ClientPtrType client, String bucketName, String key)
{
    auto objectReq = Aws::S3::Model::HeadObjectRequest();
    objectReq.WithBucket(bucketName).WithKey(key);
    auto objectRes = client->HeadObject(objectReq);
    if (objectRes.IsSuccess())
    {
        return std::make_tuple(true, objectRes.GetResult().GetMetadata());
    }
    return std::make_tuple(false, Map());
}
void CreateSecurityGroup(
        const Aws::String& group_name, const Aws::String& description,
        const Aws::String& vpc_id)
{
    Aws::EC2::EC2Client ec2;
    Aws::EC2::Model::CreateSecurityGroupRequest request;

    request.SetGroupName(group_name);
    request.SetDescription(description);
    request.SetVpcId(vpc_id);

    auto outcome = ec2.CreateSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cout << "Failed to create security group:" <<
            outcome.GetError().GetMessage() << std::endl;
        return;
    }

    std::cout << "Successfully created security group named " << group_name <<
        std::endl;

    Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorize_request;

    authorize_request.SetGroupName(group_name);

    BuildSampleIngressRule(authorize_request);

    auto ingress_request = ec2.AuthorizeSecurityGroupIngress(
            authorize_request);

    if(!ingress_request.IsSuccess()) {
        std::cout << "Failed to set ingress policy for security group " <<
            group_name << ":" << ingress_request.GetError().GetMessage() <<
            std::endl;
        return;
    }

    std::cout << "Successfully added ingress policy to security group " <<
        group_name << std::endl;
}
/**
 * Lists all iam policies
 */
int main(int argc, char** argv)
{
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::IAM::IAMClient iam;
        Aws::IAM::Model::ListPoliciesRequest request;

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = iam.ListPolicies(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to list iam policies: " <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left << std::setw(55) << "Name" <<
                    std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                    std::setw(64) << "Description" << std::setw(12) <<
                    "CreateDate" << std::endl;
                header = true;
            }

            const auto &policies = outcome.GetResult().GetPolicies();
            for (const auto &policy : policies)
            {
                std::cout << std::left << std::setw(55) <<
                    policy.GetPolicyName() << std::setw(30) <<
                    policy.GetPolicyId() << std::setw(80) << policy.GetArn() <<
                    std::setw(64) << policy.GetDescription() << std::setw(12) <<
                    policy.GetCreateDate().ToGmtString(DATE_FORMAT) <<
                    std::endl;
            }

            if (outcome.GetResult().GetIsTruncated())
            {
                request.SetMarker(outcome.GetResult().GetMarker());
            }
            else
            {
                done = true;
            }
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
 void ReplicaManagerWrapper::UpdateConfiguration(
     ReplicaInformationVector const & previousActiveReplicas,
     ULONG previousQuorum,
     ReplicaInformationVector const & currentActiveReplicas,
     ULONG currentQuorum)
 {
     auto error = replicaManagerSPtr_->UpdateConfiguration(
         previousActiveReplicas,
         previousQuorum,
         currentActiveReplicas, 
         currentQuorum, 
         true,
         true);
     VERIFY_IS_TRUE(error.IsSuccess(), L"UpdateConfiguration (catchup replicas set) should succeed");
 }
Beispiel #12
0
void getFakeObject(ClientPtrType client, String bucketName, String key)
{
    String base = "=== Get Fake Object [" + bucketName + "/" + key;
    std::cout << base << "]: Start ===\n";
    std::cout << "Reading from " << key << "\n";
    auto inpData = Aws::MakeShared<Aws::FStream>("GetObjectInputStream",
            key.c_str(), std::ios_base::in | std::ios_base::binary);
    auto objReq = Aws::S3::Model::GetObjectRequest();
    objReq.WithBucket(bucketName).WithKey(key);
    auto objRes = client->GetObject(objReq);
    if (objRes.IsSuccess())
    {
        std::cout << base << "]: Failed ===\n";
    }
    std::cout << base << "]: End ===\n\n";
}
Beispiel #13
0
void copyObject(ClientPtrType client, String bucketName, String src, String dst)
{
    String base = "=== Copy Object [" + bucketName + "/" + src + "->" + dst;
    std::cout << base << "]: Start ===\n";
    auto objReq = Aws::S3::Model::CopyObjectRequest();
    objReq.WithBucket(bucketName).WithCopySource(bucketName + "/" + src);
    auto objRes = client->CopyObject(objReq.WithKey(dst));
    if (!objRes.IsSuccess())
    {
        std::cout << base << "]: Client Side failure ===\n";
    }
    if (!std::get<0>(doesObjectExists(client, bucketName, dst)))
    {
        std::cout << base << "]: Failed ===\n";
    }
    std::cout << base << "]: End ===\n\n";
}
Beispiel #14
0
void deleteObject(ClientPtrType client, String bucketName, String key)
{
    String base = "=== Delete Object [" + bucketName + "/" + key;
    std::cout << base << "]: Start ===\n";
    auto objReq = Aws::S3::Model::DeleteObjectRequest();
    objReq.WithBucket(bucketName);
    auto objRes = client->DeleteObject(objReq.WithKey(key));
    if (!objRes.IsSuccess())
    {
        std::cout << base << "]: Client Side failure ===\n";
    }
    if (std::get<0>(doesObjectExists(client, bucketName, key)))
    {
        std::cout << base << "]: Deletion of " << key << " Failed ===\n";
    }
    std::cout << base << "]: End ===\n\n";
}
/**
 * Connects an sqs queue to an associated dead letter queue based on command
 * line input
 */
int main(int argc, char** argv)
{
    if (argc != 4)
    {
        std::cout << "Usage: dead_letter_queue <source_queue_url> " <<
            "<dead_letter_queue_arn> <max_messages>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String src_queue_url = argv[1];
        Aws::String queue_arn = argv[2];

        Aws::StringStream ss(argv[3]);
        int max_msg = 1;
        ss >> max_msg;

        Aws::SQS::SQSClient sqs;

        Aws::String redrivePolicy = MakeRedrivePolicy(queue_arn, max_msg);

        Aws::SQS::Model::SetQueueAttributesRequest request;
        request.SetQueueUrl(src_queue_url);
        request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::RedrivePolicy,
            redrivePolicy);

        auto outcome = sqs.SetQueueAttributes(request);
        if (outcome.IsSuccess())
        {
            std::cout << "Successfully set dead letter queue for queue  " <<
                src_queue_url << " to " << queue_arn << std::endl;
        }
        else
        {
            std::cout << "Error setting dead letter queue for queue " <<
                src_queue_url << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
Beispiel #16
0
void deleteBucket(ClientPtrType client, String bucketName)
{
    String base = "=== Delete Bucket [" + bucketName;
    std::cout << base << "]: Start ===\n";
    auto bucketReq = Aws::S3::Model::DeleteBucketRequest();
    auto bucketRes = client->DeleteBucket(bucketReq.WithBucket(bucketName));
    if (!bucketRes.IsSuccess())
    {
        std::cout << base << "]: Client Side failure ===\n";
        std::cout << bucketRes.GetError().GetExceptionName() << "\t" <<
                     bucketRes.GetError().GetMessage() << "\n";
    }
    if (doesBucketExists(client, bucketName))
    {
        std::cout << base << "]: Failed ===\n";
    }
    std::cout << base << "]: End ===\n\n";
}
/**
 * Posts a sample cloudwatch event, based on command line input
 */
int main(int argc, char** argv)
{
    if (argc != 4)
    {
        std::cout << "Usage:" << std::endl << "  put_events " <<
            "<resource_arn> <sample_key> <sample_value>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;

    Aws::InitAPI(options);
    {
        Aws::String resource_arn(argv[1]);
        Aws::String event_key(argv[2]);
        Aws::String event_value(argv[3]);

        Aws::CloudWatchEvents::CloudWatchEventsClient cwe;

        Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry;
        event_entry.SetDetail(MakeDetails(event_key, event_value));
        event_entry.SetDetailType("sampleSubmitted");
        event_entry.AddResources(resource_arn);
        event_entry.SetSource("aws-sdk-cpp-cloudwatch-example");

        Aws::CloudWatchEvents::Model::PutEventsRequest request;
        request.AddEntries(event_entry);

        auto outcome = cwe.PutEvents(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to post cloudwatch event: " <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully posted cloudwatch event" << std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
Beispiel #18
0
// Updates local player achievements with values from the server:
void GPGManager::FetchAchievements() {
  if (!LoggedIn() || achievement_data_state_ == kPending) return;
  achievement_data_state_ = kPending;

  game_services_->Achievements().FetchAll(
      [this](const gpg::AchievementManager::FetchAllResponse &far) mutable {

        pthread_mutex_lock(&achievements_mutex_);

        if (IsSuccess(far.status)) {
          achievement_data_state_ = kComplete;
          achievement_data_initialized_ = true;
        } else {
          achievement_data_state_ = kFailed;
        }

        achievement_data_ = far.data;
        pthread_mutex_unlock(&achievements_mutex_);
      });
}
Beispiel #19
0
void GPGManager::FetchPlayer() {
  game_services_->Players().FetchSelf([this](
      const gpg::PlayerManager::FetchSelfResponse &fsr) mutable {

    pthread_mutex_lock(&players_mutex_);
    if (IsSuccess(fsr.status)) {
      gpg::Player *player_data = new gpg::Player(fsr.data);
      SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                  "GPG: got player info. ID = %s, name = %s, avatar=%s",
                  player_data->Id().c_str(), player_data->Name().c_str(),
                  player_data->AvatarUrl(gpg::ImageResolution::HI_RES).c_str());
      player_data_.reset(player_data);
    } else {
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                   "GPG: failed to get player info");
      player_data_.reset(nullptr);
    }
    pthread_mutex_unlock(&players_mutex_);
  });
}
/**
 * Updates the status (active/inactive) of an iam user's access key, based on
 * command line input
 */
int main(int argc, char** argv)
{
    if(argc != 4) {
        PrintUsage();
        return 1;
    }

    Aws::String user_name(argv[1]);
    Aws::String accessKeyId(argv[2]);

    auto status =
        Aws::IAM::Model::StatusTypeMapper::GetStatusTypeForName(argv[3]);

    if (status == Aws::IAM::Model::StatusType::NOT_SET) {
        PrintUsage();
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);

    {
        Aws::IAM::IAMClient iam;
        Aws::IAM::Model::UpdateAccessKeyRequest request;
        request.SetUserName(user_name);
        request.SetAccessKeyId(accessKeyId);
        request.SetStatus(status);

        auto outcome = iam.UpdateAccessKey(request);
        if (outcome.IsSuccess()) {
            std::cout << "Successfully updated status of access key " <<
                accessKeyId << " for user " << user_name << std::endl;
        } else {
            std::cout << "Error updated status of access key " << accessKeyId <<
                " for user " << user_name << ": " <<
                outcome.GetError().GetMessage() << std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
/*
 * Show quest UI
 */
void Engine::ShowQuestUI() {
  EnableUI(false);
  service_->Quests().ShowAllUI([this](
      gpg::QuestManager::QuestUIResponse const & response) {
    if (IsSuccess(response.status)) {
      if (response.accepted_quest.Valid())
      {
        LOGI("Accepted a quest");
        EnableUI(true);
      }
      if (response.milestone_to_claim.Valid())
      {
        LOGI("Claimed a milestone");
        ClaimMilestone(response.milestone_to_claim);
      }
    } else {
      LOGI("Invalid response status");
      EnableUI(true);
    }
  });
}
/**
 * Creates a cloud watch logs subscription filter, based on command line input
 */
int main(int argc, char** argv)
{
    if (argc != 5)
    {
        std::cout << "Usage: " << std::endl << "  put_subscription_filter "
            << "<filter_name> <filter_pattern> <log_group_name> " <<
            "<lambda_function_arn>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String filter_name(argv[1]);
        Aws::String filter_pattern(argv[2]);
        Aws::String log_group(argv[3]);
        Aws::String dest_arn(argv[4]);

        Aws::CloudWatchLogs::CloudWatchLogsClient cwl;
        Aws::CloudWatchLogs::Model::PutSubscriptionFilterRequest request;
        request.SetFilterName(filter_name);
        request.SetFilterPattern(filter_pattern);
        request.SetLogGroupName(log_group);
        request.SetDestinationArn(dest_arn);
        auto outcome = cwl.PutSubscriptionFilter(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create cloudwatch logs subscription filter "
                << filter_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully created cloudwatch logs subscription " <<
                "filter " << filter_name << std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
        void OnTryInvalidateCompleted(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
        {
            if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }

            auto const & thisSPtr = operation->Parent;

            bool isFirstWaiter = false;
            TestCacheEntrySPtr entry;

            auto error = cache_.EndTryInvalidate(operation, isFirstWaiter, entry);

            Trace.WriteInfo(
                TraceComponent, 
                "EndTryInvalidate(key={0} worker={1}): error={2} isFirst={3}",
                key_,
                workerId_,
                error,
                isFirstWaiter);

            if (error.IsSuccess())
            {
                if (isFirstWaiter)
                {
                    this->ProcessFirstWaiterOnInvalidate(thisSPtr);
                }
                else
                {
                    this->ProcessEntryOnInvalidate(thisSPtr, entry);
                }
            }
            else if (error.IsError(ErrorCodeValue::Timeout))
            {
                this->StartTryGet(thisSPtr);
            }
            else
            {
                this->TryComplete(thisSPtr, error);
            }
        }
/**
 * Creates a long-polled sqs queue based on command line input
 */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        std::cout << "Usage: long_polling_on_create_queue <queue_name> " <<
            "<poll_time_in_seconds>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String queue_name = argv[1];
        Aws::String poll_time = argv[2];

        Aws::SQS::SQSClient sqs;

        Aws::SQS::Model::CreateQueueRequest request;
        request.SetQueueName(queue_name);
        request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds,
            poll_time);

        auto outcome = sqs.CreateQueue(request);
        if (outcome.IsSuccess())
        {
            std::cout << "Successfully created queue " << queue_name <<
                std::endl;
        }
        else
        {
            std::cout << "Error creating queue " << queue_name << ": " <<
                outcome.GetError().GetMessage() << std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
/**
 * Deletes an access key from an IAM user, based on command line input
 */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        std::cout << "Usage: delete_access_key <user_name> <access_key_id>"
            << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String user_name(argv[1]);
        Aws::String key_id(argv[2]);

        Aws::IAM::IAMClient iam;

        Aws::IAM::Model::DeleteAccessKeyRequest request;
        request.SetUserName(user_name);
        request.SetAccessKeyId(key_id);

        auto outcome = iam.DeleteAccessKey(request);

        if (!outcome.IsSuccess())
        {
            std::cout << "Error deleting access key " << key_id << " from user "
                << user_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully deleted access key " << key_id
                << " for IAM user " << user_name << std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
Beispiel #26
0
void deleteObjects(ClientPtrType client, String bucketName, String prefix, size_t num)
{
    String base = "=== Delete Objects [" + bucketName + "/" + prefix;
    std::cout << base << "]: Start ===\n";
    Aws::Vector<Aws::S3::Model::ObjectIdentifier> objects;
    for (size_t i = 0; i < num; ++i)
    {
        objects.push_back(Aws::S3::Model::ObjectIdentifier().WithKey(prefix + std::to_string(i).c_str()));
    }

    auto objReq = Aws::S3::Model::DeleteObjectsRequest();
    objReq.WithBucket(bucketName).WithDelete(Aws::S3::Model::Delete().WithObjects(objects));
    auto objRes = client->DeleteObjects(objReq);
    if (!objRes.IsSuccess())
    {
        std::cout << base << "]: Client Side failure ===\n";
    }/*
    if (std::get<0>(doesObjectExists(client, bucketName, key)))
    {
        std::cout << base << "]: Deletion of " << key << " Failed ===\n";
    }*/
    std::cout << base << "]: End ===\n\n";
}
Beispiel #27
0
void getObject(ClientPtrType client, String bucketName, String key, String path, Map metadata)
{
    String base = "=== Get Object [" + bucketName + "/" + key;
    std::cout << base << "]: Start ===\n";
    std::cout << "Reading from " << path << "\n";
    auto inpData = Aws::MakeShared<Aws::FStream>("GetObjectInputStream",
            path.c_str(), std::ios_base::in | std::ios_base::binary);
    auto objReq = Aws::S3::Model::GetObjectRequest();
    objReq.WithBucket(bucketName).WithKey(key);
    auto objRes = client->GetObject(objReq);
    if (!objRes.IsSuccess())
    {
        std::cout << base << "]: Client Side failure ===\n";
        std::cout << objRes.GetError().GetExceptionName() << "\t" <<
                     objRes.GetError().GetMessage() << "\n";
        std::cout << base << "]: Failed ===\n";
    }
    else
    {
        if (!metadata.empty())
        {
            if (metadata != objRes.GetResult().GetMetadata())
            {
                std::cout << objRes.GetResult().GetMissingMeta() << "\n";
                print(metadata);
                print(objRes.GetResult().GetMetadata());
                std::cout << base << "]: Metadata not equal ===\n";
            }
        }
        Aws::IOStream& file = objRes.GetResult().GetBody();
        if (!doFilesMatch(inpData.get(), file))
        {
            std::cout << base << "]: Content not equal ===\n";
        }
    }
    std::cout << base << "]: End ===\n\n";
}
/**
 * Creates a fixed policy with name based on command line input
 */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        std::cout << "Usage: create_policy <policy_name> <resource_arn>" <<
            std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String policy_name(argv[1]);
        Aws::String rsrc_arn(argv[2]);

        Aws::IAM::IAMClient iam;

        Aws::IAM::Model::CreatePolicyRequest request;
        request.SetPolicyName(policy_name);
        request.SetPolicyDocument(BuildSamplePolicyDocument(rsrc_arn));

        auto outcome = iam.CreatePolicy(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Error creating policy " << policy_name << ": " <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully created policy " << policy_name <<
                std::endl;
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}
/*
 * Show current event status
 */
void Engine::ShowEventStatus()
{
  EnableUI(false);
  service_->Events().FetchAll([this](gpg::EventManager::FetchAllResponse const &response)
                              {
    if (IsSuccess(response.status))
    {
      ndk_helper::JNIHelper::GetInstance()->RunOnUiThread([this,response]() {
        LOGI("Showing event status");
        if (dialog_)
          delete dialog_;

        dialog_ = new jui_helper::JUIDialog(app_->activity);

        std::ostringstream str;
        auto begin = response.data.begin();
        auto end = response.data.end();
        while( begin != end)
        {
          str <<begin->second.Name() << ": " << begin->second.Count() << "\n";
          begin++;
        }

        // Setting up message
        jui_helper::JUITextView* text = new jui_helper::JUITextView(
            str.str().c_str());

        text->AddRule(jui_helper::LAYOUT_PARAMETER_ALIGN_PARENT_TOP,
                              jui_helper::LAYOUT_PARAMETER_TRUE);
        text->AddRule(jui_helper::LAYOUT_PARAMETER_CENTER_IN_PARENT,
                              jui_helper::LAYOUT_PARAMETER_TRUE);
        text->SetAttribute("TextSize", jui_helper::ATTRIBUTE_UNIT_SP, 18.f);

        // OK Button
        jui_helper::JUIButton *button = new jui_helper::JUIButton("OK");
        button->SetCallback(
            [this](jui_helper::JUIView * view, const int32_t message) {
          switch (message) {
          case jui_helper::JUICALLBACK_BUTTON_UP: {
            dialog_->Close();
          }
          }
        });
        button->AddRule(jui_helper::LAYOUT_PARAMETER_CENTER_IN_PARENT,
                        jui_helper::LAYOUT_PARAMETER_TRUE);
        button->AddRule(jui_helper::LAYOUT_PARAMETER_BELOW, text);

        dialog_->SetCallback(
            jui_helper::JUICALLBACK_DIALOG_CANCELLED,
            [this](jui_helper::JUIDialog * dialog, const int32_t message) {
          LOGI("Dialog cancelled");
          dialog_->Close();
          EnableUI(true);
        });
        dialog_->SetCallback(
            jui_helper::JUICALLBACK_DIALOG_DISMISSED,
            [this](jui_helper::JUIDialog * dialog, const int32_t message) {
          LOGI("Dialog dismissed");
          dialog_->Close();
          EnableUI(true);
        });

        dialog_->SetAttribute("Title", "Event status");
        dialog_->AddView(text);
        dialog_->AddView(button);
        dialog_->Show();
        LOGI("Showing dialog");
      });

    }
    else
      EnableUI(true);
  });
}
status_t
AbstractSingleFileServerProcess::RunInternal()
{
	if (Logger::IsInfoEnabled())
		printf("[%s] will fetch data\n", Name());

	BPath localPath;
	status_t result = GetLocalPath(localPath);

	if (result != B_OK)
		return result;

	BString urlPathComponent = UrlPathComponent();

	if (IsSuccess(result) && HasOption(SERVER_PROCESS_DROP_CACHE))
		result = DeleteLocalFile(localPath);

	bool hasData = false;
	off_t size;

	if (IsSuccess(result))
		result = StorageUtils::ExistsObject(localPath, &hasData, NULL, &size);

	hasData = hasData && size > 0;

	if (IsSuccess(result) && ShouldAttemptNetworkDownload(hasData)) {
		result = DownloadToLocalFileAtomically(
			localPath,
			ServerSettings::CreateFullUrl(urlPathComponent));

		if (!IsSuccess(result)) {
			if (hasData) {
				printf("[%s] failed to update data, but have old data "
					"anyway so carry on with that\n", Name());
				result = B_OK;
			} else {
				printf("[%s] failed to obtain data\n", Name());
			}
		} else {
			if (Logger::IsInfoEnabled())
				printf("[%s] did fetch data\n", Name());
		}
	}

	if (IsSuccess(result)) {
		status_t hasDataResult = StorageUtils::ExistsObject(
			localPath, &hasData, NULL, &size);

		hasData = hasData && size > 0;

		if (hasDataResult == B_OK && !hasData)
			result = HD_ERR_NO_DATA;
	}

	if (IsSuccess(result)) {
		printf("[%s] will process data\n", Name());
		result = ProcessLocalData();

		switch (result) {
			case B_OK:
				printf("[%s] did process data\n", Name());
				break;
			default:
				MoveDamagedFileAside(localPath);
				break;
		}
	}

	return result;
}