~ubuntu-branches/ubuntu/trusty/moksha.common/trusty

« back to all changes in this revision

Viewing changes to moksha/common/commands/cli.py

  • Committer: Package Import Robot
  • Author(s): Simon Chopin
  • Date: 2013-05-06 14:57:06 UTC
  • Revision ID: package-import@ubuntu.com-20130506145706-au0xdyem6dt68t1f
Tags: upstream-1.2.0
ImportĀ upstreamĀ versionĀ 1.2.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
""" The Moksha Command-line Interface """
 
2
from __future__ import print_function
 
3
 
 
4
import os
 
5
import sys
 
6
import signal
 
7
import logging
 
8
import pkg_resources
 
9
 
 
10
from optparse import OptionParser
 
11
from twisted.internet import protocol
 
12
from twisted.internet import reactor
 
13
 
 
14
log = logging.getLogger(__name__)
 
15
 
 
16
pids = []
 
17
 
 
18
class MokshaProcessProtocol(protocol.ProcessProtocol):
 
19
    def __init__(self, name):
 
20
        self.name = name
 
21
    def connectionMade(self):
 
22
        pass
 
23
    def outReceived(self, data):
 
24
        sys.stdout.write(data)
 
25
    def errReceived(self, data):
 
26
        sys.stderr.write(data)
 
27
    def inConnectionLost(self):
 
28
        pass
 
29
    def outConnectionLost(self):
 
30
        pass
 
31
    def errConnectionLost(self):
 
32
        pass
 
33
    def processEnded(self, status_object):
 
34
        print("Process %r quit with status %d" % (
 
35
                self.name, status_object.value.exitCode))
 
36
        reactor.stop()
 
37
        for pid in pids:
 
38
            try:
 
39
                os.kill(pid, signal.SIGTERM)
 
40
            except OSError:
 
41
                pass
 
42
 
 
43
 
 
44
class MokshaCLI(object):
 
45
 
 
46
    def _exec(self, process, *args, **kw):
 
47
        args = args and [process] + list(args) or [process]
 
48
        print("Running %s" % ' '.join(args))
 
49
        pp = MokshaProcessProtocol(name=process)
 
50
        process = reactor.spawnProcess(pp, process, args,
 
51
                env={'PYTHONPATH': os.getcwd()}, **kw)
 
52
        pids.append(process.pid)
 
53
 
 
54
    def start(self):
 
55
        """ Start all of the Moksha components """
 
56
 
 
57
        from moksha.lib.helpers import get_moksha_config_path
 
58
 
 
59
        orbited = ['orbited']
 
60
        if os.path.exists('/etc/moksha/orbited.cfg'):
 
61
            orbited += ['-c', '/etc/moksha/orbited.cfg']
 
62
 
 
63
        self._exec(*orbited)
 
64
        self._exec('paster', 'serve', get_moksha_config_path())
 
65
        self._exec('moksha-hub', '-v')
 
66
 
 
67
    def list(self):
 
68
        """ List all available apps, widgets, producers and consumers """
 
69
        entry_points = ('root', 'widget', 'application', 'wsgiapp',
 
70
                        'producer', 'consumer')
 
71
        for entry in entry_points:
 
72
            print("[moksha.%s]" % entry)
 
73
            for obj_entry in pkg_resources.iter_entry_points('moksha.' + entry):
 
74
                print(" * %s" % obj_entry.name)
 
75
            print()
 
76
 
 
77
    def install(self):
 
78
        """ Install a Moksha component """
 
79
 
 
80
    def uninstall(self):
 
81
        """ Uninstall a Moksha component """
 
82
 
 
83
    def quickstart(self):
 
84
        """ Create a new Moksha component """
 
85
        # If no arguments given, run `paster moksha --help`
 
86
 
 
87
    def send(self, topic, message):
 
88
        """ Send a message to a topic """
 
89
        from moksha.hub.api import MokshaHub, reactor
 
90
        hub = MokshaHub()
 
91
        print("send_message(%s, %s)" % (topic, message))
 
92
        hub.send_message(topic, {'msg': message})
 
93
 
 
94
        def stop_reactor():
 
95
            hub.close()
 
96
            reactor.stop()
 
97
 
 
98
        reactor.callLater(0.2, stop_reactor)
 
99
        reactor.run()
 
100
 
 
101
 
 
102
def get_parser():
 
103
    usage = 'usage: %prog [command]'
 
104
    parser = OptionParser(usage, description=__doc__)
 
105
    parser.add_option('', '--start', action='store_true', dest='start',
 
106
                      help='Start Moksha')
 
107
    parser.add_option('', '--list', action='store_true', dest='list',
 
108
                      help='List all installed Moksha components')
 
109
    parser.add_option('', '--send', action='store_true', dest='send',
 
110
        help='Send a message to a given topic. Usage: send <topic> <message>')
 
111
    return parser
 
112
 
 
113
 
 
114
def main():
 
115
    parser = get_parser()
 
116
    opts, args = parser.parse_args()
 
117
    pkg_resources.working_set.add_entry(os.getcwd())
 
118
 
 
119
    moksha = MokshaCLI()
 
120
 
 
121
    logging.basicConfig(level=logging.INFO, format=
 
122
            '%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s')
 
123
 
 
124
    stdout = logging.StreamHandler(sys.stdout)
 
125
    stdout.setFormatter(logging.Formatter('%(message)s'))
 
126
    log.addHandler(stdout)
 
127
 
 
128
    if opts.start or 'start' in args:
 
129
        print("Starting Moksha...")
 
130
        moksha.start()
 
131
        try:
 
132
            reactor.run()
 
133
        except Exception as e:
 
134
            print("Caught exception: %s" % str(e))
 
135
            moksha.stop()
 
136
    elif opts.list or 'list' in args:
 
137
        moksha.list()
 
138
    elif opts.send or 'send' in args:
 
139
        if len(sys.argv) != 4:
 
140
            log.error('Usage: moksha send <topic> <message>')
 
141
            sys.exit(-1)
 
142
        moksha.send(sys.argv[2], sys.argv[3])
 
143
    else:
 
144
        parser.print_help()
 
145
 
 
146
 
 
147
if __name__ == '__main__':
 
148
    main()