vpnmanager/manager/tasks.py
2019-02-07 16:16:14 +00:00

92 lines
2.6 KiB
Python

from celery import shared_task
from distutils.dir_util import copy_tree
from .views import makewificonfig
from .hostname import hostname
import os
import time
import glob
import tempfile
import crypt
import subprocess
import datetime
@shared_task
def mkfirmware(device, path):
if device.firmware and device.firmware > device.model.firmware and device.firmware > device.changed and glob.glob("%s/%s.bin" % (path, device.id)):
return True
BEFORE = os.getcwd()
DEVICEDIR = "/opt/vpnmanager/device-config/%i/" % device.model.id
SRCDIR = "/opt/vpnmanager/imagebuilder/%i/" % device.model.id
if glob.glob(SRCDIR + "/.kumilock"):
return False
with open(SRCDIR + "/.kumilock", "w") as lock:
lock.write("")
tempdir = tempfile.TemporaryDirectory()
copy_tree(DEVICEDIR, tempdir.name)
# Write OpenVPN config
with open(tempdir.name + "/etc/openvpn/client.conf", "w") as vpnconf:
vpnconf.write(device.vpnconfig)
# Write secret
with open(tempdir.name + "/etc/vpnsecret", "w") as secret:
secret.write('SECRET="%s"\nHOSTNAME="%s"' % (device.secret, hostname))
# Write password
with open(tempdir.name + "/etc/shadow", "r") as shadow:
password = crypt.crypt(device.password, crypt.mksalt(crypt.METHOD_MD5))
shadowin = shadow.read()
with open(tempdir.name + "/etc/shadow", "w") as shadowout:
shadowout.write(shadowin.replace("$PASSWORD", password))
# Write Wireless config
with open(tempdir.name + "/etc/config/wireless", "r") as wireless:
wirein = wireless.read()
with open(tempdir.name + "/etc/config/wireless", "w") as wireout:
wire = wirein.replace("$SSID", device.serial)
wireout.write(wire + "\n" + makewificonfig(device))
# Create compilation environment
os.system("rm -rf " + SRCDIR + "/files/")
os.mkdir(SRCDIR + "/files/")
os.system("cp -r " + tempdir.name + "/* " + SRCDIR + "/files/")
tempdir.cleanup()
os.system("rm " + SRCDIR + "/bin/targets/ar71xx/generic/*")
# Build image
os.chdir(SRCDIR)
try:
subprocess.call(["/usr/bin/make"])
except:
os.remove(SRCDIR + "/.kumilock")
os.chdir(BEFORE)
return False
os.chdir(BEFORE)
os.rename(glob.glob(SRCDIR + "/bin/targets/ar71xx/generic/*squashfs-sysupgrade.bin")[0], "%s/%s.bin" % (path, device.id))
os.remove(SRCDIR + "/.kumilock")
os.system("rm -rf " + SRCDIR + "/files/")
os.system("rm " + SRCDIR + "/bin/targets/ar71xx/generic/*")
device.firmware = datetime.datetime.now()
device.save()
return True