使用 CloudTrail 處理程式庫 - AWS CloudTrail

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 CloudTrail 處理程式庫

CloudTrail Processing Library 是 Java 程式庫,提供簡單的 AWS CloudTrail 日誌處理方式。您可以提供有關佇列的 CloudTrail SQS組態詳細資訊,並編寫程式碼來處理事件。 CloudTrail Processing Library 會執行其餘動作。它會輪詢您的 Amazon SQS佇列、讀取和剖析佇列訊息、下載 CloudTrail 日誌檔案、剖析日誌檔案中的事件,以及將事件做為 Java 物件傳遞到您的程式碼。

CloudTrail Processing Library 具有高度可擴展性和容錯能力。它會處理日誌檔案的平行處理,讓您可以處理所需數目的日誌。它會處理與網路逾時和無法存取資源相關的網路失敗。

下列主題說明如何使用 CloudTrail 處理程式庫來處理 Java 專案中的 CloudTrail 日誌。

該程式庫以 Apache 授權的開放原始碼專案的形式提供,可在下列位置取得 GitHub:https://github.com/aws/aws-cloudtrail-processing-library。此程式庫來源包括可用作您自己專案基礎的範本程式碼。

最低需求

若要使用 CloudTrail 處理程式庫,您必須具備下列項目:

處理 CloudTrail 日誌

若要在 Java 應用程式中處理 CloudTrail 日誌:

將 CloudTrail 處理程式庫新增至您的專案

若要使用 CloudTrail Processing Library,請將它新增至 Java 專案的 classpath。

將程式庫新增至 Apache Ant 專案

將 CloudTrail 處理程式庫新增至 Apache Ant 專案
  1. 從下列位置下載或複製 CloudTrail 處理程式庫原始碼 GitHub:

  2. 從來源建置 .jar 檔案,如 所述README

    mvn clean install -Dgpg.skip=true
  3. 將產生的 .jar 檔案複製至您的專案,並將它新增至您專案的 build.xml 檔案。例如:

    <classpath> <pathelement path="${classpath}"/> <pathelement location="lib/aws-cloudtrail-processing-library-1.6.1.jar"/> </classpath>

將程式庫新增至 Apache Maven 專案

CloudTrail Processing Library 適用於 Apache Maven。您可以將它新增至專案,方法是在專案的 pom.xml 檔案中編寫單一相依性。

將 CloudTrail Processing Library 新增至 Maven 專案
  • 開啟 Maven 專案的 pom.xml 檔案,並新增下列相依性:

    <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-cloudtrail-processing-library</artifactId> <version>1.6.1</version> </dependency>

將程式庫新增至 Eclipse 專案

將 CloudTrail Processing Library 新增至 Eclipse 專案
  1. 從下列位置下載或複製 CloudTrail 處理程式庫原始碼 GitHub:

  2. 從來源建置 .jar 檔案,如 所述README

    mvn clean install -Dgpg.skip=true
  3. 將 built aws-cloudtrail-processing-library-1.6.1.jar 複製到專案中的目錄 (通常是 lib)。

  4. 在 Eclipse Project Explorer (專案瀏覽器) 中,以滑鼠右鍵按一下您專案的名稱,並選擇 Build Path (建置路徑),然後選擇 Configure (設定)

  5. Java Build Path (Java 建置路徑) 視窗中,選擇 Libraries (程式庫) 索引標籤。

  6. 選擇新增 JARs... 並導覽至您複製 aws-cloudtrail-processing-library-1.6.1.jar 的路徑。

  7. 選擇 OK (確定) 完成將 .jar 新增至您的專案。

將程式庫新增至 IntelliJ 專案

將 CloudTrail 處理程式庫新增至 IntelliJ 專案
  1. 從下列位置下載或複製 CloudTrail 處理程式庫原始碼 GitHub:

  2. 從來源建置 .jar 檔案,如 所述README

    mvn clean install -Dgpg.skip=true
  3. File (檔案) 中,選擇 Project Structure (專案結構)。

  4. 選擇 Modules (模組),然後選擇 Dependencies (相依性)。

  5. 選擇 + JARS或目錄,然後前往您建置 的路徑aws-cloudtrail-processing-library-1.6.1.jar

  6. 選擇 Apply (套用),然後選擇 OK (確定) 完成將 .jar 新增至您的專案。

設定 CloudTrail 處理程式庫

