import os
import yaml
from subprocess import check_call
from charmhelpers import fetch
from charmhelpers.core import host
from charmhelpers.core import hookenv
from charmhelpers.core import templating
from charms import reactive
from charms.reactive import hook
from charms.reactive import when
from charms.reactive import when_not
@hook('config-changed')
def config_changed():
config = hookenv.config()
if config.changed('port'):
# reactive.set_state('nginx.stop')
stop_container()
reactive.set_state('nginx.start')
@when('docker.available')
@when_not('nginx.start', 'nginx.started', 'nginx.stopped')
def install_nginx():
hookenv.status_set('maintenance', 'Pulling Nginx image')
check_call(['docker', 'pull', 'nginx'])
reactive.set_state('nginx.start')
@when('nginx.start', 'docker.available')
@when_not('nginx.started')
def run_container():
config = hookenv.config()
# Run the nginx docker container.
run_command = [
'docker',
'run',
'--restart',
'on-failure',
'--name',
'docker-nginx',
'-p',
'{}:80'.format(config['port']),
'-d',
'nginx'
]
check_call(run_command)
hookenv.open_port(config['port'])
reactive.remove_state('nginx.stopped')
reactive.remove_state('nginx.start')
reactive.set_state('nginx.started')
hookenv.status_set('active', 'Nginx container started')
@when('nginx.stop', 'docker.available')
@when_not('nginx.stopped')
def stop_container():
hookenv.status_set('maintenance', 'Stopping Nginx container')
check_call(['docker', 'kill', 'docker-nginx'])
check_call(['docker', 'remove', 'docker-nginx'])
reactive.remove_state('nginx.started')
reactive.remove_state('nginx.stop')
reactive.set_state('nginx.stopped')