martinrusev
1/8/2015 - 10:56 AM

Docker builder

Docker builder

from datetime import datetime 
from docker import Client
from djangoapp.instance.models import Instance


class AmonInstance(object):
	def __init__(self, account=None):
		self.client = Client(base_url='unix://var/run/docker.sock', version='1.15')
		self.account_id = 1
		self.instance = Instance.objects.get(account_id=self.account_id)


	def reload_container(self):
		try:
			self.stop_container()
		except:
			pass
			
		self.start_container()


	def start_container(self):
		container = self.client.create_container('martinrusev/djangoapp', 
			name='djangoapp', 
			ports=[8000],
			volumes=['/djangoapp/']
		)

		self.client.start(container, 
			port_bindings={8000: 8000},
			binds={
			'/home/djangoapp':
			{
				'bind': '/djangoapp',
				'ro': True
			},
			'/var/log/djangoapp': {
				'bind': '/var/log',
			}
		})

		container_id = container['Id']
		
		Instance.objects.filter(account_id=self.account_id).update(container_id=container_id,
			modified_date=datetime.now())
		

	def stop_container(self):
		self.client.stop(self.instance.container_id)
		self.client.remove_container(self.instance.container_id)

		Instance.objects.filter(account=self.account).update(container_id=None)