您可以透過建立在執行時間載入的 classpath 屬性檔案,或手動建立ClientConfiguration物件和設定選項來設定 CloudTrail 處理程式庫。

提供屬性檔案

您可以編寫 classpath 屬性檔案,以將組態選項提供給您的應用程式。下列範例檔案顯示您可設定的選項:

# AWS access key. (Required) accessKey = your_access_key # AWS secret key. (Required) secretKey = your_secret_key # The SQS URL used to pull CloudTrail notification from. (Required) sqsUrl = your_sqs_queue_url # The SQS end point specific to a region. sqsRegion = us-east-1 # A period of time during which Amazon SQS prevents other consuming components # from receiving and processing that message. visibilityTimeout = 60 # The S3 region to use. s3Region = us-east-1 # Number of threads used to download S3 files in parallel. Callbacks can be # invoked from any thread. threadCount = 1 # The time allowed, in seconds, for threads to shut down after # AWSCloudTrailEventProcessingExecutor.stop() is called. If they are still # running beyond this time, they will be forcibly terminated. threadTerminationDelaySeconds = 60 # The maximum number of AWSCloudTrailClientEvents sent to a single invocation # of processEvents(). maxEventsPerEmit = 10 # Whether to include raw event information in CloudTrailDeliveryInfo. enableRawEventInfo = false # Whether to delete SQS message when the CloudTrail Processing Library is unable to process the notification. deleteMessageUponFailure = false

下列是必要參數:

  • sqsUrl – 提供要URL從中提取 CloudTrail通知的 。如果您未指定此值,則 AWSCloudTrailProcessingExecutor 會擲出 IllegalStateException

  • accessKey – 您帳戶的唯一識別符,例如 AKIAIOSFODNN7EXAMPLE.

  • secretKey – 您帳戶的唯一識別符,例如 wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY.

accessKeysecretKey 參數會將您的 AWS 登入資料提供給程式庫,讓程式庫可以 AWS 代表您存取 。

其他參數的預設值是透過程式庫所設定。如需詳細資訊,請參閱 AWS CloudTrail Processing Library 參考

建立 ClientConfiguration

您可以初始化和設定 AWSCloudTrailProcessingExecutor 物件的選項,以將選項提供給 ClientConfiguration,而不是在 classpath 屬性中設定選項,如下列範例所示:

ClientConfiguration basicConfig = new ClientConfiguration( "http://sqs.us-east-1.amazonaws.com/123456789012/queue2", new DefaultAWSCredentialsProviderChain()); basicConfig.setEnableRawEventInfo(true); basicConfig.setThreadCount(4); basicConfig.setnEventsPerEmit(20);

實作事件處理器

若要處理 CloudTrail 日誌,您必須實作EventsProcessor接收 CloudTrail 日誌資料的 。下列是範例實作:

public class SampleEventsProcessor implements EventsProcessor { public void process(List<CloudTrailEvent> events) { int i = 0; for (CloudTrailEvent event : events) { System.out.println(String.format("Process event %d : %s", i++, event.getEventData())); } } }

實作 時EventsProcessor,您會實作 AWSCloudTrailProcessingExecutor用來傳送 CloudTrail 事件給您的回process()呼。事件是以 CloudTrailClientEvent 物件清單形式提供。

CloudTrailClientEvent 物件提供 CloudTrailEvent和 ,您可以使用CloudTrailEventMetadata它來讀取 CloudTrail 事件和交付資訊。

此簡單範例會列印每個傳遞至 SampleEventsProcessor 之事件的事件資訊。在您自己的實作中,您可以在符合您需求時處理日誌。AWSCloudTrailProcessingExecutor 只要有要傳送的事件且仍在執行,就會持續將事件傳送至 EventsProcessor

實例化和執行處理執行器

撰寫EventsProcessor並設定 CloudTrail 處理程式庫的組態值 (在 屬性檔案中或使用 ClientConfiguration類別) 之後,您可以使用這些元素來初始化和使用 AWSCloudTrailProcessingExecutor

使用 AWSCloudTrailProcessingExecutor處理 CloudTrail 事件
  1. 實例化 AWSCloudTrailProcessingExecutor.Builder 物件。Builder 的建構函數採用 EventsProcessor 物件和 classpath 屬性檔案名稱。

  2. 呼叫 Builderbuild() 原廠方法來設定和取得 AWSCloudTrailProcessingExecutor 物件。

  3. 使用 AWSCloudTrailProcessingExecutorstart()stop()方法來開始和結束 CloudTrail 事件處理。

