~brianlbaird/charms/trusty/pcrf/trunk

« back to all changes in this revision

Viewing changes to trusty/pcrf/lib/charms/docker/compose.py

  • Committer: brian baird
  • Date: 2016-08-24 18:05:17 UTC
  • Revision ID: brianlbaird@gmail.com-20160824180517-uyp6100mfwuj6les
dt demo

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
 
 
3
from contextlib import contextmanager
 
4
from shlex import split
 
5
from subprocess import check_output
 
6
from workspace import Workspace
 
7
 
 
8
# Wrapper and convenience methods for charming w/ docker compose in python
 
9
class Compose:
 
10
    def __init__(self, workspace, strict=True):
 
11
        '''
 
12
        Object to manage working with Docker-Compose on the CLI. exposes
 
13
        a natural language for performing common tasks with docker in
 
14
        juju charms.
 
15
 
 
16
        @param workspace - Define the CWD for docker-compose execution
 
17
 
 
18
        @param strict - Enable/disable workspace validation
 
19
        '''
 
20
        self.workspace = Workspace(workspace)
 
21
        if strict:
 
22
            self.workspace.validate()
 
23
 
 
24
    def up(self, service=None):
 
25
        '''
 
26
        Convenience method that wraps `docker-compose up`
 
27
 
 
28
        usage: c.up('nginx')  to start the 'nginx' service from the
 
29
        defined `docker-compose.yml` as a daemon
 
30
        '''
 
31
        if service:
 
32
            cmd = "docker-compose up -d {}".format(service)
 
33
        else:
 
34
            cmd = "docker-compose up -d"
 
35
        self.run(cmd)
 
36
 
 
37
    def kill(self, service=None):
 
38
        '''
 
39
        Convenience method that wraps `docker-compose kill`
 
40
 
 
41
        usage: c.kill('nginx')  to kill the 'nginx' service from the
 
42
        defined `docker-compose.yml`
 
43
        '''
 
44
        if service:
 
45
            cmd = "docker-compose kill {}".format(service)
 
46
        else:
 
47
            cmd = "docker-compose kill"
 
48
        self.run(cmd)
 
49
 
 
50
    def run(self, cmd):
 
51
        '''
 
52
        chdir sets working context on the workspace
 
53
 
 
54
        @param: cmd - String of the command to run. eg: echo "hello world"
 
55
        the string is passed through shlex.parse() for convenience.
 
56
 
 
57
        returns STDOUT of command execution
 
58
 
 
59
        usage: c.run('docker-compose ps')
 
60
        '''
 
61
        with chdir("{}".format(self.workspace)):
 
62
            out = check_output(split(cmd))
 
63
            return out
 
64
 
 
65
 
 
66
# This is helpful for setting working directory context
 
67
@contextmanager
 
68
def chdir(path):
 
69
    '''Change the current working directory to a different directory to run
 
70
    commands and return to the previous directory after the command is done.'''
 
71
    old_dir = os.getcwd()
 
72
    os.chdir(path)
 
73
    yield
 
74
    os.chdir(old_dir)