

# Schedule video recording and storage with Amazon Kinesis Video Streams Edge Agent
<a name="edge"></a>

Amazon Kinesis Video Streams offers an efficient, cost-effective way to connect to IP cameras on customer premises. With the Amazon Kinesis Video Streams Edge Agent, you can locally record and store video from the cameras and stream videos to the cloud on a customer-defined schedule for long-term storage, playback, and analytical processing.

**Note**  
To access the Amazon Kinesis Video Streams Edge Agent, complete this [brief form](https://pages.awscloud.com/GLOBAL-launch-DL-KVS-Edge-2023-learn.html).

You can download the Amazon Kinesis Video Streams Edge Agent and deploy it at your on-premises edge compute devices. You can also easily deploy them in Docker containers running on Amazon EC2 instances. After deployment, you can use the Amazon Kinesis Video Streams API to update video recording and cloud uploading configurations. The feature works with any IP camera that can stream over RTSP protocol. It doesn't require any additional firmware deployment to the cameras.

We offer the following installations for the Amazon Kinesis Video Streams Edge Agent:
+ **As an AWS IoT Greengrass V2 component:** You can install the Amazon Kinesis Video Streams Edge Agent as an AWS IoT Greengrass component on any AWS IoT Greengrass certified device. To learn more about AWS IoT Greengrass, see the [AWS IoT Greengrass Version 2 Developer Guide](https://docs.aws.amazon.com/greengrass/v2/developerguide/). 
+ **On AWS Snowball Edge:** You can run the Amazon Kinesis Video Streams Edge Agent on Snowball Edge devices. To learn more, see the [AWS Snowball Edge Edge Developer Guide](https://docs.aws.amazon.com/snowball/latest/developer-guide/). 
+ **On a native AWS IoT deployment:** You can install the Amazon Kinesis Video Streams Edge Agent natively on any compute instance. Edge SDK uses [AWS IoT Core](https://docs.aws.amazon.com//iot/latest/developerguide/iot-gs.html) for managing edge through the [Amazon Kinesis Video Streams](API_Operations_Amazon_Kinesis_Video_Streams.md). 

To get started with Amazon Kinesis Video Streams Edge Agent, continue with the appropriate procedures below.

**Topics**
+ [

## Amazon Kinesis Video Streams Edge Agent API operations
](#edge-apis)
+ [

## Monitoring Amazon Kinesis Video Streams Edge Agent
](#edge-monitoring)
+ [

# Deploy in non-AWS IoT Greengrass mode
](gs-edge-outside.md)
+ [

# Deploy the Amazon Kinesis Video Streams Edge Agent to AWS IoT Greengrass
](gs-edge-gg.md)
+ [

# Amazon Kinesis Video Streams Edge Agent FAQ
](edge-faq.md)

## Amazon Kinesis Video Streams Edge Agent API operations
<a name="edge-apis"></a>

Use the following API operations to configure the Amazon Kinesis Video Streams Edge Agent:
+ [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md)
+ [DescribeEdgeConfiguration](API_DescribeEdgeConfiguration.md)
+ [DeleteEdgeConfiguration](API_DeleteEdgeConfiguration.md)
+ [ListEdgeAgentConfigurations](API_ListEdgeAgentConfigurations.md)

## Monitoring Amazon Kinesis Video Streams Edge Agent
<a name="edge-monitoring"></a>

To monitor your Amazon Kinesis Video Streams Edge Agent, see [Monitor the Amazon Kinesis Video Streams Edge Agent with CloudWatch](monitoring-edge-cloudwatch.md).

# Deploy in non-AWS IoT Greengrass mode
<a name="gs-edge-outside"></a>

This section provides a comprehensive guide to use Amazon Kinesis Video Streams outside of the AWS IoT Greengrass environment. Whether you're working with edge devices or other platforms, this information will help you set up and utilize Kinesis Video Streams effectively.

You'll find detailed information on:
+ Setting up your development environment
+ Creating a Kinesis video stream
+ Downloading and compiling the Kinesis Video Streams Producer SDK
+ Writing and examining a sample application
+ Running the sample application

Continue with the steps below to run the Amazon Kinesis Video Streams Edge Agent with AWS IoT MQTT as a standalone deployment.

**Topics**
+ [

# Install dependencies
](gs-install-dependencies.md)
+ [

# Create resources for your IP camera RTSP URLs
](gs-create-resources-standalone.md)
+ [

# Create an IAM permissions policy
](gs-iam-role.md)
+ [

# Create an IAM role
](gs-create-role.md)
+ [

# Create the AWS IoT role alias
](gs-create-role-alias.md)
+ [

# Create the AWS IoT policy
](gs-create-policy.md)
+ [

# Create an AWS IoT thing and get AWS IoT Core credentials
](gs-create-thing.md)
+ [

# Build the Amazon Kinesis Video Streams Edge Agent
](gs-build-agent.md)
+ [

# Install the CloudWatch agent on the device
](gs-install-cloudwatch.md)
+ [

# Run the Amazon Kinesis Video Streams Edge Agent as a native process
](gs-run.md)

# Install dependencies
<a name="gs-install-dependencies"></a>

Before you can start using the Amazon Kinesis Video Streams producer SDK, you need to set up your development environment with the necessary dependencies. This page guides you through the process of installing the required software components and libraries on your system.

**Note**  
For a list of supported operating systems, see [What operating systems does Amazon Kinesis Video Streams Edge Agent support?](edge-faq.md#edge-faq-os).

**Install dependencies on the device**

1. To run the Amazon Kinesis Video Streams Edge Agent, install the following appropriate libraries on your device:

------
#### [ Ubuntu ]

   Type:

   ```
   wget -O- https://apt.corretto.aws/corretto.key | sudo apt-key add - 
   sudo add-apt-repository 'deb https://apt.corretto.aws stable main' 
   sudo apt-get update 
                           
   sudo apt-get install -y gcc libssl-dev libcurl4-openssl-dev liblog4cplus-dev \
   libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
   gstreamer1.0-plugins-base-apps gstreamer1.0-plugins-bad \
   gstreamer1.0-plugins-good gstreamer1.0-tools \
   unzip java-11-amazon-corretto-jdk maven
   ```

------
#### [ Amazon Linux 2 ]

   Type:

   ```
   sudo yum update -y && sudo yum upgrade -y && sudo yum clean all -y 
   sudo yum install -y gcc-c++ openssl-devel libcurl-devel gstreamer1* wget \
   java-11-amazon-corretto tar
   ```

   Install `log4cplus-2.1.0` from the source.

   ```
   wget https://github.com/log4cplus/log4cplus/releases/download/REL_2_1_0/log4cplus-2.1.0.tar.gz
   tar -xzvf log4cplus-2.1.0.tar.gz
   cd log4cplus-2.1.0 && \
   mkdir build && \
   cd build && \
   cmake .. && \
   sudo make && \
   sudo make install
   ```

   Install `apache-maven-3.9.2` from the source.

   ```
   wget https://dlcdn.apache.org/maven/maven-3/3.9.2/binaries/apache-maven-3.9.2-bin.tar.gz
   RUN tar -xzvf apache-maven-3.9.2-bin.tar.gz -C /opt
   ```

------
**Important**  
If you see a screen telling you that some services need to be restarted, press Enter to select **Ok**.

   For additional information, see [https://docs.aws.amazon.com//corretto/latest/corretto-11-ug/generic-linux-install.html](https://docs.aws.amazon.com//corretto/latest/corretto-11-ug/generic-linux-install.html).

1. Install the AWS Command Line Interface. See the [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com//cli/latest/userguide/getting-started-install.html) procedures in the *AWS Command Line Interface User Guide*.

# Create resources for your IP camera RTSP URLs
<a name="gs-create-resources-standalone"></a>

Follow these procedures to create the streams and secrets needed in AWS Secrets Manager. Do this step first, because you need the ARNs of the created resources in the policies.

## Create Amazon Kinesis Video Streams
<a name="gs-create-kvs"></a>

Create Amazon Kinesis Video Streams using the AWS Management Console, AWS CLI, or API.

In the AWS Management Console, open the [Amazon Kinesis Video Streams console](https://console.aws.amazon.com/kinesisvideo/home/). Choose **Video streams** in the left navigation.

For more information, see [Create an Amazon Kinesis video stream](gs-createstream.md).

## Create secrets in AWS Secrets Manager
<a name="gs-create-secrets"></a>

In the AWS Management Console, open the [AWS Secrets Manager console](https://console.aws.amazon.com/secretsmanager/landing). Choose **Secrets** in the left navigation.

Verify that the appropriate Region is selected.

1. Choose **Store a new secret**.

   1. **Step 1: Choose secret type**
      + Select **Other type of secret**.
      + In the **Key/Value Pairs** section, add a key-value pair. 

        **Key**: `MediaURI`
**Note**  
The key must be `MediaURI`. This is case-sensitive. If you enter it incorrectly, the application doesn't work.

        **Value**: `Your MediaURI`.  
**Example**  

        **Example:** `rtsp://<YourCameraIPAddress>:<YourCameraRTSPPort>/YourCameraMediaURI`.

   1. **Step 2: Configure secret**. Give this secret a name. Name it whatever you want.

   1. **Step 3: Configure rotation - optional**. Choose **Next**.

   1. **Step 4: Review**. Choose **Store**.

1. If your secret does not display immediately, select the refresh button.

   Choose the name of your secret. Make note of the **Secret ARN**.

1. Repeat this process for each MediaURI that you want to stream from.

**Note**  
The AWS network blocks some public RTSP sources. You cannot access these from within the Amazon EC2 instance or if you are running unmanaged while connected to the VPN.  
Your camera RTSP URL should stream video in h.264 format. The fragment duration must not exceed the limit mentioned in [Producer SDK quotas](limits.md#producer-sdk-limits).  
Amazon Kinesis Video Streams Edge Agent only supports video.
Run `gst-discoverer-1.0 Your RtspUrl` to make sure that your camera is reachable from your device.

Save the ARNs for all of the streams and secrets that you created. You need these for the next step.

# Create an IAM permissions policy
<a name="gs-iam-role"></a>

Follow these procedures to create an IAM policy. This permissions policy allows selective access control (a subset of supported operations) for an AWS resource. In this case, the AWS resources are the video streams that you want the Amazon Kinesis Video Streams Edge Agent to stream to. The resources also include the AWS Secrets Manager secrets that the Amazon Kinesis Video Streams Edge Agent can retrieve. For more information, see [IAM policies](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies.html).

**Create a policy by using the JSON policy editor**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the left navigation pane, choose **Policies**.

   If this is your first time choosing **Policies**, the **Welcome to Managed Policies** page appears. Choose **Get Started**.

1. At the top of the page, choose **Create policy**.

1. In the **Policy editor** section, choose the **JSON** option.

1. Enter the following JSON policy document:

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "cloudwatch:PutMetricData",
                   "kinesisvideo:ListStreams",
                   "iot:Connect",
                   "iot:Publish",
                   "iot:Subscribe",
                   "iot:Receive"
               ],
               "Resource": [
                   "*"
               ] 
           },
           {
               "Effect": "Allow",
               "Action": [
                   "kinesisvideo:DescribeStream",
                   "kinesisvideo:PutMedia",
                   "kinesisvideo:TagStream",
                   "kinesisvideo:GetDataEndpoint"
               ],
                "Resource": [ 
                   "arn:aws:kinesisvideo:*:*:stream/streamName1/*",
                   "arn:aws:kinesisvideo:*:*:stream/streamName2/*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": "secretsmanager:GetSecretValue",
               "Resource": [
                    "arn:aws:secretsmanager:*:*:secret:*",
                    "arn:aws:secretsmanager:*:*:secret:*"
               ]
           }
       ]
   }
   ```

------
**Note**  
Replace `arn:aws:kinesisvideo:*:*:stream/streamName1/*` and `arn:aws:kinesisvideo:*:*:stream/streamName2/*` with the ARNs for the video streams, and replace `arn:aws:secretsmanager:*:*:secret:*` with the ARNs that contain the MediaURI secrets that you created in [Create resources for your IP camera RTSP URLs](gs-create-resources-standalone.md). Use the ARNs for the secrets that you want the Amazon Kinesis Video Streams Edge Agent to access.

1. Choose **Next**.
**Note**  
You can switch between the **Visual** and **JSON** editor options anytime. However, if you make changes or choose **Next** in the **Visual** editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see [Policy restructuring](https://docs.aws.amazon.com//IAM/latest/UserGuide/troubleshoot_policies.html#troubleshoot_viseditor-restructure) in the IAM User Guide.

1. On the **Review and create** page, enter a **Policy name** and an optional **Description** for the policy that you are creating. Review **Permissions defined in this policy** to see the permissions that are granted by your policy. 

1. Choose **Create policy** to save your new policy.

# Create an IAM role
<a name="gs-create-role"></a>

The role that you create in this step can be assumed by AWS IoT in order to obtain temporary credentials from the AWS Security Token Service (AWS STS). This is done when performing credential authorization requests from the Amazon Kinesis Video Streams Edge Agent.

**Create the service role for Amazon Kinesis Video Streams (IAM console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose **Create role**.

1. Choose the **Custom trust policy** role type and paste the following policy:

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {
               "Service": "credentials.iot.amazonaws.com"
           },
           "Action": "sts:AssumeRole"
       }
   }
   ```

------

1. Select the box next to the IAM policy that you created in [Create an IAM permissions policy](gs-iam-role.md).

1. Choose **Next**.

1. Enter a role name or role name suffix to help you identify the purpose of this role.   
**Example**  

   **Example:** `KvsEdgeAgentRole`

1. (Optional) For **Description**, enter a description for the new role.

1. (Optional) Add metadata to the role by attaching tags as key/value pairs.

   For more information about using tags in IAM, see [Tagging IAM resources](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_tags.html) in the IAM User Guide.

1. Review the role and then choose **Create role**.

# Create the AWS IoT role alias
<a name="gs-create-role-alias"></a>

Follow these procedures to create an AWS IoT role alias for the IAM role that you created in [Create an IAM role](gs-create-role.md). A role alias is an alternate data model that points to the IAM role. An AWS IoT credentials provider request must include a role alias to indicate which IAM role to assume in order to obtain temporary credentials from the AWS Security Token Service (AWS STS). For more information, see [How to use a certificate to get a security token](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.html#authorizing-direct-aws.walkthrough).

**Create the AWS IoT role alias**

1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

1. Verify that the appropriate Region is selected.

1. On the left navigation, select **Security** and then choose **Role Aliases**.

1. Choose **Create role alias**.

1. Enter a name for your role alias.  
**Example**  

   **Example:** `KvsEdgeAgentRoleAlias`

1. In the **Role** dropdown, select the IAM role you created in [Create an IAM role](gs-create-role.md).

1. Choose **Create**. On the next page, you see a note that your role alias was successfully created.

1. Search for and select the newly created role alias. Make note of the **Role alias ARN**. You need this for the AWS IoT policy in the next step.

# Create the AWS IoT policy
<a name="gs-create-policy"></a>

Follow these procedures to create an AWS IoT policy that will be attached to the device certificate. This gives permissions to AWS IoT capabilities and allows the assumption of the role alias using the certificate.

With AWS IoT Core policies, you can control access to the AWS IoT Core data plane. The AWS IoT Core data plane consists of operations that you can use to do the following:
+ Connect to the AWS IoT Core message broker
+ Send and receive MQTT messages
+ Get or update a thing's device shadow

For more information, see [AWS IoT Core policies](https://docs.aws.amazon.com//iot/latest/developerguide/iot-policies.html).

**Use AWS IoT policy editor to create an AWS IoT policy**

1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

1. On the left navigation, select **Security** and then choose **Policies**.

1. Choose **Create policy**.

1. Enter a name for your policy.  
**Example**  

   An example of a policy name is **KvsEdgeAccessIoTPolicy**.

1. (Optional) Add metadata to the policy by attaching tags as key-value pairs.

   For more information about using tags in IAM, see [Tagging your AWS IoT resources](https://docs.aws.amazon.com//iot/latest/developerguide/tagging-iot.html) in the *AWS IoT Core Developer Guide*. 

1. Choose the **JSON** tab.

1. Paste the following JSON policy document:

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Connect",
                   "iot:Publish",
                   "iot:Subscribe",
                   "iot:Receive"
               ],
               "Resource": [
                   "*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "sts:AssumeRoleWithWebIdentity"
               ],
               "Resource": "arn:aws:iot:us-west-2:123456789012:rolealias/your-role-alias"
           }
       ]
   }
   ```

------
**Note**  
Replace `your-role-alias-arn` with the ARN of the role alias that you created in [Create the AWS IoT role alias](gs-create-role-alias.md).

1. Choose **Create** to save your work.

# Create an AWS IoT thing and get AWS IoT Core credentials
<a name="gs-create-thing"></a>

At this point you've created:
+ An IAM permissions policy. See [Create an IAM permissions policy](gs-iam-role.md).
+ An IAM role, with the permissions policy attached. See [Create an IAM role](gs-create-role.md).
+ An AWS IoT role alias for the IAM role. See [Create the AWS IoT role alias](gs-create-role-alias.md).
+ An AWS IoT policy, currently unattached to any AWS resource. See [Create the AWS IoT policy](gs-create-policy.md).

**To create and register an AWS IoT thing and get AWS IoT Core access credentials**

1. Register the device as an AWS IoT thing and generate the X.509 certificate for the device.

   1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

   1. Select the appropriate Region.

   1. On the left navigation, select **All devices**, then choose **Things**.

   1. Choose **Create things**.

   1. Select **Create single thing**, then choose **Next**.

      1. **Step 1. Specify thing properties**

         Type a name for your thing, then choose **Next**.

      1. **Step 2. Configure device certificate**

         Select **Auto-generate a new certificate (recommended)**, then choose **Next**.

      1. **Step 3. Attach policies to certificate**

         Search for the permissions policy you created in [Create the AWS IoT policy](gs-create-policy.md).

         Select the check box next to your policy and choose **Create thing**.

   1. In the window that appears, download the following files:
      + Device certificate. This is the X.509 certificate.
      + Public key file
      + Private key file
      + Amazon trust services endpoint (RSA 2048 bit key: Amazon Root CA 1)

      Make note of the location of each of these files for a later step.

   1. Choose **Done**. On the next page, you see a note that your thing was successfully created. 

   1. Transfer the files downloaded above onto your AWS IoT thing, if not already there.

1. Obtain the credential provider endpoint for your AWS account.

------
#### [ AWS CLI ]

   Run the following command:

   ```
   aws iot describe-endpoint --endpoint-type iot:CredentialProvider
   ```

------
#### [ AWS Management Console ]

   In [AWS CloudShell](https://docs.aws.amazon.com//cloudshell/latest/userguide/getting-started.html), run the following command:

   ```
   aws iot describe-endpoint --endpoint-type iot:CredentialProvider
   ```

------

   Make note of this information for a later step.

1. Obtain the device data endpoint for your AWS account.

------
#### [ AWS CLI ]

   Run the following command:

   ```
   aws iot describe-endpoint --endpoint-type iot:Data-ATS
   ```

------
#### [ AWS Management Console ]

   Do the following:

   1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

   1. In the left navigation, select **Settings**.

   1. Locate the **Device data endpoint**.

------

   Make note of this information for a later step.

1. (Optional) Verify that your certificates were generated correctly.

   Run the following command to validate that your items were generated correctly.

   ```
   curl --header "x-amzn-iot-thingname:your-thing-name" \
     --cert /path/to/certificateID-certificate.pem.crt \
     --key /path/to/certificateID-private.pem.key \
     --cacert /path/to/AmazonRootCA1.pem \
     https://your-credential-provider-endpoint/role-aliases/your-role-alias-name/credentials
   ```

   For more information, see [How to use a certificate to get a security token](https://docs.aws.amazon.com//iot/latest/developerguide/authorizing-direct-aws.html#authorizing-direct-aws.walkthrough).

# Build the Amazon Kinesis Video Streams Edge Agent
<a name="gs-build-agent"></a>

**Build the Amazon Kinesis Video Streams Edge Agent**

1. Download the `tar` file using the link that was provided to you.

   If you completed the Amazon Kinesis Video Streams Edge Agent interest form, check your email for the download link. If you haven't completed the form, complete it [here](https://pages.awscloud.com/GLOBAL-launch-DL-KVS-Edge-2023-learn.html).

1. Verify the checksum.

1. Extract the binaries and jar in your device.

   Type: `tar -xvf kvs-edge-agent.tar.gz`.

   After extraction, your folder structure will look like the following:

   ```
   kvs-edge-agent/LICENSE
   kvs-edge-agent/THIRD-PARTY-LICENSES
   kvs-edge-agent/pom.xml
   kvs-edge-agent/KvsEdgeComponent
   kvs-edge-agent/KvsEdgeComponent/recipes
   kvs-edge-agent/KvsEdgeComponent/recipes/recipe.yaml
   kvs-edge-agent/KvsEdgeComponent/artifacts
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/edge_log_config
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/kvs-edge-agent.jar
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/libgstkvssink.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/libIngestorPipelineJNI.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib/libcproducer.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib/libKinesisVideoProducer.so
   ```
**Note**  
The release folder name should be set up in a way that reflects the latest binary release number. For example, a 1.0.0 release will have the folder name set as 1.0.0. 

1. Build the dependencies jar. 
**Note**  
The jar included with the `kvs-edge-agent.tar.gz` does not have the dependencies. Use the following steps to build those libraries.

   Navigate to the `kvs-edge-agent` folder that contains `pom.xml`. 

   Type `mvn clean package`.

   This generates a jar file containing the dependencies the Amazon Kinesis Video Streams Edge Agent requires at `kvs-edge-agent/target/libs.jar`.

1. Place the `libs.jar` into the folder that contains the component's artifacts.

   Type `mv ./target/libs.jar ./KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/`.

1. Set environment variables using the values from previous steps. The following table provides descriptions for the variables.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-build-agent.html)

1. Clear the GStreamer cache. Type:

   ```
   rm ~/.cache/gstreamer-1.0/registry.your-os-architecture.bin
   ```

   For more information, see the [GStreamer registry documentation](https://gstreamer.freedesktop.org/documentation/gstreamer/gstregistry.html?gi-language=c).

1. Prepare and run the java command. The Amazon Kinesis Video Streams Edge Agent accepts the following arguments:    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-build-agent.html)

   To set these, add `-Djava-property-name=value` to the java command used to run the jar.

   For example:

   ```
   java -Djava.library.path=/download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion \
     --add-opens java.base/jdk.internal.misc=ALL-UNNAMED \
     -Dio.netty.tryReflectionSetAccessible=true \
     -cp kvs-edge-agent.jar:libs.jar \
     com.amazonaws.kinesisvideo.edge.controller.ControllerApp
   ```
**Important**  
Run the java command above from the same directory as `/download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion`.

1. Send configurations to the application using the AWS CLI.

   1. Create a new file, `example-edge-configuration.json`. 

      Paste the following code into the file. This is a sample configuration that records daily from 9:00:00 AM to 4:59:59 PM (according to the system time on your AWS IoT device). It also uploads the recorded media daily from 7:00:00 PM to 9:59:59 PM.

      For more information, see [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md).

      ```
      {
          "StreamARN": "arn:aws:kinesisvideo:your-region:your-account-id:stream/your-stream/0123456789012",
          "EdgeConfig": {
              "HubDeviceArn": "arn:aws:iot:your-region:your-account-id:thing/kvs-edge-agent-demo",
              "RecorderConfig": {
                  "MediaSourceConfig": {
                      "MediaUriSecretArn": "arn:aws:secretsmanager:your-region:your-account-id:secret:your-secret-dRbHJQ",
                      "MediaUriType": "RTSP_URI"
                  },
                  "ScheduleConfig": {
                      "ScheduleExpression": "0 0 9,10,11,12,13,14,15,16 ? * * *",
                      "DurationInSeconds": 3599
                  }
              },
              "UploaderConfig": {
                  "ScheduleConfig": {
                      "ScheduleExpression": "0 0 19,20,21 ? * * *",
                      "DurationInSeconds": 3599
                  }
              },
              "DeletionConfig": {
                  "EdgeRetentionInHours": 15,
                  "LocalSizeConfig": {
                    "MaxLocalMediaSizeInMB": 2800,
                    "StrategyOnFullSize": "DELETE_OLDEST_MEDIA"
                  },
                  "DeleteAfterUpload": true
              }
          }
      }
      ```

   1. To send the file to the Amazon Kinesis Video Streams Edge Agent, type the following in the AWS CLI:

      ```
      aws kinesisvideo start-edge-configuration-update --cli-input-json "file://example-edge-configuration.json"
      ```

1. Repeat the previous step for each stream for the Amazon Kinesis Video Streams Edge Agent.

# Install the CloudWatch agent on the device
<a name="gs-install-cloudwatch"></a>

**Note**  
Be aware of the [CloudWatch quotas](https://docs.aws.amazon.com//AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html). 

Follow these procedures to install and configure the CloudWatch agent to automatically upload the logs generated by the Amazon Kinesis Video Streams Edge Agent to CloudWatch. This is an optional step.

For [procedures](https://docs.aws.amazon.com//AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html) to install the CloudWatch agent on your device, see the Amazon CloudWatch User Guide.

When prompted for the configuration, select **one** of the following configurations.

**Important**  
The `file_path` in the following configurations assumes that the default logging output location is used.  
The file path used assumes that you are running the Amazon Kinesis Video Streams Edge Agent from the location: `download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version`.
+ To configure the CloudWatch agent to upload logs and post device RAM and CPU metrics, paste the following into the configuration file.

  ```
  {
    "agent": {
      "run_as_user": "ubuntu",
      "metrics_collection_interval": 60
    },
    "metrics": {
      "metrics_collected": {
        "mem": {
          "measurement": [
            "mem_used_percent"
          ],
          "append_dimensions": {
            "IotThing": "YourIotThingName"
          }
        },
        "cpu": {
          "resources": [
            "*" 
          ],
          "measurement": [
            "usage_active"
          ],
          "totalcpu": true,
          "append_dimensions": {
            "IotThing": "YourIotThingName"
          }
        }
      }
    },
    "logs": {
      "logs_collected": {
        "files": {
          "collect_list": [
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/java_kvs.log",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-java_kvs.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvs_edge.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvs_edge.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvs_streams.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvs_streams.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvssink.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvssink.log"
            }
          ]
        }
      }
    }
  }
  ```
+ To upload only the logs and not collect device’s RAM and CPU, use the following configuration:

  ```
  {
    "logs": {
      "logs_collected": {
        "files": {
          "collect_list": [
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/java_kvs.log",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-java_kvs.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvs_edge.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvs_edge.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvs_streams.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvs_streams.log"
            },
            {
              "file_path": "download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/version/log/cpp_kvssink.log*",
              "log_group_name": "/aws/kinesisvideo/EdgeRuntimeAgent",
              "log_stream_name": "YourIotThingName-cpp_kvssink.log"
            }
          ]
        }
      }
    }
  }
  ```

# Run the Amazon Kinesis Video Streams Edge Agent as a native process
<a name="gs-run"></a>

Set up the Amazon Kinesis Video Streams Edge Agent as a systemd service. This is an optional step.

`systemd` is a systems and service manager on Linux devices. `systemd` is the recommended way to manage the process, as it will restart the Amazon Kinesis Video Streams Edge Agent in case the application encounters an error or the device running the application loses power.

Do the following:

**Run the Amazon Kinesis Video Streams Edge Agent as a native process**

1. Create a new file in `/etc/systemd/system` and name it `aws.kinesisvideo.edge-runtime-agent.service`.

   Paste the following:

   ```
   [Unit]
   Description=AWS Kinesis Video Streams edge agent
   After=network.target
   StartLimitBurst=3
   StartLimitInterval=30
   
   [Service]
   Type=simple
   Restart=on-failure
   RestartSec=10
   WorkingDirectory=/download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion
   Environment="GST_PLUGIN_PATH=/download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion"
   Environment="LD_LIBRARY_PATH=/download-location/kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib"
   ...
   Environment="AWS_IOT_CORE_DATA_ATS_ENDPOINT=data-account-specific-prefix.iot.aws-region.amazonaws.com"
   ExecStart=/usr/lib/jvm/java-11-amazon-corretto/bin/java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED -Dio.netty.tryReflectionSetAccessible=true -cp kvs-edge-agent.jar:libs.jar com.amazonaws.kinesisvideo.edge.controller.ControllerApp
   
   [Install]
   WantedBy=multi-user.target
   ```

   For more information about the parameters accepted by `systemd` service configuration file, see the [documentation](https://www.freedesktop.org/software/systemd/man/systemd.unit.html#%5BUnit%5D%20Section%20Options).
**Note**  
Add required the environment variables at the `...` location, as specified in [Build the Amazon Kinesis Video Streams Edge Agent](gs-build-agent.md).

1. Reload the service files to include the new service.

   Type `sudo systemctl daemon-reload`.

1. Start the service.

   Type `sudo systemctl start aws.kinesisvideo.edge-runtime-agent.service`.

1. Check the status of the Amazon Kinesis Video Streams Edge Agent service to verify that it is running.

   Type `sudo systemctl status aws.kinesisvideo.edge-runtime-agent.service`.

   The following is an example of the output that you will see.

   ```
   aws.kinesisvideo.edge-runtime-agent.service - AWS Kinesis Video Streams edge agent
        Loaded: loaded (/etc/systemd/system/aws.kinesisvideo.edge-runtime-agent.service; disabled; vendor preset: enabled)
        Active: active (running) since Thu 2023-06-08 19:15:02 UTC; 6s ago
      Main PID: 506483 (java)
         Tasks: 23 (limit: 9518)
        Memory: 77.5M
           CPU: 4.214s
        CGroup: /system.slice/aws.kinesisvideo.edge-runtime-agent.service
                └─506483 /usr/lib/jvm/java-11-amazon-corretto/bin/java -cp kvs-edge-agent.jar:libs.jar com.amazonaws.kinesisvideo.edge.controller.ControllerApp
   ```

1. Inspect the logs for any errors.

   Type `journalctl -e -u aws.kinesisvideo.edge-runtime-agent.service`.

1. Type `systemctl --help` for the full list of options to manage the process using `systemctl`.

   The following are some common commands to manage the Amazon Kinesis Video Streams Edge Agent:
   + To restart, type `sudo systemctl restart aws.kinesisvideo.edge-runtime-agent.service`.
   + To stop, type `sudo systemctl stop aws.kinesisvideo.edge-runtime-agent.service`.
   + To automatically start on every device reboot, type `sudo systemctl enable aws.kinesisvideo.edge-runtime-agent.service`.

# Deploy the Amazon Kinesis Video Streams Edge Agent to AWS IoT Greengrass
<a name="gs-edge-gg"></a>

 

This section provides a comprehensive guide to use Amazon Kinesis Video Streams with AWS IoT Greengrass. By combining these services, you can efficiently stream video from edge devices to the cloud, enabling a wide range of applications in IoT, surveillance, and more.

You'll find detailed information on:
+ Setting up your development environment
+ Creating a Kinesis video stream
+ Creating and packaging a Lambda function
+ Configuring the Kinesis Video Streams core device
+ Deploying to the core device
+ Verifying your stream

Follow these steps to deploy the Amazon Kinesis Video Streams Edge Agent to AWS IoT Greengrass to record and upload media from IP cameras.

**Topics**
+ [

# Create an Ubuntu Amazon EC2 instance
](gs-ubuntu.md)
+ [

# Set up the AWS IoT Greengrass V2 core device on the device
](gs-setup-gg.md)
+ [

# Create the Amazon Kinesis Video Streams and AWS Secrets Manager resources for your IP camera RTSP URLs
](gs-create-resources.md)
+ [

# Add permissions to the token exchange service (TES) role
](gs-add-permissions.md)
+ [

# Install the AWS IoT Greengrass Secret Manager component on the device
](gs-install-secrets-manager.md)
+ [

# Deploy the Amazon Kinesis Video Streams Edge Agent AWS IoT Greengrass component on the device
](gs-deploy-edge.md)
+ [

# Install the AWS IoT Greengrass log manager component on the device
](gs-publish-edge.md)

# Create an Ubuntu Amazon EC2 instance
<a name="gs-ubuntu"></a>

Do the following to create an Ubuntu Amazon EC2 instance.

**Create an Ubuntu Amazon EC2 instance**

1. Sign in to the AWS Management Console and open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

   Verify that the appropriate Region is selected.

1. Choose **Launch Instance**.

   Complete the following fields:
   + **Name** – Type a name for the instance.
   + **Application and OS Images (Amazon Machine Image)** – Select **Ubuntu**.
   + **Instance type** – Select **t2.large**.
   + **Key pair login** – Create your own key pair.
   + **Network settings** – Keep the default.
   + **Configure storage** – Increase the volume to 256 GiB.
   + **Advanced settings** – Keep the default.

1. Launch the instance and SSH into it.

   Do the following:

   1. Select **Instances** in the left navigation, then select the instance ID.

   1. Choose **Connect** in the top-right.

   1. Choose **SSH client** and follow the instructions on the screen.

   1. Open a terminal and navigate to the downloaded `.pem` file (likely in `~/Downloads`).

   1. The first time you follow these procedures, you will receive the message "The authenticity of host (…) can't be established." Type **yes**.

1. Install system libraries to build the Amazon Kinesis Video Streams Edge Agent onto the instance.

   ```
   wget -O- https://apt.corretto.aws/corretto.key | sudo apt-key add - 
   sudo add-apt-repository 'deb https://apt.corretto.aws stable main'
   
   sudo apt-get update
   
   sudo apt-get install -y gcc libssl-dev libcurl4-openssl-dev liblog4cplus-dev \
   libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
   gstreamer1.0-plugins-base-apps gstreamer1.0-plugins-bad \
   gstreamer1.0-plugins-good gstreamer1.0-tools \
   unzip java-11-amazon-corretto-jdk maven
   ```
**Important**  
If you see a screen telling you that some services need to be restarted, press Enter to select **Ok**.

   For more information, see [https://docs.aws.amazon.com//corretto/latest/corretto-11-ug/generic-linux-install.html](https://docs.aws.amazon.com//corretto/latest/corretto-11-ug/generic-linux-install.html).

# Set up the AWS IoT Greengrass V2 core device on the device
<a name="gs-setup-gg"></a>

Follow these procedures to install the AWS IoT Greengrass core nucleus software on the Amazon EC2 instance.

**Set up the AWS IoT Greengrass core device**

1. Sign in to the AWS Management Console, [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/).

   Verify that the appropriate Region is selected.

1. In the left navigation, select **Greengrass devices**, **Core devices**.

1. Choose **Set up one core device**.

1. Complete the steps on the screen.
   + **Step 1: Register a Greengrass core device**. Type a name for the device.
   + **Step 2: Add to a thing group to apply a continuous deployment**. Select **No group**.
   + **Step 3: Install the Greengrass Core software**. Select **Linux**.
     + **Step 3.1: Install Java on the device**

       Java is installed as part of [Create an Ubuntu Amazon EC2 instance](gs-ubuntu.md). Return to that step if you don't have Java installed yet.
     + **Step 3.2: Copy AWS credentials onto the device**

       Open the `bash/zsh` option and paste the export commands in the Amazon EC2 instance.
     + **Step 3.3: Run the installer**

       1. Copy and run the **Download the installer** and **Run the installer** commands in the Ubuntu Amazon EC2 instance.
**Note**  
The **Run the installer** command will automatically update based on the name you chose in a previous step.

       1. Make note of the token exchange service (TES) role that is created. You need it later.
**Note**  
By default, the role created is called **GreengrassV2TokenExchangeRole**.

# Create the Amazon Kinesis Video Streams and AWS Secrets Manager resources for your IP camera RTSP URLs
<a name="gs-create-resources"></a>

Follow these procedures to create the streams and secrets needed in AWS Secrets Manager. Do this step first, because you need the ARNs of the created resources in the policies.

## Create Amazon Kinesis Video Streams
<a name="gs-create-kvs"></a>

Create Amazon Kinesis Video Streams using the AWS Management Console, AWS CLI, or API.

In the AWS Management Console, open the [Amazon Kinesis Video Streams console](https://console.aws.amazon.com/kinesisvideo/home/). Choose **Video streams** in the left navigation.

For more information, see [Create an Amazon Kinesis video stream](gs-createstream.md).

## Create secrets in AWS Secrets Manager
<a name="gs-create-secrets"></a>

In the AWS Management Console, open the [AWS Secrets Manager console](https://console.aws.amazon.com/secretsmanager/landing). Choose **Secrets** in the left navigation.

Verify that the appropriate Region is selected.

1. Choose **Store a new secret**.

   1. **Step 1: Choose secret type**
      + Select **Other type of secret**.
      + In the **Key/Value Pairs** section, add a key-value pair. 

        **Key**: `MediaURI`
**Note**  
The key must be `MediaURI`. This is case-sensitive. If you enter it incorrectly, the application doesn't work.

        **Value**: `Your MediaURI`.  
**Example**  

        **Example:** `rtsp://<YourCameraIPAddress>:<YourCameraRTSPPort>/YourCameraMediaURI`.

   1. **Step 2: Configure secret**. Give this secret a name. Name it whatever you want.

   1. **Step 3: Configure rotation - optional**. Choose **Next**.

   1. **Step 4: Review**. Choose **Store**.

1. If your secret does not display immediately, select the refresh button.

   Choose the name of your secret. Make note of the **Secret ARN**.

1. Repeat this process for each MediaURI that you want to stream from.

**Note**  
The AWS network blocks some public RTSP sources. You cannot access these from within the Amazon EC2 instance or if you are running unmanaged while connected to the VPN.  
Your camera RTSP URL should stream video in h.264 format. The fragment duration must not exceed the limit mentioned in [Producer SDK quotas](limits.md#producer-sdk-limits).  
Amazon Kinesis Video Streams Edge Agent only supports video.
Run `gst-discoverer-1.0 Your RtspUrl` to make sure that your camera is reachable from your device.

Save the ARNs for all of the streams and secrets that you created. You need these for the next step.

# Add permissions to the token exchange service (TES) role
<a name="gs-add-permissions"></a>

Grant the token exchange service (TES) role to the device that assumes permissions to look at the secrets. This is necessary for the AWS Secrets Manager AWS IoT Greengrass component to work correctly.

**Add permissions to the TES role**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Choose **Roles** in the left navigation and search for the TES role that you created earlier in the process.

1. In the **Add permissions** dropdown, select **Attach policies**.

1. Choose **Create policy**.

1. Scroll down and select **Edit**.

1. In the policy editor, choose **JSON** and edit the policy.

   Replace the policy with the following:
**Note**  
Replace `arn:aws:kinesisvideo:*:*:stream/streamName1/*` and `arn:aws:kinesisvideo:*:*:stream/streamName2/*` with the ARNs for the streams that you created in a previous step.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "kinesisvideo:ListStreams"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "kinesisvideo:DescribeStream",
                   "kinesisvideo:PutMedia",
                   "kinesisvideo:TagStream",
                   "kinesisvideo:GetDataEndpoint"
               ],
               "Resource": [
                   "arn:aws:kinesisvideo:*:*:stream/streamName1/*",
                   "arn:aws:kinesisvideo:*:*:stream/streamName2/*"
               ]
           }
       ]
   }
   ```

------

1. On the **Add tags** page, choose **Next: Review**.

1. Name your policy, then choose **Create policy**.

   An example of a policy name is **KvsEdgeAccessPolicy**.

1. Close the tab and return to the tab where you were attaching a policy to the TES role.

   Choose the refresh button, then search for the newly created policy.

   Select the check box and choose **Attach policies**.

   On the next screen, you see a note that says **Policy was successfully attached to role.**

1. Create and attach another policy, this time for your secrets.

   Replace the policy with the following:
**Note**  
Replace `arn:aws:secretsmanager:*:*:secret:*` with the ARNs containing the MediaURI secrets that you created in [Create the Amazon Kinesis Video Streams and AWS Secrets Manager resources for your IP camera RTSP URLs](gs-create-resources.md).

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "secretsmanager:GetSecretValue",
               "Resource": [
                   "arn:aws:secretsmanager:*:*:secret:*",
                   "arn:aws:secretsmanager:*:*:secret:*"
               ]
           }
       ]
   }
   ```

------

1. Create and attach another policy, this time for Amazon CloudWatch metrics. Replace the policy with the following:

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "cloudwatch:PutMetricData"
               ],
               "Resource": [
                   "*"
               ]
           }
       ]
   }
   ```

------

# Install the AWS IoT Greengrass Secret Manager component on the device
<a name="gs-install-secrets-manager"></a>

The Amazon Kinesis Video Streams Edge Agent requires the AWS IoT Greengrass Secret Manager component to be installed on the device first.

**Install the Secret Manager component**

1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/). Verify that the appropriate Region is selected.

1. In the left navigation, choose **Greengrass devices**, **Deployments**.

   Choose the deployment with the same target as the thing we created in [Set up the AWS IoT Greengrass V2 core device on the device](gs-setup-gg.md).

1. In the **Actions** dropdown in the top right corner, choose **Revise**.

   In the pop-up that appears, choose **Revise deployment**.

1. Complete the following sections:
   + **Step 1: Specify target**. Choose **Next**.
   + **Step 2: Select components**.
     + Verify that the **aws.greengrass.Cli** component is selected. Do not uninstall this component.
     + Toggle the **Show only selected components** switch and search for **aws.greengrass.SecretManager**.
     + Check the box next to **aws.greengrass.SecretManager**, then choose **Next**.
   + **Step 3: Configure components**. Configure the AWS IoT Greengrass Secret Manager component to download the secrets from within the AWS IoT Greengrass environment.

     Select the **aws.greengrass.SecretManager** component, then choose **Configure component**.

     In the screen that appears, update the AWS Secrets Manager ARNs in the **Configuration to merge** box.
**Note**  
Replace `arn:aws:secretsmanager:*:*:secret:*` with the ARNs of the secrets that you created in [Create the Amazon Kinesis Video Streams and AWS Secrets Manager resources for your IP camera RTSP URLs](gs-create-resources.md).

     ```
     {
      "cloudSecrets": [
           {
             "arn": "arn:aws:secretsmanager:*:*:secret:*"
           },
           {
             "arn": "arn:aws:secretsmanager:*:*:secret:*"
           }
         ]
     }
     ```
**Note**  
`cloudSecrets` is a list of objects with the key `arn`. For more information, see the [Secret manager configuration](https://docs.aws.amazon.com//greengrass/v2/developerguide/secret-manager-component.html#secret-manager-component-configuration) section in the AWS IoT Greengrass Version 2 Developer Guide. 

     When you're done, select **Confirm**, then choose **Next**.
   + **Step 4: Configure advanced settings**. Select **Next**.
   + **Step 5: Review**. Select **Deploy**.

1. Confirm that the AWS Secrets Manager component and permissions were installed correctly.

   On the Ubuntu Amazon EC2 instance, type `sudo /greengrass/v2/bin/greengrass-cli component details --name aws.greengrass.SecretManager` to verify that the component received the updated configuration.

1. Inspect the AWS IoT Greengrass core logs.

   Type `sudo less /greengrass/v2/logs/greengrass.log`.

   Review for deployment errors. 

   If there was an error, revise the deployment to remove the `aws.greengrass.SecretManager` component.

   Type `sudo service greengrass restart` to restart the AWS IoT Greengrass core service.

   If the deployment error was related to missing permissions, review the [Add permissions to the token exchange service (TES) role](gs-add-permissions.md) section to make sure that the TES role has the proper permissions. Then, repeat this section.

1. **Update the secrets on the AWS IoT Greengrass Secret Manager component**
**Important**  
The AWS IoT Greengrass Secret Manager component fetches and caches secrets only when the deployment is updated.

   In order to update the secrets on the AWS IoT Greengrass Secret Manager component, follow the preceding steps 1–6, with the following change.

   **Step 3: Configure components**. Configure the AWS IoT Greengrass Secret Manager component to download the secrets from within the AWS IoT Greengrass environment.

   Select the **aws.greengrass.SecretManager** component, then choose **Configure component**.

   In the screen that appears, paste `[""]` in the **Reset paths** box, and update the AWS Secrets Manager ARNs in the **Configuration to merge** box.

   For more information, see [Reset updates](https://docs.aws.amazon.com//greengrass/v2/developerguide/update-component-configurations.html#reset-configuration-update).

# Deploy the Amazon Kinesis Video Streams Edge Agent AWS IoT Greengrass component on the device
<a name="gs-deploy-edge"></a>

Do the following to deploy the Amazon Kinesis Video Streams Edge Agent AWS IoT Greengrass component on the device:

**Deploy the component**

1. Download the `tar` file using the provided link.

   If you completed the Amazon Kinesis Video Streams Edge Agent interest form, check your email for the download link. If you haven't completed the form, complete it [here](https://pages.awscloud.com/GLOBAL-launch-DL-KVS-Edge-2023-learn.html).

1. Verify the checksum.

1. Extract the binaries and jar in your device.

   Type: `tar -xvf kvs-edge-agent.tar.gz`.

   After extraction, your folder structure will look like the following:

   ```
   kvs-edge-agent/LICENSE
   kvs-edge-agent/THIRD-PARTY-LICENSES
   kvs-edge-agent/pom.xml
   kvs-edge-agent/KvsEdgeComponent
   kvs-edge-agent/KvsEdgeComponent/recipes
   kvs-edge-agent/KvsEdgeComponent/recipes/recipe.yaml
   kvs-edge-agent/KvsEdgeComponent/artifacts
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/edge_log_config                   
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/kvs-edge-agent.jar
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/libgstkvssink.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/libIngestorPipelineJNI.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib/libcproducer.so
   kvs-edge-agent/KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/lib/libKinesisVideoProducer.so
   ```
**Note**  
The release folder name should be set up in a way that reflects the latest binary release number. For example, a 1.0.0 release will have the folder name set as 1.0.0. 

1. Build the dependencies jar. 
**Note**  
The jar included with the kvs-edge-agent.tar.gz does not have the dependencies. Use the following steps to build those libraries.

   Navigate to the `kvs-edge-agent` folder that contains `pom.xml`. 

   Type `mvn clean package`.

   This will generate a jar file containing the dependencies the Amazon Kinesis Video Streams Edge Agent requires at `kvs-edge-agent/target/libs.jar`.

1. Place the libs.jar into the folder that contains the component’s artifacts.

   Type `mv ./target/libs.jar ./KvsEdgeComponent/artifacts/aws.kinesisvideo.KvsEdgeComponent/EdgeAgentVersion/`.

1. **Optional.** Configure properties. The Amazon Kinesis Video Streams Edge Agent accepts the following environment variables in AWS IoT Greengrass mode:    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-deploy-edge.html)

   Open `kvs-edge-agent/KvsEdgeComponent/recipes/recipe.yaml` and modify the run script to add any of the preceding environment variables.
**Important**  
Make sure that the modified run script doesn't contain any **tab** characters. The AWS IoT Greengrass core software won't be able to read the recipe.

1. Deploy the Amazon Kinesis Video Streams Edge Agent AWS IoT Greengrass component. 

   Type:

   ```
   sudo /greengrass/v2/bin/greengrass-cli deployment create \
     --recipeDir <download location>/kvs-edge-agent/KvsEdgeComponent/recipes/ \
     --artifactDir <download location>/kvs-edge-agent/KvsEdgeComponent/artifacts/ \
     --merge "aws.kinesisvideo.KvsEdgeComponent=EdgeAgentVersion"
   ```

   For additional information, see the following sections in the *AWS IoT Greengrass Version 2 Developer Guide*:
   + [AWS IoT Greengrass CLI commands](https://docs.aws.amazon.com//greengrass/v2/developerguide/gg-cli-reference.html)
   + [Deploy AWS IoT Greengrass components to devices](https://docs.aws.amazon.com//greengrass/v2/developerguide/manage-deployments.html)

1. Send configurations to the application using the AWS CLI.

   1. Create a new file, `example-edge-configuration.json`. 

      Paste the following code into the file. This is a sample configuration that records daily from 9:00:00 AM to 4:59:59 PM (according to the system time on your AWS IoT device). It also uploads the recorded media daily from 7:00:00 PM to 9:59:59 PM.

      For more information, see [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md).

      ```
      {
          "StreamARN": "arn:aws:kinesisvideo:your-region:your-account-id:stream/your-stream/0123456789012",
          "EdgeConfig": {
              "HubDeviceArn": "arn:aws:iot:your-region:your-account-id:thing/kvs-edge-agent-demo",
              "RecorderConfig": {
                  "MediaSourceConfig": {
                      "MediaUriSecretArn": "arn:aws:secretsmanager:your-region:your-account-id:secret:your-secret-dRbHJQ",
                      "MediaUriType": "RTSP_URI"
                  },
                  "ScheduleConfig": {
                      "ScheduleExpression": "0 0 9,10,11,12,13,14,15,16 ? * * *",
                      "DurationInSeconds": 3599
                  }
              },
              "UploaderConfig": {
                  "ScheduleConfig": {
                      "ScheduleExpression": "0 0 19,20,21 ? * * *",
                      "DurationInSeconds": 3599
                  }
              },
              "DeletionConfig": {
                  "EdgeRetentionInHours": 15,
                  "LocalSizeConfig": {
                    "MaxLocalMediaSizeInMB": 2800,
                    "StrategyOnFullSize": "DELETE_OLDEST_MEDIA"
                  },
                  "DeleteAfterUpload": true
              }
          }
      }
      ```

   1. Type the following in the AWS CLI to send the file to the Amazon Kinesis Video Streams Edge Agent:

      ```
      aws kinesisvideo start-edge-configuration-update --cli-input-json "file://example-edge-configuration.json"
      ```

1. Repeat the previous step for each stream for the Amazon Kinesis Video Streams Edge Agent.

# Install the AWS IoT Greengrass log manager component on the device
<a name="gs-publish-edge"></a>

**Note**  
Be aware of the [CloudWatch quotas](https://docs.aws.amazon.com//AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html).

Follow these procedures to configure the Amazon Kinesis Video Streams Edge Agent logs to automatically upload to CloudWatch using the AWS IoT Greengrass log manager component. This is an optional step.

**Install the AWS IoT Greengrass log manager component**

1. Confirm that the AWS IoT Greengrass device role has the [appropriate permissions](https://docs.aws.amazon.com//greengrass/v2/developerguide/log-manager-component.html#log-manager-component-requirements).

   1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. Click **Roles** in the left navigation.

   1. Choose the name of the TES role created in [Set up the AWS IoT Greengrass V2 core device on the device](gs-setup-gg.md). Use the search bar if necessary.

   1. Select the `GreengrassV2TokenExchangeRoleAccess` policy.

   1. Select the JSON tab and verify that the policy looks like the following:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "logs:CreateLogGroup",
                      "logs:CreateLogStream",
                      "logs:PutLogEvents",
                      "logs:DescribeLogStreams",
                      "s3:GetBucketLocation"
                  ],
                  "Resource": "*"
              }
          ]
      }
      ```

------

   1. If the `GreengrassV2TokenExchangeRoleAccess` policy doesn't exist, or if some required permissions are missing, create a new IAM policy with these permissions and attach it to the TES role created in [Set up the AWS IoT Greengrass V2 core device on the device](gs-setup-gg.md).

1. Sign in to the AWS Management Console and open the AWS IoT Core console at [https://console.aws.amazon.com/iot/](https://console.aws.amazon.com/iot/). Verify that the appropriate Region is selected.

1. In the left navigation, choose **Greengrass devices**, **Deployments**.

   Choose the deployment with the same target as the thing you created in [Set up the AWS IoT Greengrass V2 core device on the device](gs-setup-gg.md).

1. In the top right corner, select **Actions**, then choose **Revise**.

   In the pop-up that appears, choose **Revise deployment**.

1. Complete the following sections:

   1. **Step 1: Specify target.** Choose **Next**.

   1. **Step 2: Select components.**

      1. Verify that the **aws.greengrass.Cli** component and **aws.greengrass.SecretManager** components are still selected.
**Important**  
Don't uninstall these components.

      1. Toggle the **Show only selected components** switch and search for **aws.greengrass.LogManager**.

      1. Select the box next to **aws.greengrass.LogManager**, then choose **Next**.

   1. **Step 3: Configure components.** Configure the AWS IoT Greengrass log manager component to upload the logs generated by the Amazon Kinesis Video Streams Edge Agent.

      Select the **aws.greengrass.LogManager** component, then choose **Configure component**.

      In the screen that appears, paste the following log manager configuration in the **Configuration to merge** box.

      ```
      {
          "logsUploaderConfiguration": {
              "componentLogsConfigurationMap": {
                  "aws.kinesisvideo.KvsEdgeComponent/java_kvs.log": {
                      "diskSpaceLimit": "100",
                      "diskSpaceLimitUnit": "MB",
                      "logFileDirectoryPath": "/greengrass/v2/work/aws.kinesisvideo.KvsEdgeComponent/log",
                      "logFileRegex": "java_kvs.log\\w*"
                  },
                  "aws.kinesisvideo.KvsEdgeComponent/cpp_kvs_edge.log": {
                      "diskSpaceLimit": "100",
                      "diskSpaceLimitUnit": "MB",
                      "logFileDirectoryPath": "/greengrass/v2/work/aws.kinesisvideo.KvsEdgeComponent/log",
                      "logFileRegex": "cpp_kvs_edge.log\\w*"
                  },
                  "aws.kinesisvideo.KvsEdgeComponent/cpp_kvssink.log": {
                      "diskSpaceLimit": "100",
                      "diskSpaceLimitUnit": "MB",
                      "logFileDirectoryPath": "/greengrass/v2/work/aws.kinesisvideo.KvsEdgeComponent/log",
                      "logFileRegex": "cpp_kvssink.log\\w*"
                  },
                  "aws.kinesisvideo.KvsEdgeComponent/cpp_kvs_streams.log": {
                      "diskSpaceLimit": "100",
                      "diskSpaceLimitUnit": "MB",
                      "logFileDirectoryPath": "/greengrass/v2/work/aws.kinesisvideo.KvsEdgeComponent/log",
                      "logFileRegex": "cpp_kvs_streams.log\\w*"
                  }
              }
          },
          "periodicUploadIntervalSec": "1"
      }
      ```
**Important**  
The `logFileDirectoryPath` in the preceding configuration assumes that the default logging output location is used.
**Note**  
For more information about each of the parameters for the log manager configuration, see the [Log manager](https://docs.aws.amazon.com//greengrass/v2/developerguide/log-manager-component.html#log-manager-component-configuration) section of the AWS IoT Greengrass Version 2 Developer Guide.

      Once you finish, select **Confirm**, then choose **Next**.

   1. **Step 4: Configure advanced settings.** Select **Next**.

   1. **Step 5: Review.** Select **Deploy**.

1. Confirm that the AWS log manager component and permissions were installed correctly.

1. On the Ubuntu Amazon EC2 instance, type `sudo /greengrass/v2/bin/greengrass-cli component details --name aws.greengrass.LogManager` to verify the component received the updated configuration.

1. Inspect the AWS IoT Greengrass core logs.

   Type `sudo less /greengrass/v2/logs/greengrass.log`.

   Review for deployment errors.

   If there was an error, revise the deployment to remove the `aws.greengrass.LogManager` component.

   Type `sudo service greengrass restart` to restart the AWS IoT Greengrass core service.

   If the deployment error was related to missing permissions, review [Add permissions to the token exchange service (TES) role](gs-add-permissions.md) to make sure that the TES role has proper permissions. Then, repeat this section.

# Amazon Kinesis Video Streams Edge Agent FAQ
<a name="edge-faq"></a>

The following are some common questions for the Amazon Kinesis Video Streams Edge Agent service.

## What operating systems does Amazon Kinesis Video Streams Edge Agent support?
<a name="edge-faq-os"></a>

Amazon Kinesis Video Streams Edge Agent currently supports the following operating systems:

**Ubuntu**
+ 22.x
  + AMD64
+ 18.x
  + ARM

**AL2**
+ amzn2
  + AMD64 amazonlinux:2.0.20210219.0-amd64 (Snowball)

## Does the Amazon Kinesis Video Streams Edge Agent support H.265 media?
<a name="edge-faq-h265"></a>

Amazon Kinesis Video Streams Edge Agent only supports H.264 elementary streams.

## Does the Amazon Kinesis Video Streams Edge Agent work in AL2?
<a name="edge-faq-al2"></a>

Yes.

## How can I run multiple streams within the AWS IoT thing or device?
<a name="edge-faq-multiple-streams"></a>

Send another [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md) to the same `HubDeviceArn`, but different Amazon Kinesis Video Streams/AWS Secrets Manager ARNs.

## How can I edit a `StartEdgeConfigurationUpdate` after it has been sent?
<a name="edge-faq-multiple-edit"></a>

Send an updated [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md)to the same `HubDeviceArn` with the same Amazon Kinesis Video Streams ARN. When the application receives the message from Amazon Kinesis Video Streams, it overrides the previous configuration for that stream. Changes will take place then.

## Do you have any examples of common `ScheduleConfigs`?
<a name="edge-faq-common-config"></a>

The Amazon Kinesis Video Streams Edge Agent uses the system time of the device that it's running on.


| Description | ScheduleExpression | DurationInSeconds | 
| --- |--- |--- |
|  24/7 recording, hourly uploading  | (null ScheduleConfig) | 
|  9:00:00 AM - 4:59:59 PM every day  | 0 0 9-16 \$1 \$1 ? \$1 | 3599 | 
| 9:00:00 AM - 4:59:59 PM weekdays | 0 0 9-16 ? \$1 2-6 \$1 |  3599  | 
|  `0 0 9-16 ? * 2,3,4,5,6 *`  |  3599  | 
|  `0 0 9-16 ? * MON-FRI *`  |  3599  | 
|  `0 0 9-16 ? * MON,TUE,WED,THU,FRI *`  |  3599  | 
|  9:00:00 AM - 4:59:59 PM weekends  |  `0 0 9-16 ? * SAT,SUN *`  |  3599  | 
|  10:00:00 PM - 11:59:59 PM weekdays  |  `0 0 22,23 ? * MON-FRI *`  |  3599  | 
|  9:00:00 AM - 10:00:00 AM every day  |  `0 0 9 * * ? *`  |  3600  | 
|  4:00:00 PM - 5:59:59 PM every day  |  `0 0 16-17 * * ? *`  |  3599  | 

For more examples, see the [Quartz documentation](https://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html).

## Is there a maximum stream limit?
<a name="edge-faq-stream-limits"></a>

The Amazon Kinesis Video Streams Edge Agent currently has a hard limit of 16 streams per device. Use the [DeleteEdgeConfiguration](API_DeleteEdgeConfiguration.md) API to delete streams from a device. Updating a configuration for the same stream using the [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md) does not increase the device’s stream count.

## How do I restart a job that has errored out?
<a name="edge-faq-restat"></a>

If an error is encountered, the Amazon Kinesis Video Streams Edge Agent will attempt to restart the job. However, with some errors (such as configuration errors), you must manually restart the job.

To determine which jobs need to be restarted manually, see the **FatalError** metric in [Monitor the Amazon Kinesis Video Streams Edge Agent with CloudWatch](monitoring-edge-cloudwatch.md).

Resend the [StartEdgeConfigurationUpdate](API_StartEdgeConfigurationUpdate.md) to restart the job for the stream.

## How do I monitor the health of my Amazon Kinesis Video Streams Edge Agent?
<a name="edge-faq-monitoring"></a>

For more information, see [Monitor the Amazon Kinesis Video Streams Edge Agent with CloudWatch](monitoring-edge-cloudwatch.md).