public class SampleApp { public static void main(String[] args) throws InterruptedException { AWSCloudTrailProcessingExecutor executor = new AWSCloudTrailProcessingExecutor.Builder(new SampleEventsProcessor(), "/myproject/cloudtrailprocessing.properties").build(); executor.start(); Thread.sleep(24 * 60 * 60 * 1000); // let it run for a while (optional) executor.stop(); // optional } }

進階主題

篩選要處理的事件

根據預設,Amazon SQS佇列 S3 儲存貯體中的所有日誌,以及其中包含的所有事件都會傳送至您的 EventsProcessor。 CloudTrail Processing Library 提供選用介面,您可以實作這些介面來篩選用於取得 CloudTrail 日誌的來源,以及篩選您有興趣處理的事件。

SourceFilter

您可以實作 SourceFilter 界面,選擇是否要處理所提供來源的日誌。SourceFilter 會宣告可接收 CloudTrailSource 物件的單一回呼方法 filterSource()。若要持續處理來源中的事件,請從 false 傳回 filterSource()

CloudTrail 處理程式庫會在程式庫輪詢 Amazon SQS佇列上的日誌之後呼叫 filterSource()方法。這發生在程式庫啟動日誌的事件篩選或處理之前。

下列是範例實作:

public class SampleSourceFilter implements SourceFilter{ private static final int MAX_RECEIVED_COUNT = 3; private static List<String> accountIDs ; static { accountIDs = new ArrayList<>(); accountIDs.add("123456789012"); accountIDs.add("234567890123"); } @Override public boolean filterSource(CloudTrailSource source) throws CallbackException { source = (SQSBasedSource) source; Map<String, String> sourceAttributes = source.getSourceAttributes(); String accountId = sourceAttributes.get( SourceAttributeKeys.ACCOUNT_ID.getAttributeKey()); String receivedCount = sourceAttributes.get( SourceAttributeKeys.APPROXIMATE_RECEIVE_COUNT.getAttributeKey()); int approximateReceivedCount = Integer.parseInt(receivedCount); return approximateReceivedCount <= MAX_RECEIVED_COUNT && accountIDs.contains(accountId); } }

如果您未提供自己的 SourceFilter,則會使用 DefaultSourceFilter,以允許處理所有來源 (一律會傳回 true)。

EventFilter

您可以實作 EventFilter 界面,選擇是否要將 CloudTrail 事件傳送給您的 EventsProcessorEventFilter 會宣告可接收 filterEvent() 物件的單一回呼方法 CloudTrailEvent。若要持續處理事件,請從 false 傳回 filterEvent()

CloudTrail 處理程式庫會在程式庫輪詢 Amazon SQS佇列上的日誌,以及來源篩選之後呼叫 filterEvent()方法。這發生在程式庫啟動日誌的事件處理之前。

請參閱下列範例實作:

public class SampleEventFilter implements EventFilter{ private static final String EC2_EVENTS = "ec2.amazonaws.com"; @Override public boolean filterEvent(CloudTrailClientEvent clientEvent) throws CallbackException { CloudTrailEvent event = clientEvent.getEvent(); String eventSource = event.getEventSource(); String eventName = event.getEventName(); return eventSource.equals(EC2_EVENTS) && eventName.startsWith("Delete"); } }

如果您未提供自己的 EventFilter,則會使用 DefaultEventFilter,以允許處理所有事件 (一律會傳回 true)。

處理資料事件

CloudTrail 處理資料事件時,它會以原始格式保留數字,無論是整數 (int) 還是 float(包含小數的數字)。在資料事件欄位中具有整數的事件中, CloudTrail 歷史上會將這些數字處理為浮點數。目前, 會保留其原始格式,以 CloudTrail 處理這些欄位中的數字。

最佳實務是,為了避免中斷自動化,請靈活運用您用來處理或篩選 CloudTrail 資料事件的任何程式碼或自動化,並允許 intfloat 格式的數字。為了獲得最佳結果,請使用 1.4.0 版或更新版本的 CloudTrail 處理程式庫。

下列範例片段顯示 float 格式化的數字,2.0,適用於資料事件的 ResponseParameters 區塊中的 desiredCount 參數。

"eventName": "CreateService", "awsRegion": "us-east-1", "sourceIPAddress": "000.00.00.00", "userAgent": "console.amazonaws.com", "requestParameters": { "clientToken": "EXAMPLE", "cluster": "default", "desiredCount": 2.0 ...

下列範例片段顯示 int 格式化的數字,2,適用於資料事件的 ResponseParameters 區塊中的 desiredCount 參數。

"eventName": "CreateService", "awsRegion": "us-east-1", "sourceIPAddress": "000.00.00.00", "userAgent": "console.amazonaws.com", "requestParameters": { "clientToken": "EXAMPLE", "cluster": "default", "desiredCount": 2 ...

報告進度

實作ProgressReporter界面來自訂 CloudTrail 處理程式庫進度的報告。 ProgressReporter宣告兩種方法: reportStart()reportEnd(),在下列操作的開頭和結尾呼叫:

  • 從 Amazon 輪詢訊息 SQS

  • 從 Amazon 剖析訊息 SQS

  • 處理 CloudTrail 日誌的 Amazon SQS來源

  • 從 Amazon 刪除訊息 SQS

  • 下載 CloudTrail 日誌檔案

  • 處理 CloudTrail 日誌檔案

兩種方法都會收到 ProgressStatus 物件,其中包含所執行操作的資訊。progressState 成員擁有可識別目前操作之 ProgressState 列舉的成員。這個成員可以在 progressInfo 成員中包含其他資訊。此外,您從 reportStart() 傳回的任何物件都會傳遞至 reportEnd(),因此您可以提供內容資訊 (例如開始處理事件的時間)。

下列範例實作提供操作需要多久時間才能完成的資訊:

public class SampleProgressReporter implements ProgressReporter { private static final Log logger = LogFactory.getLog(DefaultProgressReporter.class); @Override public Object reportStart(ProgressStatus status) { return new Date(); } @Override public void reportEnd(ProgressStatus status, Object startDate) { System.out.println(status.getProgressState().toString() + " is " + status.getProgressInfo().isSuccess() + " , and latency is " + Math.abs(((Date) startDate).getTime()-new Date().getTime()) + " milliseconds."); } }

如果您未實作自己的 ProgressReporter,則會改用 DefaultExceptionHandler,以列印所執行狀態的名稱。

處理錯誤

ExceptionHandler 界面可讓您在日誌處理期間發生例外狀況時提供特殊處理。ExceptionHandler 宣告單一回呼方法 handleException(),以接收包含所發生例外狀況之內容的 ProcessingLibraryException 物件。

您可以使用傳入之 ProcessingLibraryExceptiongetStatus() 方法,了解發生例外狀況時所執行的操作,並取得操作狀態的其他資訊。ProcessingLibraryException 衍生自 Java 的標準 Exception 類別,因此您也可以呼叫任何例外狀況方法來擷取例外狀況的資訊。

請參閱下列範例實作:

public class SampleExceptionHandler implements ExceptionHandler{ private static final Log logger = LogFactory.getLog(DefaultProgressReporter.class); @Override public void handleException(ProcessingLibraryException exception) { ProgressStatus status = exception.getStatus(); ProgressState state = status.getProgressState(); ProgressInfo info = status.getProgressInfo(); System.err.println(String.format( "Exception. Progress State: %s. Progress Information: %s.", state, info)); } }

如果您未提供自己的 ExceptionHandler,則會改用 DefaultExceptionHandler,以列印標準錯誤訊息。

注意

如果 deleteMessageUponFailure 參數為 true, CloudTrail 處理程式庫不會區分一般例外狀況與處理錯誤,而且可能會刪除佇列訊息。

  1. 例如,您使用 SourceFilter,依時間戳記來篩選訊息。

  2. 不過,您沒有存取接收 CloudTrail 日誌檔案之 S3 儲存貯體所需的許可。因為您沒有必要許可,所以會擲回 AmazonServiceException。 CloudTrail Processing Library 將此包裝在 中CallBackException

  3. DefaultExceptionHandler 會將這個項目記錄為錯誤,但不會識別根本原因,即您沒有必要許可。Processing CloudTrail Library 會將此視為處理錯誤,並刪除訊息,即使訊息包含有效的 CloudTrail 日誌檔案。

如果您想要使用 SourceFilter 來篩選訊息,則請驗證 ExceptionHandler 可以區分服務例外狀況與處理錯誤。

其他資源

如需 CloudTrail 處理程式庫的詳細資訊,請參閱以下內容: