terraform deploy on ECS (#27)

This commit is contained in:
David Zhao
2021-02-28 22:28:17 -08:00
committed by GitHub
parent 7b93e661f0
commit f7af7607b9
17 changed files with 444 additions and 21 deletions
+2
View File
@@ -0,0 +1,2 @@
.terraform*
terraform.tfstate*
+47
View File
@@ -0,0 +1,47 @@
locals {
livekit_config = {
port = var.http_port
rtc = {
port_range_start = var.udp_port_start
port_range_end = var.udp_port_end
}
development = true
keys = var.api_keys
redis = {
address = var.redis_address
}
}
port_mapping = concat([{
containerPort = var.http_port
protocol = "tcp"
}], [
for p in range(var.udp_port_start, var.udp_port_end): {
containerPort = p
protocol = "udp"
}
])
task_config = [{
name = "livekit"
image = "livekit/livekit-server:networktest"
cpu = 1024
memory = 1024
essential = true
environment = [
{
name = "LIVEKIT_CONFIG"
value = yamlencode(local.livekit_config)
}
]
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-region" = var.region
"awslogs-group" = "livekit"
"awslogs-stream-prefix" = var.name
}
},
portMappings = local.port_mapping
}]
}
+26
View File
@@ -0,0 +1,26 @@
data "aws_ami" "ecs_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn-ami-*-amazon-ecs-optimized"]
}
}
module "app_ecs_cluster" {
source = "trussworks/ecs-cluster/aws"
name = "livekit"
environment = var.name
image_id = data.aws_ami.ecs_ami.image_id
instance_type = var.instance_type
vpc_id = var.vpc_id
subnet_ids = var.subnet_ids
security_group_ids = concat(var.security_groups, [aws_security_group.main.id])
desired_capacity = var.nodes
max_size = var.max_nodes
min_size = var.min_nodes
}
+42
View File
@@ -0,0 +1,42 @@
resource "aws_ecs_task_definition" "livekit" {
family = "service"
container_definitions = jsonencode(local.task_config)
network_mode = "host"
execution_role_arn = aws_iam_role.ecs_role.arn
}
resource "aws_ecs_service" "livekit" {
name = "livekit-${var.name}"
cluster = module.app_ecs_cluster.ecs_cluster_arn
task_definition = aws_ecs_task_definition.livekit.arn
desired_count = var.nodes
force_new_deployment = true
launch_type = "EC2"
placement_constraints {
// one instance per node
type = "distinctInstance"
}
ordered_placement_strategy {
type = "spread"
field = "instanceId"
}
// load balancer for TCP port
load_balancer {
target_group_arn = aws_lb_target_group.main.arn
container_name = "livekit"
container_port = var.http_port
}
// lifecycle {
// ignore_changes = [desired_count]
// }
}
resource "aws_cloudwatch_log_group" "livekit" {
name = "livekit"
retention_in_days = 7
}
+42
View File
@@ -0,0 +1,42 @@
# name of the livekit cluster, resources will be called `livekit-${name}`
name = "demo"
# type of instance to use
instance_type = "t3.small"
# limits to the number of nodes to run
max_nodes = 2
# minimum number of nodes to run
min_nodes = 1
# initially use this number of nodes
nodes = 1
# VPC to create the cluster in
vpc_id = ""
# List of subnet IDs to create the cluster in
subnet_ids = []
# region to use, must match AWS_REGION environment variable
region = "us-east-1"
# additional security groups to attach the cluster to.
# include security group of the redis instance to allow access
security_groups = [
""
]
# Livekit configuration
# address and port to redis instance
redis_address = ""
# list of API keys and secrets
api_keys = {
"key" = "secret"
}
udp_port_start = 9000
udp_port_end = 9100
+26
View File
@@ -0,0 +1,26 @@
// role for ECS execution
resource "aws_iam_role" "ecs_role" {
name = "livekit-${var.name}-execution"
assume_role_policy = <<ROLE_POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
ROLE_POLICY
}
resource "aws_iam_role_policy_attachment" "ecs_role-attach" {
role = aws_iam_role.ecs_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
+31
View File
@@ -0,0 +1,31 @@
// configure target group
resource "aws_lb_target_group" "main" {
name = "livekit-${var.name}"
port = 80
protocol = "HTTP"
vpc_id = data.aws_vpc.main.id
}
resource "aws_lb" "main" {
name = "livekit-${var.name}"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.lb.id]
subnets = var.subnet_ids
}
// TODO: HTTPS
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.main.arn
port = "80"
protocol = "HTTP"
// ssl_policy = "ELBSecurityPolicy-2016-08"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.main.arn
}
}
+89
View File
@@ -0,0 +1,89 @@
#
# The following variables need to be set:
# AWS_ACCESS_KEY_ID (or reads from ~/.aws/credentials)
# AWS_SECRET_ACCESS_KEY (or reads from ~/.aws/credentials)
# AWS_REGION
#
provider "aws" {
}
# name of the cluster
variable "name" {
type = string
}
# type of instance to deploy on
variable "instance_type" {
type = string
default = "t3.small"
}
variable "nodes" {
type = number
default = 1
}
variable "min_nodes" {
type = number
default = 1
}
variable "max_nodes" {
type = number
}
variable "region" {
type = string
}
# target CPU utilization
variable "target_cluster_utilization" {
type = number
default = 90
}
# VPC to launch the cluster in
variable "vpc_id" {
type = string
}
# launch in the following subnet ids
variable "subnet_ids" {
type = list(string)
}
# additional security groups to associate with
# i.e. security group of the Redis instance
variable "security_groups" {
type = list(string)
default = []
}
# livekit config
variable "http_port" {
type = number
default = 7880
}
variable "udp_port_start" {
type = number
default = 9000
}
variable "udp_port_end" {
type = number
default = 9100
}
variable "api_keys" {
type = map(string)
}
variable "redis_address" {
type = string
default = ""
}
output "livekit_lb" {
value = aws_lb.main.dns_name
}
+69
View File
@@ -0,0 +1,69 @@
data "aws_vpc" "main" {
id = var.vpc_id
}
resource "aws_security_group" "main" {
name = "livekit-${var.name}"
description = "Allow LiveKit inbound TCP and UDP traffic"
vpc_id = data.aws_vpc.main.id
ingress {
description = "UDP port for ICE"
from_port = var.udp_port_start
to_port = var.udp_port_end
protocol = "udp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "internal traffic"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = [data.aws_vpc.main.cidr_block]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "livekit"
}
}
resource "aws_security_group" "lb" {
name = "livekit-${var.name}-lb"
description = "Load balancer traffic"
vpc_id = data.aws_vpc.main.id
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "livekit"
}
}
+7
View File
@@ -0,0 +1,7 @@
# Redis Terraform
Creates a Redis elasticache cluster. Run it like the following
`AWS_REGION=<region> terraform apply`
Enter a name for the cluster, as well as the subnet ids that Redis should be created in
+33
View File
@@ -0,0 +1,33 @@
#
# The following variables need to be set:
# AWS_ACCESS_KEY_ID (or reads from ~/.aws/credentials)
# AWS_SECRET_ACCESS_KEY (or reads from ~/.aws/credentials)
# AWS_REGION
#
provider "aws" {
}
# type of instance to deploy on
# see: https://aws.amazon.com/elasticache/pricing/
variable "instance_type" {
type = string
default = "cache.t3.micro"
}
# name of the cluster
variable "cluster_id" {
type = string
}
# launch in the following subnet ids
variable "subnet_ids" {
type = list(string)
}
variable "security_groups" {
type = list(string)
}
output "address" {
value = "${aws_elasticache_cluster.main.cache_nodes[0].address}:${aws_elasticache_cluster.main.cache_nodes[0].port}"
}
+18
View File
@@ -0,0 +1,18 @@
resource "aws_elasticache_cluster" "main" {
cluster_id = var.cluster_id
engine = "redis"
node_type = var.instance_type
num_cache_nodes = 1
parameter_group_name = "default.redis6.x"
# strangely terraform requires you to change to a specific version when
# modifying the resource.
engine_version = "6.x"
subnet_group_name = aws_elasticache_subnet_group.main.name
security_group_ids = var.security_groups
port = 6379
}
resource "aws_elasticache_subnet_group" "main" {
name = var.cluster_id
subnet_ids = var.subnet_ids
}
+1
View File
@@ -4,6 +4,7 @@ go 1.15
require (
github.com/bep/debounce v1.2.0
github.com/fatih/hclfmt v0.0.0-20181010234132-374cd0fd2a55 // indirect
github.com/go-redis/redis/v8 v8.4.8
github.com/golang/protobuf v1.4.3
github.com/google/wire v0.4.0
+3
View File
@@ -99,6 +99,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/hclfmt v0.0.0-20181010234132-374cd0fd2a55 h1:FucIiafNzNNvdfp8BzKYDPXMCAhJaBsNjqiPdPJcieA=
github.com/fatih/hclfmt v0.0.0-20181010234132-374cd0fd2a55/go.mod h1:O9mb/7h6jenxXEB9aeff3D8kXpoBKCU2ASH1OflMFjM=
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
@@ -208,6 +210,7 @@ github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
+2 -2
View File
@@ -51,8 +51,8 @@ func NewConfig(confString string) (*Config, error) {
conf := &Config{
Port: 7880,
RTC: RTCConfig{
ICEPortRangeStart: 8000,
ICEPortRangeEnd: 10000,
ICEPortRangeStart: 9000,
ICEPortRangeEnd: 9200,
StunServers: []string{
"stun.l.google.com:19302",
"stun1.l.google.com:19302",
+1 -19
View File
@@ -55,6 +55,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// require a claim
if claims == nil || claims.Video == nil {
handleError(w, http.StatusUnauthorized, rtc.ErrPermissionDenied.Error())
return
}
identity := claims.Identity
@@ -170,22 +171,3 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
}
type errStruct struct {
StatusCode int `json:"statusCode"`
Error string `json:"error"`
Message string `json:"message,omitempty"`
}
func jsonError(code int, error ...string) errStruct {
es := errStruct{
StatusCode: code,
}
if len(error) > 0 {
es.Error = error[0]
}
if len(error) > 1 {
es.Message = error[1]
}
return es
}
+5
View File
@@ -59,6 +59,7 @@ func NewLivekitServer(conf *config.Config,
mux := http.NewServeMux()
mux.Handle(s.roomServer.PathPrefix(), s.roomServer)
mux.Handle("/rtc", rtcService)
mux.HandleFunc("/", s.healthCheck)
s.httpServer = &http.Server{
Addr: fmt.Sprintf(":%d", conf.Port),
@@ -141,6 +142,10 @@ func (s *LivekitServer) Stop() {
}
}
func (s *LivekitServer) healthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// worker to perform periodic tasks per node
func (s *LivekitServer) backgroundWorker() {
roomTicker := time.NewTicker(30 * time.Second)