-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
206 lines (164 loc) · 7.19 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import os
import time
import boto3
import digitalocean
import paramiko
import requests
from Crypto.PublicKey import RSA
from retry import retry
DIGITALOCEAN_API_TOKEN = os.getenv("DIGITALOCEAN_API_TOKEN")
DIGITALOCEAN_REGION_SLUG = os.getenv("DIGITALOCEAN_REGION_SLUG")
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
SLACK_INCOMING_WEBHOOK_URL = os.getenv("SLACK_INCOMING_WEBHOOK_URL")
MINECRAFT_LAMBDA_FUNCTION_TOKEN = os.getenv("MINECRAFT_LAMBDA_FUNCTION_TOKEN")
def lambda_handler(event, context):
if event["token"] != MINECRAFT_LAMBDA_FUNCTION_TOKEN:
return {"message": ":no_good: Invalid token. Your request body is: " + str(event)}
try:
action = event["text"]
if action == "create":
_slack_notify(":muscle: Creating server...")
message = create_server()
_slack_notify(message)
elif action == "upload":
_slack_notify(":muscle: Uploading world data...")
message = upload_world()
_slack_notify(message)
elif action == "destroy":
_slack_notify(":muscle: Uploading world data...")
message = upload_world()
_slack_notify(message)
_slack_notify(":muscle: Destroying server...")
message = destroy_server()
_slack_notify(message)
elif action == "destroy_without_saving":
_slack_notify(":muscle: Destroying server...")
message = destroy_server()
_slack_notify(message)
else:
message = "Invalid action: " + action
_slack_notify(message)
except Exception as e:
message = ":no_good: Error: " + e.message
_slack_notify(message)
return {"message": message}
def create_server():
private_key = _get_ssh_private_key()
public_key = "ssh-rsa " + private_key.get_base64()
droplet = _create_droplet(public_key)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ip_address = _get_ip_address_of_droplet(droplet)
_ssh_connect(client, hostname=ip_address, username="root", pkey=private_key)
bucket_location = boto3.client("s3").get_bucket_location(Bucket=S3_BUCKET_NAME)["LocationConstraint"]
world_path = "https://s3-%s.amazonaws.com/%s/world.zip" % (bucket_location, S3_BUCKET_NAME)
commands = [
"docker run -d -e EULA=TRUE -e WORLD=%s -e SLACK_WEBHOOK_URL=%s --name minecraft -p 25565:25565 morishin127/minecraft-server" % (world_path, SLACK_INCOMING_WEBHOOK_URL)
]
_exec_commands(client, commands)
message = ":hammer_and_pick: Created instance: `" + ip_address + "`"
return message
def upload_world():
manager = digitalocean.Manager(token=DIGITALOCEAN_API_TOKEN)
all_droplets = manager.get_all_droplets()
droplet = filter(lambda droplet: droplet.name == "minecraft", all_droplets)[0]
private_key = _get_ssh_private_key()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ip_address = _get_ip_address_of_droplet(droplet)
_ssh_connect(client, hostname=ip_address, username="root", pkey=private_key)
commands = [
"cd /root",
"docker cp minecraft:/data/world ./",
"apt install -y zip",
"zip -r world.zip world"
]
_exec_commands(client, commands)
sftp = client.open_sftp()
sftp.get("/root/world.zip", "/tmp/world.zip")
s3 = boto3.resource("s3")
bucket = s3.Bucket(S3_BUCKET_NAME)
obj = bucket.Object("world.zip")
obj.put(Body=open("/tmp/world.zip", "rb"))
obj.Acl().put(ACL="public-read")
bucket_location = boto3.client("s3").get_bucket_location(Bucket=S3_BUCKET_NAME)["LocationConstraint"]
world_path = "https://s3-%s.amazonaws.com/%s/world.zip" % (bucket_location, S3_BUCKET_NAME)
message = ":rocket: Uploaded world.zip: " + world_path
return message
def destroy_server():
manager = digitalocean.Manager(token=DIGITALOCEAN_API_TOKEN)
all_droplets = manager.get_all_droplets()
droplet = filter(lambda droplet: droplet.name == "minecraft", all_droplets)[0]
ip_address = _get_ip_address_of_droplet(droplet)
droplet.destroy()
message = ":boom: Destroyed instance: `" + ip_address + "`"
return message
@retry(tries=30, delay=5)
def _ssh_connect(client, hostname, username, pkey):
print("Trying SSH connection... IP: %s" % (hostname))
client.connect(hostname=hostname, username=username, pkey=pkey)
def _exec_commands(client, commands):
for command in commands:
print("Executing {}".format(command))
stdin, stdout, stderr = client.exec_command(command)
print(stdout.read())
print(stderr.read())
def _create_droplet(public_key):
key_name = 'minecraft-lambda-function-' + public_key[-7:]
manager = digitalocean.Manager(token=DIGITALOCEAN_API_TOKEN)
all_droplets = manager.get_all_droplets()
existing_droplets = filter(lambda droplet: droplet.name == "minecraft", all_droplets)
minecraft_droplet = None
if len(existing_droplets) == 0:
keys = manager.get_all_sshkeys()
if len(filter(lambda k: k.name == key_name, keys)) == 0:
key = digitalocean.SSHKey(token=DIGITALOCEAN_API_TOKEN,
name=key_name,
public_key=public_key)
key.create()
keys.append(key)
droplet = digitalocean.Droplet(token=DIGITALOCEAN_API_TOKEN,
name="minecraft",
region= DIGITALOCEAN_REGION_SLUG if DIGITALOCEAN_REGION_SLUG is not None else "sgp1",
image="docker-18-04",
size_slug="2gb",
ssh_keys=keys,
backups=False)
droplet.create()
minecraft_droplet = manager.get_droplet(droplet.id)
else:
minecraft_droplet = existing_droplets[0]
return minecraft_droplet
@retry(tries=10, delay=3)
def _get_ip_address_of_droplet(droplet):
droplet.load()
if droplet.ip_address is None:
raise Exception("Failed to obtain IP address")
return droplet.ip_address
def _get_ssh_private_key():
key_file_name = "id_rsa"
s3 = boto3.resource("s3")
bucket = s3.Bucket(S3_BUCKET_NAME)
obj = bucket.Object(key_file_name)
try:
obj.load()
except:
_generate_ssh_key(key_file_name)
client = boto3.client("s3")
client.download_file(S3_BUCKET_NAME, key_file_name, "/tmp/" + key_file_name)
private_key = paramiko.RSAKey.from_private_key_file("/tmp/" + key_file_name)
return private_key
def _generate_ssh_key(key_file_name):
key = RSA.generate(2048)
key_file_path = "/tmp/" + key_file_name
with open(key_file_path, "w") as content_file:
os.chmod(key_file_path, 600)
content_file.write(key.exportKey("PEM"))
s3 = boto3.resource("s3")
bucket = s3.Bucket(S3_BUCKET_NAME)
obj = bucket.Object(key_file_name)
obj.put(Body=open(key_file_path, "rb"))
def _slack_notify(message):
requests.post(SLACK_INCOMING_WEBHOOK_URL, {"payload": '{"text": "%s"}' % (message)})