---
title: "Quick-Start-Guide"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Quick-Start-Guide}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r, include = FALSE}
if(FALSE){
  knitr::knit("inst/quick-start-guide.raw.Rmd", output = "vignettes/quick-start-guide.Rmd")
knitr::knit("vignettes/quick-start-guide.Rmd", output = "README.md")
}

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(aws.ecx)
# aws.ecx::aws_set_retry_time(10)
# aws.ecx::aws_set_print_on_error(FALSE)
```

`r badger::badge_cran_release(color = "green")`
`r badger::badge_github_version(color = "orange")`
`r badger::badge_cran_download(color = "blue")`

# Introduction
This package aims to provide the functions for communicating with Amazon Web Services(AWS) Elastic Container Service(ECS) using AWS REST APIs. The ECS functions start with the prefix `ecs_` and EC2 functions start with `ec2_`. The general-purpose functions have the prefix `aws_`.

Since there are above 400 EC2 APIs, it is not possible for the unit test to cover all use cases. If you see any problems when using the package, please consider to submit the issue to [GitHub issue][GitHub issue].

[GitHub issue]: https://github.com/Jiefei-Wang/aws.ecx/issues

# Authentication
Credentials must be provided for using the package. The package uses `access key id` and `secret access key` to authenticate with AWS. See [AWS user guide][AWS user guide] for the information about how to obtain them from AWS console. The credentials can be set via `aws_set_credentials()`.
```{r}
aws_set_credentials()
```
The function `aws_set_credentials` sets both the credentials and the region of the AWS service. You can either explicitly provide them by the function arguments or rely on the locator to automatically find your credentials. There are many ways to locate the credentials but the most important methods are as follow(sorted by the search order):

1. environment variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`, and `AWS_SESSION_TOKEN`

2. a profile in a global credentials dot file in a location set by `AWS_SHARED_CREDENTIALS_FILE` or defaulting typically to `"~/.aws/credentials"` (or another OS-specific location), using the profile specified by `AWS_PROFILE`

Users can find the details on how the credentials are located from `?aws.signature::locate_credentials`. A list of AWS regions can be found by calling the function `aws_list_regions`. 
```{r}
aws_list_regions()
```


[AWS user guide]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html

# Call the functions
Calling the EC2 or ECS function is simple, for example, you can list all ECS clusters via
```{r}
ecs_list_clusters()
```
The original EC2 and ECS APIs accept the request parameter via the query parameter or header and return the result by JSON or XML text in the REST request. The package provides a unified way to call both APIs. The request parameters can be given by the function arguments and the result is returned in a list format. If possible, the package will try to simplify the result and return a simple character vector. It will also handle the `nextToken` parameter in the REST APIs and collect the full result in a single function call. This default behavior can be turned off by providing the parameter `simplefy = FALSE`.

Each EC2 or ECS API has its own document. For example, you can find the help page of `ecs_list_clusters` via `?ecs_list_clusters`. The full description of the APIs can be found at [AWS Documentation][AWS Documentation].

[AWS Documentation]: https://docs.aws.amazon.com/

## A note for the AWS EC2 functions
### Array

