

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Monitoraggio di flussi di attività di database
<a name="DBActivityStreams.Monitoring"></a>

I flussi di attività di database monitorano e segnalano le attività. Il flusso di attività viene raccolto e trasmesso a Amazon Kinesis. Da Kinesis, è possibile monitorare il flusso di attività oppure altri servizi e applicazioni possono utilizzare il flusso di attività per ulteriori analisi. È possibile trovare il nome del flusso Kinesis sottostante utilizzando il comando della AWS CLI `describe-db-instances` o l'operazione `DescribeDBInstances` dell'API RDS.

Amazon RDS gestisce il flusso Kinesis per tuo conto come segue:
+ Amazon RDS crea automaticamente il flusso Kinesis con un periodo di conservazione di 24 ore. 
+  Amazon RDS dimensiona il flusso Kinesis, se necessario. 
+  Se si interrompe il flusso di attività del database o si elimina l'istanza database, Amazon RDS elimina il flusso Kinesis. 

Le seguenti categorie di attività vengono monitorate e inserite nel log di controllo del flusso di attività:
+ **Comandi SQL**: tutti i comandi SQL sono controllati e anche le istruzioni preparate, le funzioni integrate e le funzioni in PL/SQL Le chiamate alle procedure archiviate vengono controllate. Vengono inoltre controllate tutte le istruzioni SQL rilasciate all'interno di procedure o funzioni archiviate.
+ **Altre informazioni di database** – L'attività monitorata include l'istruzione SQL completa, il conteggio righe delle righe interessate da comandi DML, gli oggetti ai quali si accede e il nome del database univoco. I flussi di attività del database monitorano anche le variabili di bind e i parametri della stored procedure. 
**Importante**  
Il testo SQL completo di ogni istruzione è visibile nel registro di controllo del flusso di attività, inclusi eventuali dati sensibili. Tuttavia, le password degli utenti del database vengono omesse se Oracle può stabilirle dal contesto, come nell'istruzione SQL seguente.   

  ```
  ALTER ROLE role-name WITH password
  ```
+ **Informazioni di connessione** – L'attività monitorata include informazioni di sessione e di rete, l'ID di processo del server e i codici di uscita.

Se un flusso di attività restituisce un errore durante il monitoraggio dell'istanza database, riceverai una notifica mediante eventi RDS.

Nelle sezioni seguenti puoi accedere ai flussi di attività del database, eseguirne l’audit ed elaborarli.

