-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulticraft.py
More file actions
78 lines (69 loc) · 2.61 KB
/
multicraft.py
File metadata and controls
78 lines (69 loc) · 2.61 KB
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
#!/usr/bin/python
# -----------------------------------------------------------------------------
#
# Multicraft - Launch multiple Minecraft instances using docker
# Pedro Perez - 2015
#
#
# -----------------------------------------------------------------------------
import sys
import os
import socket
from docker import Client
from azure.storage.queue import QueueService
debug = 0
defaultport = 25565
counter = 0
instanceCreated = 0
maxInstances = 3
imageName = "mcdocker"
# DB update settings
account_name = "mcdockerqueue"
account_key = sys.argv[1]
queuename = "servers"
# Create a new instance on an available port
def createMcInstance(port):
directory = "/mnt/mc" + str(port)
try:
os.mkdir(directory)
except:
if debug == 1: print "Directory already exists!"
c = Client(base_url='unix://var/run/docker.sock')
container = c.create_container(image=imageName, ports=[25565], command='/start')
c.start(container, port_bindings={25565: ('0.0.0.0', port)})
return container
# Simple TCP 3WHS to check if a port is available, returns 0 if it's not.
def checkPort(localport):
if localport < 65536:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('127.0.0.1', localport))
return result
s.close()
else:
return 111
# Main thread - Check if port 25565 and move to the next if it's not. Once a free port has been found, create a new instance (up to 3)
while instanceCreated == 0:
freeport = checkPort(defaultport)
if freeport == 0:
defaultport += 1
counter += 1
if counter > maxInstances:
print "Too many instances! you can't run more than %s instances" % maxInstances
sys.exit()
else:
if debug == 1: print "Port %s is free" % defaultport
container = createMcInstance(defaultport)
instanceCreated = 1
counter +=1
# Return Instance ID, port and total number of instances once finished creating the server
print "Instance ID: %s" % container["Id"]
print "Listening on port %s" % defaultport
print "There are %s instances running on this server" % counter
# Update servers queue
queue_service = QueueService(account_name, account_key)
try:
queue_service.create_queue(queuename)
except:
print "Queue creation failed."
queue_service.put_message(queuename, '{"ContainerID":"%s", "ContainerPort":"%s", "ServerID":"%s"}' % container["Id"], defaultport, socket.gethostname())
sys.exit()