While the AWS Documentation is very helpful in finding the API use cases. There are some inconsistencies between the AWS Documentation and the package functions. To be more specific, the array type parameter will get a special treatment in this package. For example, here is an example for `DescribeVpcs` from the [AWS Documentation][example] which describes the specified VPCs
```
https://ec2.amazonaws.com/?Action=DescribeVpcs
&VpcId.1=vpc-081ec835f3EXAMPLE
&vpcId.2=vpc-0ee975135dEXAMPLE
&VpcId.3=vpc-06e4ab6c6cEXAMPLE
```
The `VpcId` is so-called array object in the AWS Documentation. The package uses a vector or a list to represent the array object. The dot `.` in the array can be explained as `[[` and anything followed by the dot can be explained as the index. Therefore, the corresponding R expression for `VpcId` is
```{r}
## VpcId can also be a character vector
VpcId <- list()
VpcId[[1]] <- "vpc-081ec835f3EXAMPLE"
VpcId[[2]] <- "vpc-0ee975135dEXAMPLE"
VpcId[[3]] <- "vpc-06e4ab6c6cEXAMPLE"

VpcId
```
and the same request in R can be made by
```
ec2_describe_vpcs(VpcId = VpcId)
```
Internally, `VpcId` will be converted to an array object using the function `list_to_array`, e.g.
```{r}
## The first argument is the parameter prefix
## The second argument should be a (named) vector or list
list_to_array("VpcId", VpcId)
```
Just like list can be nested, the array object can be nested as well. For example, if we have a `tags` array like
```
tags.1.name = name-example
tags.1.value.1 = value-example1
tags.1.value.2 = value-example2
```
Using the array rule we mentioned above, the corresponding R expression is
```{r}
tags <- list()
tags[[1]] <- list()
tags[[1]][["name"]] <- "name-example"
tags[[1]][["value"]] <- list()
tags[[1]][["value"]][[1]] <- "value-example1"
tags[[1]][["value"]][[2]] <- "value-example2"

tags
```
We can verify the request parameter using `list_to_array`
```{r}
list_to_array("tags", tags)
```

### Filter
A even more aggressive change can be found on the `Filter` parameter. Here is an example of describing VPCs which satisfy some specific conditions from the [AWS Documentation][example]
```
https://ec2.amazonaws.com/?Action=DescribeVpcs
&Filter.1.Name=dhcp-options-id
&Filter.1.Value.1=dopt-7a8b9c2d
&Filter.1.Value.2=dopt-2b2a3d3c
&Filter.2.Name=state
&Filter.2.Value.1=available
```
The `Filter` parameter is, of course, an array object in AWS documentation. However, it is clearly redundant to specify the filter's name and value separately. Therefore, the package allows users to provide the filter as a named list. The same request in R can be given by
```
ec2_describe_vpcs(
  Filter = list(
    `dhcp-options-id` = c("dopt-7a8b9c2d", "dopt-2b2a3d3c"),
    state="available"
  )
)
```
The `Filter` parameter will be converted into a list object which meets the AWS filter requirement. If you are unsure about whether you has specified the correct filter, you can check the converted filter values via
```{R}
filter <- list(
    `dhcp-options-id` = c("dopt-7a8b9c2d", "dopt-2b2a3d3c"),
    state="available"
  )
list_to_filter(filter)
```

[example]: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html


## A note for the AWS ECS functions
The AWS ECS API uses JSON format to assemble the request parameter. Therefore, the ECS functions will call `rjson::toJSON` to convert the request parameters into JSON objects. If you are not sure if you use the parameter correctly, you can manually run `rjson::toJSON` and compare the result with the example provided in AWS documentation. For example, the request syntax for the `tags` parameter in `CreateCluster` API is 
```
"tags": [ 
         { 
            "key": "string",
            "value": "string"
         }
      ]
```
The corresponding R format should be
```{r}
tags <- list(
  c(key = "key", value = "value")
  )
```
You can verify it by
```{r}
cat(rjson::toJSON(tags, indent = 1))
```

# Package settings
The package handles the network issue via the parameter `retry_time`, `print_on_error` and `network_timeout`.

```{r}
aws_get_retry_time()
aws_get_print_on_error()
aws_get_network_timeout()
```
`retry_time` determines the number of time the function will retry when network error occurs before throwing an error. If `print_on_error` is set to `False`, no message will be given when the network error has occurred and the package will silently resend the REST request. `network_timeout` decides how long the function will wait before it fails. They can be changed via the corresponding setters(e.g. `aws_set_retry_time`). You can also temporary alter the setting by providing the package setting as a parameter in the EC2 or ECS function.

# Warning
Not all AWS APIs are idempotent, especially for the functions that need to allocate resources on AWS(e.g. `ecs_start_task`). If you plan to use the AWS function in your package, special handle for the network issue is required for the non-idempotent API to avoid a double allocation. 


# Session info
```{r}
sessionInfo()
```

# future work
1. Convert parameter type if it does not meet the AWS type requirement. Done

2. add link to the function documentation