**Topics**
+ [Accesso a un flusso di attività da Amazon Kinesis](DBActivityStreams.KinesisAccess.md)
+ [Contenuto ed esempi di log di audit per i flussi di attività del database](DBActivityStreams.AuditLog.md)
+ [Array JSON databaseActivityEventList per flussi di attività del database](DBActivityStreams.AuditLog.databaseActivityEventList.md)
+ [Elaborazione di un flusso di attività del database utilizzando l'SDK AWS](DBActivityStreams.CodeExample.md)

# Accesso a un flusso di attività da Amazon Kinesis
<a name="DBActivityStreams.KinesisAccess"></a>

Quando abiliti un flusso di attività per un database, viene creato automaticamente un flusso Kinesis. Da Kinesis, puoi monitorare l'attività del database in tempo reale. Per analizzare ulteriormente l'attività del database, puoi connettere il flusso Kinesis ad applicazioni consumer. È inoltre possibile connettere il flusso alle applicazioni di gestione della conformità, ad esempio Security Guardium IBM o SecureSphere Database Audit and Protection Imperva.

Puoi accedere al tuo flusso Kinesis dalla console RDS o dalla console Kinesis.

**Come accedere a un flusso di attività da Kinesis utilizzando la console RDS**

1. Apri la console Amazon RDS all'indirizzo [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/).

1. Nel riquadro di navigazione, scegliere **Databases (Database)**.

1. Seleziona l'istanza database Amazon RDS in cui hai avviato un flusso di attività.

1. Scegliere **Configuration (Configurazione)**.

1. In **Database activity stream** (Flusso di attività del database), scegli il collegamento sotto **Kinesis stream** (Flusso Kinesis).

1. Nella console Kinesis, scegli **Monitoring** (Monitoraggio) per iniziare l'osservazione dell'attività del database.

**Per accedere a un flusso di attività da Kinesis utilizzando la console Kinesis**

1. Aprire la console Kinesis all'indirizzo [https://console.aws.amazon.com/kinesis](https://console.aws.amazon.com/kinesis).

1. Scegliere il flusso di attività dall'elenco di flussi Kinesis.

   Il nome di un flusso di attività include il prefisso `aws-rds-das-db-` seguito dall'ID risorsa del database. Di seguito è riportato un esempio. 

   ```
   aws-rds-das-db-NHVOV4PCLWHGF52NP
   ```

   Per utilizzare la console Amazon RDS per trovare l'ID risorsa per il database, scegli l'istanza database dall'elenco di database, quindi seleziona la scheda **Configuration (Configurazione)**.

   Per utilizzare la AWS CLI per trovare il nome del flusso Kinesis completo per un flusso di attività, utilizzare una richiesta CLI [describe-db-instances](https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html) e prendere nota del valore di `ActivityStreamKinesisStreamName` nella risposta.

1. Scegliere **Monitoring (Monitoraggio)** per iniziare l'osservazione dell'attività di database.

Per ulteriori informazioni sull'utilizzo di Amazon Kinesis, consulta [Che cos'è Amazon Kinesis Data Streams?](https://docs.aws.amazon.com/streams/latest/dev/introduction.html).

# Contenuto ed esempi di log di audit per i flussi di attività del database
<a name="DBActivityStreams.AuditLog"></a>

Gli eventi monitorati sono rappresentati nel flusso di attività del database come stringhe JSON. La struttura è costituita da un oggetto JSON contenente un `DatabaseActivityMonitoringRecord`, che a sua volta contiene un array `databaseActivityEventList` di eventi attività. 

**Nota**  
Per i flussi di attività del database, l’array JSON `paramList` non include valori null dalle applicazioni Hibernate.

**Topics**
+ [Esempi di log di verifica per un flusso di attività](#DBActivityStreams.AuditLog.Examples)
+ [DatabaseActivityMonitoringRecords Oggetto JSON](#DBActivityStreams.AuditLog.DatabaseActivityMonitoringRecords)
+ [databaseActivityEvents Oggetto JSON](#DBActivityStreams.AuditLog.databaseActivityEvents)

## Esempi di log di verifica per un flusso di attività
<a name="DBActivityStreams.AuditLog.Examples"></a>

Di seguito sono riportati registri di controllo JSON decrittografati di esempio di record di eventi attività.

**Example Registrazione degli eventi di attività di**  
Il seguente record di evento di attività mostra un accesso con l'utilizzo di un'istruzione SQL `CONNECT` (`command`) mediante un client JDBC Thin (`clientApplication`) per il database Oracle.  

```
{
    "class": "Standard",
    "clientApplication": "JDBC Thin Client",
    "command": "LOGON",
    "commandText": null,
    "dbid": "0123456789",
    "databaseName": "ORCL",
    "dbProtocol": "oracle",
    "dbUserName": "TEST",
    "endTime": null,
    "errorMessage": null,
    "exitCode": 0,
    "logTime": "2021-01-15 00:15:36.233787",
    "netProtocol": "tcp",
    "objectName": null,
    "objectType": null,
    "paramList": [],
    "pid": 17904,
    "remoteHost": "123.456.789.012",
    "remotePort": "25440",
    "rowCount": null,
    "serverHost": "987.654.321.098",
    "serverType": "oracle",
    "serverVersion": "19.0.0.0.ru-2020-01.rur-2020-01.r1.EE.3",
    "serviceName": "oracle-ee",
    "sessionId": 987654321,
    "startTime": null,
    "statementId": 1,
    "substatementId": null,
    "transactionId": "0000000000000000",
    "engineNativeAuditFields": {
        "UNIFIED_AUDIT_POLICIES": "TEST_POL_EVERYTHING",
        "FGA_POLICY_NAME": null,
        "DV_OBJECT_STATUS": null,
        "SYSTEM_PRIVILEGE_USED": "CREATE SESSION",
        "OLS_LABEL_COMPONENT_TYPE": null,
        "XS_SESSIONID": null,
        "ADDITIONAL_INFO": null,
        "INSTANCE_ID": 1,
        "DBID": 123456789
        "DV_COMMENT": null,
        "RMAN_SESSION_STAMP": null,
        "NEW_NAME": null,
        "DV_ACTION_NAME": null,
        "OLS_PROGRAM_UNIT_NAME": null,
        "OLS_STRING_LABEL": null,
        "RMAN_SESSION_RECID": null,
        "OBJECT_PRIVILEGES": null,
        "OLS_OLD_VALUE": null,
        "XS_TARGET_PRINCIPAL_NAME": null,
        "XS_NS_ATTRIBUTE": null,
        "XS_NS_NAME": null,
        "DBLINK_INFO": null,
        "AUTHENTICATION_TYPE": "(TYPE\u003d(DATABASE));(CLIENT ADDRESS\u003d((ADDRESS\u003d(PROTOCOL\u003dtcp)(HOST\u003d205.251.233.183)(PORT\u003d25440))));",
        "OBJECT_EDITION": null,
        "OLS_PRIVILEGES_GRANTED": null,
        "EXCLUDED_USER": null,
        "DV_ACTION_OBJECT_NAME": null,
        "OLS_LABEL_COMPONENT_NAME": null,
        "EXCLUDED_SCHEMA": null,
        "DP_TEXT_PARAMETERS1": null,
        "XS_USER_NAME": null,
        "XS_ENABLED_ROLE": null,
        "XS_NS_ATTRIBUTE_NEW_VAL": null,
        "DIRECT_PATH_NUM_COLUMNS_LOADED": null,
        "AUDIT_OPTION": null,
        "DV_EXTENDED_ACTION_CODE": null,
        "XS_PACKAGE_NAME": null,
        "OLS_NEW_VALUE": null,
        "DV_RETURN_CODE": null,
        "XS_CALLBACK_EVENT_TYPE": null,
        "USERHOST": "a1b2c3d4e5f6.amazon.com",
        "GLOBAL_USERID": null,
        "CLIENT_IDENTIFIER": null,
        "RMAN_OPERATION": null,
        "TERMINAL": "unknown",
        "OS_USERNAME": "sumepate",
        "OLS_MAX_READ_LABEL": null,
        "XS_PROXY_USER_NAME": null,
        "XS_DATASEC_POLICY_NAME": null,
        "DV_FACTOR_CONTEXT": null,
        "OLS_MAX_WRITE_LABEL": null,
        "OLS_PARENT_GROUP_NAME": null,
        "EXCLUDED_OBJECT": null,
        "DV_RULE_SET_NAME": null,
        "EXTERNAL_USERID": null,
        "EXECUTION_ID": null,
        "ROLE": null,
        "PROXY_SESSIONID": 0,
        "DP_BOOLEAN_PARAMETERS1": null,
        "OLS_POLICY_NAME": null,
        "OLS_GRANTEE": null,
        "OLS_MIN_WRITE_LABEL": null,
        "APPLICATION_CONTEXTS": null,
        "XS_SCHEMA_NAME": null,
        "DV_GRANTEE": null,
        "XS_COOKIE": null,
        "DBPROXY_USERNAME": null,
        "DV_ACTION_CODE": null,
        "OLS_PRIVILEGES_USED": null,
        "RMAN_DEVICE_TYPE": null,
        "XS_NS_ATTRIBUTE_OLD_VAL": null,
        "TARGET_USER": null,
        "XS_ENTITY_TYPE": null,
        "ENTRY_ID": 1,
        "XS_PROCEDURE_NAME": null,
        "XS_INACTIVITY_TIMEOUT": null,
        "RMAN_OBJECT_TYPE": null,
        "SYSTEM_PRIVILEGE": null,
        "NEW_SCHEMA": null,
        "SCN": 5124715
    }
}
```
Il seguente record di evento di attività mostra un errore di accesso per il database SQL Server.  

```
{
    "type": "DatabaseActivityMonitoringRecord",
    "clusterId": "",
    "instanceId": "db-4JCWQLUZVFYP7DIWP6JVQ77O3Q",
    "databaseActivityEventList": [
        {
            "class": "LOGIN",
            "clientApplication": "Microsoft SQL Server Management Studio",
            "command": "LOGIN FAILED",
            "commandText": "Login failed for user 'test'. Reason: Password did not match that for the login provided. [CLIENT: local-machine]",
            "databaseName": "",
            "dbProtocol": "SQLSERVER",
            "dbUserName": "test",
            "endTime": null,
            "errorMessage": null,
            "exitCode": 0,
            "logTime": "2022-10-06 21:34:42.7113072+00",
            "netProtocol": null,
            "objectName": "",
            "objectType": "LOGIN",
            "paramList": null,
            "pid": null,
            "remoteHost": "local machine",
            "remotePort": null,
            "rowCount": 0,
            "serverHost": "172.31.30.159",
            "serverType": "SQLSERVER",
            "serverVersion": "15.00.4073.23.v1.R1",
            "serviceName": "sqlserver-ee",
            "sessionId": 0,
            "startTime": null,
            "statementId": "0x1eb0d1808d34a94b9d3dcf5432750f02",
            "substatementId": 1,
            "transactionId": "0",
            "type": "record",
            "engineNativeAuditFields": {
                "target_database_principal_id": 0,
                "target_server_principal_id": 0,
                "target_database_principal_name": "",
                "server_principal_id": 0,
                "user_defined_information": "",
                "response_rows": 0,
                "database_principal_name": "",
                "target_server_principal_name": "",
                "schema_name": "",
                "is_column_permission": false,
                "object_id": 0,
                "server_instance_name": "EC2AMAZ-NFUJJNO",
                "target_server_principal_sid": null,
                "additional_information": "<action_info "xmlns=\"http://schemas.microsoft.com/sqlserver/2008/sqlaudit_data\"><pooled_connection>0</pooled_connection><error>0x00004818</error><state>8</state><address>local machine</address><PasswordFirstNibbleHash>B</PasswordFirstNibbleHash></action_info>"-->,
                "duration_milliseconds": 0,
                "permission_bitmask": "0x00000000000000000000000000000000",
                "data_sensitivity_information": "",
                "session_server_principal_name": "",
                "connection_id": "98B4F537-0F82-49E3-AB08-B9D33B5893EF",
                "audit_schema_version": 1,
                "database_principal_id": 0,
                "server_principal_sid": null,
                "user_defined_event_id": 0,
                "host_name": "EC2AMAZ-NFUJJNO"
            }
        }
    ]
}
```
Se un flusso di attività del database non è abilitato, l'ultimo campo nel documento JSON è `"engineNativeAuditFields": { }`. 

**Example Record di evento attività di un'istruzione CREATE TABLE**  
Il seguente esempio mostra un evento `CREATE TABLE` per il database Oracle.  

```
{
    "class": "Standard",
    "clientApplication": "sqlplus@ip-12-34-5-678 (TNS V1-V3)",
    "command": "CREATE TABLE",
    "commandText": "CREATE TABLE persons(\n    person_id NUMBER GENERATED BY DEFAULT AS IDENTITY,\n    first_name VARCHAR2(50) NOT NULL,\n    last_name VARCHAR2(50) NOT NULL,\n    PRIMARY KEY(person_id)\n)",
    "dbid": "0123456789",
    "databaseName": "ORCL",
    "dbProtocol": "oracle",
    "dbUserName": "TEST",
    "endTime": null,
    "errorMessage": null,
    "exitCode": 0,
    "logTime": "2021-01-15 00:22:49.535239",
    "netProtocol": "beq",
    "objectName": "PERSONS",
    "objectType": "TEST",
    "paramList": [],
    "pid": 17687,
    "remoteHost": "123.456.789.0",
    "remotePort": null,
    "rowCount": null,
    "serverHost": "987.654.321.01",
    "serverType": "oracle",
    "serverVersion": "19.0.0.0.ru-2020-01.rur-2020-01.r1.EE.3",
    "serviceName": "oracle-ee",
    "sessionId": 1234567890,
    "startTime": null,
    "statementId": 43,
    "substatementId": null,
    "transactionId": "090011007F0D0000",
    "engineNativeAuditFields": {
        "UNIFIED_AUDIT_POLICIES": "TEST_POL_EVERYTHING",
        "FGA_POLICY_NAME": null,
        "DV_OBJECT_STATUS": null,
        "SYSTEM_PRIVILEGE_USED": "CREATE SEQUENCE, CREATE TABLE",
        "OLS_LABEL_COMPONENT_TYPE": null,
        "XS_SESSIONID": null,
        "ADDITIONAL_INFO": null,
        "INSTANCE_ID": 1,
        "DV_COMMENT": null,
        "RMAN_SESSION_STAMP": null,
        "NEW_NAME": null,
        "DV_ACTION_NAME": null,
        "OLS_PROGRAM_UNIT_NAME": null,
        "OLS_STRING_LABEL": null,
        "RMAN_SESSION_RECID": null,
        "OBJECT_PRIVILEGES": null,
        "OLS_OLD_VALUE": null,
        "XS_TARGET_PRINCIPAL_NAME": null,
        "XS_NS_ATTRIBUTE": null,
        "XS_NS_NAME": null,
        "DBLINK_INFO": null,
        "AUTHENTICATION_TYPE": "(TYPE\u003d(DATABASE));(CLIENT ADDRESS\u003d((PROTOCOL\u003dbeq)(HOST\u003d123.456.789.0)));",
        "OBJECT_EDITION": null,
        "OLS_PRIVILEGES_GRANTED": null,
        "EXCLUDED_USER": null,
        "DV_ACTION_OBJECT_NAME": null,
        "OLS_LABEL_COMPONENT_NAME": null,
        "EXCLUDED_SCHEMA": null,
        "DP_TEXT_PARAMETERS1": null,
        "XS_USER_NAME": null,
        "XS_ENABLED_ROLE": null,
        "XS_NS_ATTRIBUTE_NEW_VAL": null,
        "DIRECT_PATH_NUM_COLUMNS_LOADED": null,
        "AUDIT_OPTION": null,
        "DV_EXTENDED_ACTION_CODE": null,
        "XS_PACKAGE_NAME": null,
        "OLS_NEW_VALUE": null,
        "DV_RETURN_CODE": null,
        "XS_CALLBACK_EVENT_TYPE": null,
        "USERHOST": "ip-10-13-0-122",
        "GLOBAL_USERID": null,
        "CLIENT_IDENTIFIER": null,
        "RMAN_OPERATION": null,
        "TERMINAL": "pts/1",
        "OS_USERNAME": "rdsdb",
        "OLS_MAX_READ_LABEL": null,
        "XS_PROXY_USER_NAME": null,
        "XS_DATASEC_POLICY_NAME": null,
        "DV_FACTOR_CONTEXT": null,
        "OLS_MAX_WRITE_LABEL": null,
        "OLS_PARENT_GROUP_NAME": null,
        "EXCLUDED_OBJECT": null,
        "DV_RULE_SET_NAME": null,
        "EXTERNAL_USERID": null,
        "EXECUTION_ID": null,
        "ROLE": null,
        "PROXY_SESSIONID": 0,
        "DP_BOOLEAN_PARAMETERS1": null,
        "OLS_POLICY_NAME": null,
        "OLS_GRANTEE": null,
        "OLS_MIN_WRITE_LABEL": null,
        "APPLICATION_CONTEXTS": null,
        "XS_SCHEMA_NAME": null,
        "DV_GRANTEE": null,
        "XS_COOKIE": null,
        "DBPROXY_USERNAME": null,
        "DV_ACTION_CODE": null,
        "OLS_PRIVILEGES_USED": null,
        "RMAN_DEVICE_TYPE": null,
        "XS_NS_ATTRIBUTE_OLD_VAL": null,
        "TARGET_USER": null,
        "XS_ENTITY_TYPE": null,
        "ENTRY_ID": 12,
        "XS_PROCEDURE_NAME": null,
        "XS_INACTIVITY_TIMEOUT": null,
        "RMAN_OBJECT_TYPE": null,
        "SYSTEM_PRIVILEGE": null,
        "NEW_SCHEMA": null,
        "SCN": 5133083
    }
}
```
Il seguente esempio mostra un evento `CREATE TABLE` per il database SQL Server.  

```
{
    "type": "DatabaseActivityMonitoringRecord",
    "clusterId": "",
    "instanceId": "db-4JCWQLUZVFYP7DIWP6JVQ77O3Q",
    "databaseActivityEventList": [
        {
            "class": "SCHEMA",
            "clientApplication": "Microsoft SQL Server Management Studio - Query",
            "command": "ALTER",
            "commandText": "Create table [testDB].[dbo].[TestTable2](\r\ntextA varchar(6000),\r\n    textB varchar(6000)\r\n)",
            "databaseName": "testDB",
            "dbProtocol": "SQLSERVER",
            "dbUserName": "test",
            "endTime": null,
            "errorMessage": null,
            "exitCode": 1,
            "logTime": "2022-10-06 21:44:38.4120677+00",
            "netProtocol": null,
            "objectName": "dbo",
            "objectType": "SCHEMA",
            "paramList": null,
            "pid": null,
            "remoteHost": "local machine",
            "remotePort": null,
            "rowCount": 0,
            "serverHost": "172.31.30.159",
            "serverType": "SQLSERVER",
            "serverVersion": "15.00.4073.23.v1.R1",
            "serviceName": "sqlserver-ee",
            "sessionId": 84,
            "startTime": null,
            "statementId": "0x5178d33d56e95e419558b9607158a5bd",
            "substatementId": 1,
            "transactionId": "4561864",
            "type": "record",
            "engineNativeAuditFields": {
                "target_database_principal_id": 0,
                "target_server_principal_id": 0,
                "target_database_principal_name": "",
                "server_principal_id": 2,
                "user_defined_information": "",
                "response_rows": 0,
                "database_principal_name": "dbo",
                "target_server_principal_name": "",
                "schema_name": "",
                "is_column_permission": false,
                "object_id": 1,
                "server_instance_name": "EC2AMAZ-NFUJJNO",
                "target_server_principal_sid": null,
                "additional_information": "",
                "duration_milliseconds": 0,
                "permission_bitmask": "0x00000000000000000000000000000000",
                "data_sensitivity_information": "",
                "session_server_principal_name": "test",
                "connection_id": "EE1FE3FD-EF2C-41FD-AF45-9051E0CD983A",
                "audit_schema_version": 1,
                "database_principal_id": 1,
                "server_principal_sid": "0x010500000000000515000000bdc2795e2d0717901ba6998cf4010000",
                "user_defined_event_id": 0,
                "host_name": "EC2AMAZ-NFUJJNO"
            }
        }
    ]
}
```

**Example Record di evento attività di un'istruzione SELECT**  
Il seguente esempio mostra un evento `SELECT` per il database Oracle.  

```
{
    "class": "Standard",
    "clientApplication": "sqlplus@ip-12-34-5-678 (TNS V1-V3)",
    "command": "SELECT",
    "commandText": "select count(*) from persons",
    "databaseName": "1234567890",
    "dbProtocol": "oracle",
    "dbUserName": "TEST",
    "endTime": null,
    "errorMessage": null,
    "exitCode": 0,
    "logTime": "2021-01-15 00:25:18.850375",
    "netProtocol": "beq",
    "objectName": "PERSONS",
    "objectType": "TEST",
    "paramList": [],
    "pid": 17687,
    "remoteHost": "123.456.789.0",
    "remotePort": null,
    "rowCount": null,
    "serverHost": "987.654.321.09",
    "serverType": "oracle",
    "serverVersion": "19.0.0.0.ru-2020-01.rur-2020-01.r1.EE.3",
    "serviceName": "oracle-ee",
    "sessionId": 1080639707,
    "startTime": null,
    "statementId": 44,
    "substatementId": null,
    "transactionId": null,
    "engineNativeAuditFields": {
        "UNIFIED_AUDIT_POLICIES": "TEST_POL_EVERYTHING",
        "FGA_POLICY_NAME": null,
        "DV_OBJECT_STATUS": null,
        "SYSTEM_PRIVILEGE_USED": null,
        "OLS_LABEL_COMPONENT_TYPE": null,
        "XS_SESSIONID": null,
        "ADDITIONAL_INFO": null,
        "INSTANCE_ID": 1,
        "DV_COMMENT": null,
        "RMAN_SESSION_STAMP": null,
        "NEW_NAME": null,
        "DV_ACTION_NAME": null,
        "OLS_PROGRAM_UNIT_NAME": null,
        "OLS_STRING_LABEL": null,
        "RMAN_SESSION_RECID": null,
        "OBJECT_PRIVILEGES": null,
        "OLS_OLD_VALUE": null,
        "XS_TARGET_PRINCIPAL_NAME": null,
        "XS_NS_ATTRIBUTE": null,
        "XS_NS_NAME": null,
        "DBLINK_INFO": null,
        "AUTHENTICATION_TYPE": "(TYPE\u003d(DATABASE));(CLIENT ADDRESS\u003d((PROTOCOL\u003dbeq)(HOST\u003d123.456.789.0)));",
        "OBJECT_EDITION": null,
        "OLS_PRIVILEGES_GRANTED": null,
        "EXCLUDED_USER": null,
        "DV_ACTION_OBJECT_NAME": null,
        "OLS_LABEL_COMPONENT_NAME": null,
        "EXCLUDED_SCHEMA": null,
        "DP_TEXT_PARAMETERS1": null,
        "XS_USER_NAME": null,
        "XS_ENABLED_ROLE": null,
        "XS_NS_ATTRIBUTE_NEW_VAL": null,
        "DIRECT_PATH_NUM_COLUMNS_LOADED": null,
        "AUDIT_OPTION": null,
        "DV_EXTENDED_ACTION_CODE": null,
        "XS_PACKAGE_NAME": null,
        "OLS_NEW_VALUE": null,
        "DV_RETURN_CODE": null,
        "XS_CALLBACK_EVENT_TYPE": null,
        "USERHOST": "ip-12-34-5-678",
        "GLOBAL_USERID": null,
        "CLIENT_IDENTIFIER": null,
        "RMAN_OPERATION": null,
        "TERMINAL": "pts/1",
        "OS_USERNAME": "rdsdb",
        "OLS_MAX_READ_LABEL": null,
        "XS_PROXY_USER_NAME": null,
        "XS_DATASEC_POLICY_NAME": null,
        "DV_FACTOR_CONTEXT": null,
        "OLS_MAX_WRITE_LABEL": null,
        "OLS_PARENT_GROUP_NAME": null,
        "EXCLUDED_OBJECT": null,
        "DV_RULE_SET_NAME": null,
        "EXTERNAL_USERID": null,
        "EXECUTION_ID": null,
        "ROLE": null,
        "PROXY_SESSIONID": 0,
        "DP_BOOLEAN_PARAMETERS1": null,
        "OLS_POLICY_NAME": null,
        "OLS_GRANTEE": null,
        "OLS_MIN_WRITE_LABEL": null,
        "APPLICATION_CONTEXTS": null,
        "XS_SCHEMA_NAME": null,
        "DV_GRANTEE": null,
        "XS_COOKIE": null,
        "DBPROXY_USERNAME": null,
        "DV_ACTION_CODE": null,
        "OLS_PRIVILEGES_USED": null,
        "RMAN_DEVICE_TYPE": null,
        "XS_NS_ATTRIBUTE_OLD_VAL": null,
        "TARGET_USER": null,
        "XS_ENTITY_TYPE": null,
        "ENTRY_ID": 13,
        "XS_PROCEDURE_NAME": null,
        "XS_INACTIVITY_TIMEOUT": null,
        "RMAN_OBJECT_TYPE": null,
        "SYSTEM_PRIVILEGE": null,
        "NEW_SCHEMA": null,
        "SCN": 5136972
    }
}
```
Il seguente esempio mostra un evento `SELECT` per il database SQL Server.  

```
{
    "type": "DatabaseActivityMonitoringRecord",
    "clusterId": "",
    "instanceId": "db-4JCWQLUZVFYP7DIWP6JVQ77O3Q",
    "databaseActivityEventList": [
        {
            "class": "TABLE",
            "clientApplication": "Microsoft SQL Server Management Studio - Query",
            "command": "SELECT",
            "commandText": "select * from [testDB].[dbo].[TestTable]",
            "databaseName": "testDB",
            "dbProtocol": "SQLSERVER",
            "dbUserName": "test",
            "endTime": null,
            "errorMessage": null,
            "exitCode": 1,
            "logTime": "2022-10-06 21:24:59.9422268+00",
            "netProtocol": null,
            "objectName": "TestTable",
            "objectType": "TABLE",
            "paramList": null,
            "pid": null,
            "remoteHost": "local machine",
            "remotePort": null,
            "rowCount": 0,
            "serverHost": "172.31.30.159",
            "serverType": "SQLSERVER",
            "serverVersion": "15.00.4073.23.v1.R1",
            "serviceName": "sqlserver-ee",
            "sessionId": 62,
            "startTime": null,
            "statementId": "0x03baed90412f564fad640ebe51f89b99",
            "substatementId": 1,
            "transactionId": "4532935",
            "type": "record",
            "engineNativeAuditFields": {
                "target_database_principal_id": 0,
                "target_server_principal_id": 0,
                "target_database_principal_name": "",
                "server_principal_id": 2,
                "user_defined_information": "",
                "response_rows": 0,
                "database_principal_name": "dbo",
                "target_server_principal_name": "",
                "schema_name": "dbo",
                "is_column_permission": true,
                "object_id": 581577110,
                "server_instance_name": "EC2AMAZ-NFUJJNO",
                "target_server_principal_sid": null,
                "additional_information": "",
                "duration_milliseconds": 0,
                "permission_bitmask": "0x00000000000000000000000000000001",
                "data_sensitivity_information": "",
                "session_server_principal_name": "test",
                "connection_id": "AD3A5084-FB83-45C1-8334-E923459A8109",
                "audit_schema_version": 1,
                "database_principal_id": 1,
                "server_principal_sid": "0x010500000000000515000000bdc2795e2d0717901ba6998cf4010000",
                "user_defined_event_id": 0,
                "host_name": "EC2AMAZ-NFUJJNO"
            }
        }
    ]
}
```

## DatabaseActivityMonitoringRecords Oggetto JSON
<a name="DBActivityStreams.AuditLog.DatabaseActivityMonitoringRecords"></a>

I record di eventi dell'attività del database si trovano in un oggetto JSON che contiene le seguenti informazioni.


****  

| Campo JSON | Tipo di dati | Descrizione | 
| --- | --- | --- | 
|  `type`  | stringa |  Il tipo di record JSON. Il valore è `DatabaseActivityMonitoringRecords`.  | 
| version | stringa |  La versione dei record di monitoraggio delle attività del database. Oracle DB utilizza la versione 1.3 e SQL Server utilizza la versione 1.4. Queste versioni del motore introducono l'oggetto JSON engineNativeAuditFields.  | 
|  [databaseActivityEvents](#DBActivityStreams.AuditLog.databaseActivityEvents)  | stringa |  Un oggetto JSON contenente gli eventi di attività.  | 
| key | stringa | Una chiave di crittografia utilizzata per decrittare [Array JSON databaseActivityEventList](DBActivityStreams.AuditLog.databaseActivityEventList.md)  | 

## databaseActivityEvents Oggetto JSON
<a name="DBActivityStreams.AuditLog.databaseActivityEvents"></a>

L'oggetto JSON `databaseActivityEvents` contiene le seguenti informazioni.

### Campi di primo livello nel record JSON
<a name="DBActivityStreams.AuditLog.topLevel"></a>

 Ogni evento nel registro di controllo viene racchiuso in un record in formato JSON. Questo record contiene i seguenti campi. 

**type**  
 Questo campo ha sempre il valore `DatabaseActivityMonitoringRecords`. 

**versione**  
 Questo campo rappresenta la versione del protocollo o del contratto di dati del flusso di attività del database. Definisce quali campi sono disponibili.

**databaseActivityEvents**  
 Stringa crittografata che rappresenta uno o più eventi di attività. È rappresentato come un array di byte base64. Quando si decrittografa la stringa, il risultato è un record in formato JSON con campi come illustrato negli esempi di questa sezione.

**key**  
 Chiave dati crittografata utilizzata per crittografare la stringa `databaseActivityEvents`. È lo stesso AWS KMS key che hai fornito quando hai avviato il flusso di attività del database.

 Nell'esempio seguente viene illustrato il formato di questo record.

```
{
  "type":"DatabaseActivityMonitoringRecords",
  "version":"1.3",
  "databaseActivityEvents":"encrypted audit records",
  "key":"encrypted key"
}
```

```
           "type":"DatabaseActivityMonitoringRecords",
           "version":"1.4",
           "databaseActivityEvents":"encrypted audit records",
           "key":"encrypted key"
```

Per decrittografare il contenuto del campo `databaseActivityEvents`, procedere come segue:

1.  Decrittare il valore nel campo `key` JSON utilizzando la chiave KMS fornita all'avvio del flusso di attività del database. In questo modo viene restituita la chiave di crittografia dei dati in testo non crittografato. 

1.  Decodificare il valore nel campo `databaseActivityEvents` JSON con base64 per ottenere il testo cifrato, in formato binario, del payload di controllo. 

1.  Decifrare il testo cifrato binario con la chiave di crittografia dei dati decodificata nel primo passaggio. 

1.  Decomprimere il payload decrittografato. 
   +  Il payload crittografato è nel campo `databaseActivityEvents`. 
   +  Il campo `databaseActivityEventList` contiene una matrice di record di controllo. I campi `type` nella matrice possono essere `record` o `heartbeat`. 

Il record dell'evento attività registro di controllo è un oggetto JSON che contiene le seguenti informazioni.


****  

| Campo JSON | Tipo di dati | Descrizione | 
| --- | --- | --- | 
|  `type`  | stringa |  Il tipo di record JSON. Il valore è `DatabaseActivityMonitoringRecord`.  | 
| instanceId | stringa | Identificatore della risorsa istanza database. Corrisponde all'attributo di istanza database DbiResourceId. | 
|  [Array JSON databaseActivityEventList](DBActivityStreams.AuditLog.databaseActivityEventList.md)   | stringa |  Matrice di record di controllo delle attività o messaggi heartbeat.  | 

# Array JSON databaseActivityEventList per flussi di attività del database
<a name="DBActivityStreams.AuditLog.databaseActivityEventList"></a>

Il payload del registro di controllo è un array JSON `databaseActivityEventList` crittografato. La tabella riporta in ordine alfabetico i campi per ogni evento di attività nella matrice `DatabaseActivityEventList` decrittata di un log di verifica. 

Quando la verifica unificata è abilitata in Oracle Database, i record di verifica vengono popolati in questo nuovo percorso di verifica. La visualizzazione `UNIFIED_AUDIT_TRAIL` mostra i record di verifica in formato tabulare recuperando i record di verifica dal percorso di verifica. Quando si avvia un flusso di attività del database, una colonna in `UNIFIED_AUDIT_TRAIL` viene mappata a un campo nella matrice `databaseActivityEventList`.

**Importante**  
Tale struttura di eventi è soggetta a modifiche. Amazon RDS potrebbe aggiungere nuovi campi agli eventi di attività in futuro. Nelle applicazioni che analizzano i dati JSON, assicurarsi che il codice possa ignorare o eseguire le azioni appropriate per i nomi di campo sconosciuti. 

## Campi databaseActivityEventList per Amazon RDS for Oracle
<a name="DBActivityStreams.AuditLog.databaseActivityEventList.ro"></a>

Di seguito sono riportati i campi di `databaseActivityEventList` per Amazon RDS per Oracle.


| Campo | Tipo di dati | Origine | Descrizione | 
| --- | --- | --- | --- | 
|  `class`  |  stringa  |  Colonna `AUDIT_TYPE` in `UNIFIED_AUDIT_TRAIL`  |  La classe dell'evento attività. Questo corrisponde alla colonna `AUDIT_TYPE` nella visualizzazione `UNIFIED_AUDIT_TRAIL`. I valori validi per Amazon RDS for Oracle sono i seguenti: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/AmazonRDS/latest/UserGuide/DBActivityStreams.AuditLog.databaseActivityEventList.html) Per ulteriori informazioni, consulta [UNIFIED\$1AUDIT\$1TRAIL](https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/UNIFIED_AUDIT_TRAIL.html#GUID-B7CE1C02-2FD4-47D6-80AA-CF74A60CDD1D) nella documentazione di Oracle.  | 
|  `clientApplication`  |  stringa  |  `CLIENT_PROGRAM_NAME` in `UNIFIED_AUDIT_TRAIL`  |  L'applicazione utilizzata dal client per eseguire la connessione come segnalato dal client. Il client non deve fornire queste informazioni, pertanto il valore può essere nullo. Un valore di esempio è `JDBC Thin Client`.  | 
|  `command`  |  stringa  |  Colonna `ACTION_NAME` in `UNIFIED_AUDIT_TRAIL`  |  Nome dell'azione eseguita dall'utente. Per comprendere l'azione completa, leggere sia il nome del comando che il valore `AUDIT_TYPE`. Un valore di esempio è `ALTER DATABASE`.  | 
|  `commandText`  |  stringa  |  Colonna `SQL_TEXT` in `UNIFIED_AUDIT_TRAIL`  |  L'istruzione SQL associata all'evento. Un valore di esempio è `ALTER DATABASE BEGIN BACKUP`.  | 
|  `databaseName`  |  stringa  |  Colonna `NAME` in `V$DATABASE`  |  Nome del database.  | 
|  `dbid`  |  numero  |  Colonna `DBID` in `UNIFIED_AUDIT_TRAIL`  |  Identificatore numerico per il database. Un valore di esempio è `1559204751`.  | 
|  `dbProtocol`  |  stringa  |  N/A  |  Il protocollo di database. In questa beta, il valore è `oracle`.  | 
|  `dbUserName`  |  stringa  |  Colonna `DBUSERNAME` in `UNIFIED_AUDIT_TRAIL`  |  Il nome dell'utente del database le cui azioni sono state verificate. Un valore di esempio è `RDSADMIN`.  | 
|  `endTime`  |  stringa  |  N/A  |  Questo campo non viene utilizzato per RDS for Oracle ed è sempre null.  | 
|  `engineNativeAuditFields`  |  oggetto  |  `UNIFIED_AUDIT_TRAIL`  |  Per impostazione predefinita, è vuoto. Quando si avvia il flusso di attività con l'opzione `--engine-native-audit-fields-included`, questo oggetto include le seguenti colonne e i relativi valori: <pre>ADDITIONAL_INFO<br />APPLICATION_CONTEXTS<br />AUDIT_OPTION<br />AUTHENTICATION_TYPE<br />CLIENT_IDENTIFIER<br />CURRENT_USER<br />DBLINK_INFO<br />DBPROXY_USERNAME<br />DIRECT_PATH_NUM_COLUMNS_LOADED<br />DP_BOOLEAN_PARAMETERS1<br />DP_TEXT_PARAMETERS1<br />DV_ACTION_CODE<br />DV_ACTION_NAME<br />DV_ACTION_OBJECT_NAME<br />DV_COMMENT<br />DV_EXTENDED_ACTION_CODE<br />DV_FACTOR_CONTEXT<br />DV_GRANTEE<br />DV_OBJECT_STATUS<br />DV_RETURN_CODE<br />DV_RULE_SET_NAME<br />ENTRY_ID<br />EXCLUDED_OBJECT<br />EXCLUDED_SCHEMA<br />EXCLUDED_USER<br />EXECUTION_ID<br />EXTERNAL_USERID<br />FGA_POLICY_NAME<br />GLOBAL_USERID<br />INSTANCE_ID<br />KSACL_SERVICE_NAME<br />KSACL_SOURCE_LOCATION<br />KSACL_USER_NAME<br />NEW_NAME<br />NEW_SCHEMA<br />OBJECT_EDITION<br />OBJECT_PRIVILEGES<br />OLS_GRANTEE<br />OLS_LABEL_COMPONENT_NAME<br />OLS_LABEL_COMPONENT_TYPE<br />OLS_MAX_READ_LABEL<br />OLS_MAX_WRITE_LABEL<br />OLS_MIN_WRITE_LABEL<br />OLS_NEW_VALUE<br />OLS_OLD_VALUE<br />OLS_PARENT_GROUP_NAME<br />OLS_POLICY_NAME<br />OLS_PRIVILEGES_GRANTED<br />OLS_PRIVILEGES_USED<br />OLS_PROGRAM_UNIT_NAME<br />OLS_STRING_LABEL<br />OS_USERNAME<br />PROTOCOL_ACTION_NAME<br />PROTOCOL_MESSAGE<br />PROTOCOL_RETURN_CODE<br />PROTOCOL_SESSION_ID<br />PROTOCOL_USERHOST<br />PROXY_SESSIONID<br />RLS_INFO<br />RMAN_DEVICE_TYPE<br />RMAN_OBJECT_TYPE<br />RMAN_OPERATION<br />RMAN_SESSION_RECID<br />RMAN_SESSION_STAMP<br />ROLE<br />SCN<br />SYSTEM_PRIVILEGE<br />SYSTEM_PRIVILEGE_USED<br />TARGET_USER<br />TERMINAL<br />UNIFIED_AUDIT_POLICIES<br />USERHOST<br />XS_CALLBACK_EVENT_TYPE<br />XS_COOKIE<br />XS_DATASEC_POLICY_NAME<br />XS_ENABLED_ROLE<br />XS_ENTITY_TYPE<br />XS_INACTIVITY_TIMEOUT<br />XS_NS_ATTRIBUTE<br />XS_NS_ATTRIBUTE_NEW_VAL<br />XS_NS_ATTRIBUTE_OLD_VAL<br />XS_NS_NAME<br />XS_PACKAGE_NAME<br />XS_PROCEDURE_NAME<br />XS_PROXY_USER_NAME<br />XS_SCHEMA_NAME<br />XS_SESSIONID<br />XS_TARGET_PRINCIPAL_NAME<br />XS_USER_NAME</pre> Per ulteriori informazioni, consulta [UNIFIED\$1AUDIT\$1TRAIL](https://docs.oracle.com/database/121/REFRN/GUID-B7CE1C02-2FD4-47D6-80AA-CF74A60CDD1D.htm#REFRN29162) nella documentazione di Oracle Database.  | 
|  `errorMessage`  |  stringa  |  N/A  |  Questo campo non viene utilizzato per RDS for Oracle ed è sempre null.  | 
|  `exitCode`  |  numero  |  Colonna `RETURN_CODE` in `UNIFIED_AUDIT_TRAIL`  |  Codice di errore di Oracle Database generato dall'operazione. Se l'azione ha avuto esito positivo, il valore è `0`.  | 
|  `logTime`  |  stringa  |  Colonna `EVENT_TIMESTAMP_UTC` in `UNIFIED_AUDIT_TRAIL`  |  Timestamp della creazione della voce del percorso di verifica. Un valore di esempio è `2020-11-27 06:56:14.981404`.  | 
|  `netProtocol`  |  stringa  |  Colonna `AUTHENTICATION_TYPE` in `UNIFIED_AUDIT_TRAIL`  |  Il protocollo di comunicazione di rete. Un valore di esempio è `TCP`.  | 
|  `objectName`  |  stringa  |  Colonna `OBJECT_NAME` in `UNIFIED_AUDIT_TRAIL`  |  Il nome dell'oggetto interessato dall'operazione. Un valore di esempio è `employees`.  | 
|  `objectType`  |  stringa  |  Colonna `OBJECT_SCHEMA` in `UNIFIED_AUDIT_TRAIL`  |  Il nome dello schema dell'oggetto interessato dall'operazione. Un valore di esempio è `hr`.  | 
|  `paramList`  |  elenco  |  Colonna `SQL_BINDS` in `UNIFIED_AUDIT_TRAIL`  |  L'elenco delle variabili di bind, se presenti, associate a `SQL_TEXT`. Un valore di esempio è `parameter_1,parameter_2`.  | 
|  `pid`  |  numero  |  Colonna `OS_PROCESS` in `UNIFIED_AUDIT_TRAIL`  |  L'identificatore del processo del sistema operativo del processo di database Oracle. Un valore di esempio è `22396`.  | 
|  `remoteHost`  |  stringa  |  Colonna `AUTHENTICATION_TYPE` in `UNIFIED_AUDIT_TRAIL`  |  L'indirizzo IP o il nome dell'host da cui è stata generata la sessione. Un valore di esempio è `123.456.789.123`.  | 
|  `remotePort`  |  stringa  |  Colonna `AUTHENTICATION_TYPE` in `UNIFIED_AUDIT_TRAIL`  |  Il numero di porta del client. Un valore tipico negli ambienti Oracle Database è `1521`.  | 
|  `rowCount`  |  numero  |  N/A  |  Questo campo non viene utilizzato per RDS for Oracle ed è sempre null.  | 
|  `serverHost`  |  stringa  |  Host database  |  L'indirizzo IP dell'host del server di database. Un valore di esempio è `123.456.789.123`.  | 
|  `serverType`  |  stringa  |  N/A  |  Il tipo di server di database. Il valore è sempre `ORACLE`.  | 
|  `serverVersion`  |  stringa  |  Host database  |  La versione, il Release Update (RU) e la Release Update Revision (RUR) di Amazon RDS for Oracle. Un valore di esempio è `19.0.0.0.ru-2020-01.rur-2020-01.r1.EE.3`.  | 
|  `serviceName`  |  stringa  |  Host database  |  Il nome del servizio Un valore di esempio è `oracle-ee`.   | 
|  `sessionId`  |  numero  |  Colonna `SESSIONID` in `UNIFIED_AUDIT_TRAIL`  |  L'identificatore di sessione della verifica. Un esempio è `1894327130`.  | 
|  `startTime`  |  stringa  |  N/A  |  Questo campo non viene utilizzato per RDS for Oracle ed è sempre null.  | 
|  `statementId`  |  numero  |  Colonna `STATEMENT_ID` in `UNIFIED_AUDIT_TRAIL`  |  ID numerico per ogni esecuzione di istruzione. Un'istruzione può causare molte azioni. Un valore di esempio è `142197`.  | 
|  `substatementId`  |  N/D  |  N/D  |  Questo campo non viene utilizzato per RDS for Oracle ed è sempre null.  | 
|  `transactionId`  |  stringa  |  Colonna `TRANSACTION_ID` in `UNIFIED_AUDIT_TRAIL`  |  L'identificatore della transazione in cui l'oggetto viene modificato. Un valore di esempio è `02000800D5030000`.  | 

## Campi databaseActivityEventList per Amazon RDS per SQL Server
<a name="DBActivityStreams.AuditLog.databaseActivityEventList.rss"></a>

Di seguito sono riportati i campi di `databaseActivityEventList` per Amazon RDS per SQL Server.


| Campo | Tipo di dati | Origine | Descrizione | 
| --- | --- | --- | --- | 
|  `class`  |  stringa  |  ` sys.fn_get_audit_file.class_type` mappato a `sys.dm_audit_class_type_map.class_type_desc`  |  La classe dell'evento attività. Per ulteriori informazioni, consulta [Controllo in SQL Server (motore del database)](https://learn.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-database-engine?view=sql-server-ver16) nella documentazione di Microsoft.  | 
|  `clientApplication`  |  stringa  |  `sys.fn_get_audit_file.application_name`  |  L'applicazione a cui il client si connette come indicato dal client (SQL Server versione 14 e successive). Questo campo è nullo in SQL Server versione 13.  | 
|  `command`  |  stringa  |  `sys.fn_get_audit_file.action_id` mappato a `sys.dm_audit_actions.name`  |  Categoria generale dell'istruzione SQL. I valori di questo campo dipendono dal valore della classe.  | 
|  `commandText`  |  stringa  |  `sys.fn_get_audit_file.statement`  |  Questo campo indica l'istruzione SQL.  | 
|  `databaseName`  |  stringa  |  `sys.fn_get_audit_file.database_name`  |  Nome del database.  | 
|  `dbProtocol`  |  stringa  |  N/A  |  Il protocollo di database. Il valore è `SQLSERVER`.  | 
|  `dbUserName`  |  stringa  |  `sys.fn_get_audit_file.server_principal_name`  |  L'utente del database per l'autenticazione del client.  | 
|  `endTime`  |  stringa  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `engineNativeAuditFields`  |  oggetto  |  Ogni campo presente in `sys.fn_get_audit_file` che non è elencato in questa colonna.  |  Per impostazione predefinita, è vuoto. Quando avvii il flusso di attività con l'opzione `--engine-native-audit-fields-included`, questo oggetto include altri campi di controllo nativi del motore, che non vengono restituiti da questa mappa JSON.  | 
|  `errorMessage`  |  stringa  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `exitCode`  |  integer  |  `sys.fn_get_audit_file.succeeded`  |  Indica se l'azione che ha avviato l'evento è stata completata. Questo campo non può essere nullo. Per tutti gli eventi, tranne quelli di accesso, questo campo indica se il controllo delle autorizzazioni è riuscito o meno, ma non se l'operazione è riuscita o meno. I valori includono: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/AmazonRDS/latest/UserGuide/DBActivityStreams.AuditLog.databaseActivityEventList.html)  | 
|  `logTime`  |  stringa  |  `sys.fn_get_audit_file.event_time`  |  Il timestamp dell'evento registrato da SQL Server.  | 
|  `netProtocol`  |  stringa  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `objectName`  |  stringa  |  `sys.fn_get_audit_file.object_name`  |  Il nome dell'oggetto di database se l'istruzione SQL viene eseguita su un oggetto.  | 
|  `objectType`  |  stringa  |  `sys.fn_get_audit_file.class_type` mappato a `sys.dm_audit_class_type_map.class_type_desc`  |  Il tipo di oggetto di database se l'istruzione SQL viene eseguita su un oggetto.  | 
|  `paramList`  |  stringa  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `pid`  |  integer  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `remoteHost`  |  stringa  |  `sys.fn_get_audit_file.client_ip`  |  L'indirizzo IP o il nome host del client che ha emesso l'istruzione SQL (SQL Server versione 14 e successive). Questo campo è nullo in SQL Server versione 13.  | 
|  `remotePort`  |  integer  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `rowCount`  |  integer  |  `sys.fn_get_audit_file.affected_rows`  |  Il numero di righe della tabella interessate dall'istruzione SQL (SQL Server versione 14 e successive). Questo campo è in SQL Server versione 13.  | 
|  `serverHost`  |  stringa  |  Host database  |  L'indirizzo IP del server di database di host.  | 
|  `serverType`  |  stringa  |  N/A  |  Il tipo di server di database. Il valore è `SQLSERVER`.  | 
|  `serverVersion`  |  stringa  |  Host database  |  La versione di server di database, ad esempio 15.00.4073.23.v1.R1 per SQL Server 2017.  | 
|  `serviceName`  |  stringa  |  Host database  |  Il nome del servizio Un valore di esempio è `sqlserver-ee`.  | 
|  `sessionId`  |  integer  |  `sys.fn_get_audit_file.session_id`  |  Identificatore univoco della sessione.  | 
|  `startTime`  |  stringa  |  N/A  |  Questo campo non è utilizzato da Amazon RDS per SQL Server e il valore è nullo.  | 
|  `statementId`  |  stringa  |  `sys.fn_get_audit_file.sequence_group_id`  |  Identificatore univoco per l'istruzione SQL del client. L'identificatore è diverso per ogni evento generato. Un valore di esempio è `0x38eaf4156267184094bb82071aaab644`.  | 
|  `substatementId`  |  integer  |  `sys.fn_get_audit_file.sequence_number`  |  Identificatore per determinare il numero di sequenza di una dichiarazione. Questo identificatore è utile quando i record di grandi dimensioni vengono suddivisi in più record.  | 
|  `transactionId`  |  integer  |  `sys.fn_get_audit_file.transaction_id`  |  Identificatore di una transazione. Se non ci sono transazioni attive, il valore è zero.  | 
|  `type`  |  stringa  |  Flussi di attività di database generati  |  Tipo di evento. I valori sono `record` o `heartbeat`.  | 

# Elaborazione di un flusso di attività del database utilizzando l'SDK AWS
<a name="DBActivityStreams.CodeExample"></a>

Puoi elaborare un flusso di attività a livello di programmazione utilizzando l'SDK AWS. Di seguito sono riportati esempi Java e Python completamente funzionanti dell'utilizzo dei record dei flussi di attività del database per l'abilitazione basata sull'istanza.

------
#### [ Java ]

```
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoInputStream;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.InvalidStateException;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.ShutdownException;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.ThrottlingException;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessor;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorCheckpointer;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorFactory;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShutdownReason;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker.Builder;
import com.amazonaws.services.kinesis.model.Record;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import com.amazonaws.util.Base64;
import com.amazonaws.util.IOUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class DemoConsumer {

    private static final String STREAM_NAME = "aws-rds-das-[instance-external-resource-id]"; // aws-rds-das-db-ABCD123456
    private static final String APPLICATION_NAME = "AnyApplication"; //unique application name for dynamo table generation that holds kinesis shard tracking
    private static final String AWS_ACCESS_KEY = "[AWS_ACCESS_KEY_TO_ACCESS_KINESIS]";
    private static final String AWS_SECRET_KEY = "[AWS_SECRET_KEY_TO_ACCESS_KINESIS]";
    private static final String RESOURCE_ID = "[external-resource-id]"; // db-ABCD123456
    private static final String REGION_NAME = "[region-name]"; //us-east-1, us-east-2...
    private static final BasicAWSCredentials CREDENTIALS = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
    private static final AWSStaticCredentialsProvider CREDENTIALS_PROVIDER = new AWSStaticCredentialsProvider(CREDENTIALS);

    private static final AwsCrypto CRYPTO = new AwsCrypto();
    private static final AWSKMS KMS = AWSKMSClientBuilder.standard()
            .withRegion(REGION_NAME)
            .withCredentials(CREDENTIALS_PROVIDER).build();

    class Activity {
        String type;
        String version;
        String databaseActivityEvents;
        String key;
    }

    class ActivityEvent {
        @SerializedName("class") String _class;
        String clientApplication;
        String command;
        String commandText;
        String databaseName;
        String dbProtocol;
        String dbUserName;
        String endTime;
        String errorMessage;
        String exitCode;
        String logTime;
        String netProtocol;
        String objectName;
        String objectType;
        List<String> paramList;
        String pid;
        String remoteHost;
        String remotePort;
        String rowCount;
        String serverHost;
        String serverType;
        String serverVersion;
        String serviceName;
        String sessionId;
        String startTime;
        String statementId;
        String substatementId;
        String transactionId;
        String type;
    }

    class ActivityRecords {
        String type;
        String clusterId; // note that clusterId will contain an empty string on RDS Oracle and RDS SQL Server
        String instanceId;
        List<ActivityEvent> databaseActivityEventList;
    }

    static class RecordProcessorFactory implements IRecordProcessorFactory {
        @Override
        public IRecordProcessor createProcessor() {
            return new RecordProcessor();
        }
    }

    static class RecordProcessor implements IRecordProcessor {

        private static final long BACKOFF_TIME_IN_MILLIS = 3000L;
        private static final int PROCESSING_RETRIES_MAX = 10;
        private static final long CHECKPOINT_INTERVAL_MILLIS = 60000L;
        private static final Gson GSON = new GsonBuilder().serializeNulls().create();

        private static final Cipher CIPHER;
        static {
            Security.insertProviderAt(new BouncyCastleProvider(), 1);
            try {
                CIPHER = Cipher.getInstance("AES/GCM/NoPadding", "BC");
            } catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) {
                throw new ExceptionInInitializerError(e);
            }
        }

        private long nextCheckpointTimeInMillis;

        @Override
        public void initialize(String shardId) {
        }

        @Override
        public void processRecords(final List<Record> records, final IRecordProcessorCheckpointer checkpointer) {
            for (final Record record : records) {
                processSingleBlob(record.getData());
            }

            if (System.currentTimeMillis() > nextCheckpointTimeInMillis) {
                checkpoint(checkpointer);
                nextCheckpointTimeInMillis = System.currentTimeMillis() + CHECKPOINT_INTERVAL_MILLIS;
            }
        }

        @Override
        public void shutdown(IRecordProcessorCheckpointer checkpointer, ShutdownReason reason) {
            if (reason == ShutdownReason.TERMINATE) {
                checkpoint(checkpointer);
            }
        }

        private void processSingleBlob(final ByteBuffer bytes) {
            try {
                // JSON $Activity
                final Activity activity = GSON.fromJson(new String(bytes.array(), StandardCharsets.UTF_8), Activity.class);

                // Base64.Decode
                final byte[] decoded = Base64.decode(activity.databaseActivityEvents);
                final byte[] decodedDataKey = Base64.decode(activity.key);

                Map<String, String> context = new HashMap<>();
                context.put("aws:rds:db-id", RESOURCE_ID);

                // Decrypt
                final DecryptRequest decryptRequest = new DecryptRequest()
                        .withCiphertextBlob(ByteBuffer.wrap(decodedDataKey)).withEncryptionContext(context);
                final DecryptResult decryptResult = KMS.decrypt(decryptRequest);
                final byte[] decrypted = decrypt(decoded, getByteArray(decryptResult.getPlaintext()));

                // GZip Decompress
                final byte[] decompressed = decompress(decrypted);
                // JSON $ActivityRecords
                final ActivityRecords activityRecords = GSON.fromJson(new String(decompressed, StandardCharsets.UTF_8), ActivityRecords.class);

                // Iterate throught $ActivityEvents
                for (final ActivityEvent event : activityRecords.databaseActivityEventList) {
                    System.out.println(GSON.toJson(event));
                }
            } catch (Exception e) {
                // Handle error.
                e.printStackTrace();
            }
        }

        private static byte[] decompress(final byte[] src) throws IOException {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
            GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
            return IOUtils.toByteArray(gzipInputStream);
        }

        private void checkpoint(IRecordProcessorCheckpointer checkpointer) {
            for (int i = 0; i < PROCESSING_RETRIES_MAX; i++) {
                try {
                    checkpointer.checkpoint();
                    break;
                } catch (ShutdownException se) {
                    // Ignore checkpoint if the processor instance has been shutdown (fail over).
                    System.out.println("Caught shutdown exception, skipping checkpoint." + se);
                    break;
                } catch (ThrottlingException e) {
                    // Backoff and re-attempt checkpoint upon transient failures
                    if (i >= (PROCESSING_RETRIES_MAX - 1)) {
                        System.out.println("Checkpoint failed after " + (i + 1) + "attempts." + e);
                        break;
                    } else {
                        System.out.println("Transient issue when checkpointing - attempt " + (i + 1) + " of " + PROCESSING_RETRIES_MAX + e);
                    }
                } catch (InvalidStateException e) {
                    // This indicates an issue with the DynamoDB table (check for table, provisioned IOPS).
                    System.out.println("Cannot save checkpoint to the DynamoDB table used by the Amazon Kinesis Client Library." + e);
                    break;
                }
                try {
                    Thread.sleep(BACKOFF_TIME_IN_MILLIS);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted sleep" + e);
                }
            }
        }
    }

    private static byte[] decrypt(final byte[] decoded, final byte[] decodedDataKey) throws IOException {
        // Create a JCE master key provider using the random key and an AES-GCM encryption algorithm
        final JceMasterKey masterKey = JceMasterKey.getInstance(new SecretKeySpec(decodedDataKey, "AES"),
                "BC", "DataKey", "AES/GCM/NoPadding");
        try (final CryptoInputStream<JceMasterKey> decryptingStream = CRYPTO.createDecryptingStream(masterKey, new ByteArrayInputStream(decoded));
             final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            IOUtils.copy(decryptingStream, out);
            return out.toByteArray();
        }
    }

    public static void main(String[] args) throws Exception {
        final String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
        final KinesisClientLibConfiguration kinesisClientLibConfiguration =
                new KinesisClientLibConfiguration(APPLICATION_NAME, STREAM_NAME, CREDENTIALS_PROVIDER, workerId);
        kinesisClientLibConfiguration.withInitialPositionInStream(InitialPositionInStream.LATEST);
        kinesisClientLibConfiguration.withRegionName(REGION_NAME);
        final Worker worker = new Builder()
                .recordProcessorFactory(new RecordProcessorFactory())
                .config(kinesisClientLibConfiguration)
                .build();

        System.out.printf("Running %s to process stream %s as worker %s...\n", APPLICATION_NAME, STREAM_NAME, workerId);

        try {
            worker.run();
        } catch (Throwable t) {
            System.err.println("Caught throwable while processing data.");
            t.printStackTrace();
            System.exit(1);
        }
        System.exit(0);
    }

    private static byte[] getByteArray(final ByteBuffer b) {
        byte[] byteArray = new byte[b.remaining()];
        b.get(byteArray);
        return byteArray;
    }
}
```

------
#### [ Python ]

```
import base64
import json
import zlib
import aws_encryption_sdk
from aws_encryption_sdk import CommitmentPolicy
from aws_encryption_sdk.internal.crypto import WrappingKey
from aws_encryption_sdk.key_providers.raw import RawMasterKeyProvider
from aws_encryption_sdk.identifiers import WrappingAlgorithm, EncryptionKeyType
import boto3

REGION_NAME = '<region>'                    # us-east-1
RESOURCE_ID = '<external-resource-id>'      # db-ABCD123456
STREAM_NAME = 'aws-rds-das-' + RESOURCE_ID  # aws-rds-das-db-ABCD123456

enc_client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)

class MyRawMasterKeyProvider(RawMasterKeyProvider):
    provider_id = "BC"

    def __new__(cls, *args, **kwargs):
        obj = super(RawMasterKeyProvider, cls).__new__(cls)
        return obj

    def __init__(self, plain_key):
        RawMasterKeyProvider.__init__(self)
        self.wrapping_key = WrappingKey(wrapping_algorithm=WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING,
                                        wrapping_key=plain_key, wrapping_key_type=EncryptionKeyType.SYMMETRIC)

    def _get_raw_key(self, key_id):
        return self.wrapping_key


def decrypt_payload(payload, data_key):
    my_key_provider = MyRawMasterKeyProvider(data_key)
    my_key_provider.add_master_key("DataKey")
    decrypted_plaintext, header = enc_client.decrypt(
        source=payload,
        materials_manager=aws_encryption_sdk.materials_managers.default.DefaultCryptoMaterialsManager(master_key_provider=my_key_provider))
    return decrypted_plaintext


def decrypt_decompress(payload, key):
    decrypted = decrypt_payload(payload, key)
    return zlib.decompress(decrypted, zlib.MAX_WBITS + 16)


def main():
    session = boto3.session.Session()
    kms = session.client('kms', region_name=REGION_NAME)
    kinesis = session.client('kinesis', region_name=REGION_NAME)

    response = kinesis.describe_stream(StreamName=STREAM_NAME)
    shard_iters = []
    for shard in response['StreamDescription']['Shards']:
        shard_iter_response = kinesis.get_shard_iterator(StreamName=STREAM_NAME, ShardId=shard['ShardId'],
                                                         ShardIteratorType='LATEST')
        shard_iters.append(shard_iter_response['ShardIterator'])

    while len(shard_iters) > 0:
        next_shard_iters = []
        for shard_iter in shard_iters:
            response = kinesis.get_records(ShardIterator=shard_iter, Limit=10000)
            for record in response['Records']:
                record_data = record['Data']
                record_data = json.loads(record_data)
                payload_decoded = base64.b64decode(record_data['databaseActivityEvents'])
                data_key_decoded = base64.b64decode(record_data['key'])
                data_key_decrypt_result = kms.decrypt(CiphertextBlob=data_key_decoded,
                                                      EncryptionContext={'aws:rds:db-id': RESOURCE_ID})
                print (decrypt_decompress(payload_decoded, data_key_decrypt_result['Plaintext']))
            if 'NextShardIterator' in response:
                next_shard_iters.append(response['NextShardIterator'])
        shard_iters = next_shard_iters


if __name__ == '__main__':
    main()
```

------