~dmedia/dmedia/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/python3

# Authors:
#   Jason Gerard DeRose <jderose@novacut.com>
#   David Green <david4dev@gmail.com>
#
# dmedia: distributed media library
# Copyright (C) 2010, 2011 Jason Gerard DeRose <jderose@novacut.com>
#
# This file is part of `dmedia`.
#
# `dmedia` is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# `dmedia` is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with `dmedia`.  If not, see <http://www.gnu.org/licenses/>.


"""
Command line tool for talking to dmedia DBus services.
"""

import argparse
from collections import OrderedDict
import sys
from gettext import ngettext
from os import path

import dbus

import dmedia
from dmedia.units import minsec


methods = OrderedDict()

KILL_MSG = """{} was running for {}

WARNING: `dmedia-cli Kill` is deprecated!  Run `stop dmedia` instead.
(Upstart has probably respawned dmedia-service already!)"""


def error(msg, code=1):
    print('ERROR:', msg)
    sys.exit(code)


def print_methods():
    width = max(len(name) for name in methods)
    print('DBus methods on {}:'.format(dmedia.BUS))
    for name in methods:
        if name == 'futon':
                print('')
                print('Misc commands:')
        cls = methods[name]
        print('  {}  {}'.format(name.ljust(width), cls.__doc__))


def print_usage(cls):
    print('Usage:')
    print(' ', *cls.usage())


class MethodMeta(type):
    def __new__(meta, name, bases, dict):
        cls = type.__new__(meta, name, bases, dict)
        if not name.startswith('_'):
            methods[name] = cls
        return cls


class _Method(metaclass=MethodMeta):
    args = tuple()

    def __init__(self, bus):
        self.bus = bus
        self.proxy = dbus.SessionBus().get_object(bus, '/')

    @classmethod
    def usage(cls):
        script = path.basename(sys.argv[0])
        cmd = [script, cls.__name__]
        cmd.extend(arg.upper() for arg in cls.args)
        return cmd

    def run(self, args):
        args = self.validate_args(*args)
        method = self.proxy.get_dbus_method(self.__class__.__name__)
        return self.format_output(method(*args))

    def validate_args(self, *args):
        return args

    def format_output(self, output):
        return output


class Version(_Method):
    'Show version of running dmedia-service'


class Kill(_Method):
    'Deprecated, run `stop dmedia` instead'

    def format_output(self, seconds):
        return KILL_MSG.format(self.bus, minsec(seconds))


class GetEnv(_Method):
    'Get the CouchDB and Dmedia environment info'


class Tasks(_Method):
    'Info about currently running background tasks'


class Stores(_Method):
    'Show the currently connected file-stores'


class Peers(_Method):
    'Show peers'


class CreateFileStore(_Method):
    'Create a new FileStore'

    args = ['directory']
    
    def validate_args(self, directory):
        return [path.abspath(directory)]


class DowngradeStore(_Method):
    'Downgrade durability confidence to zero copies'

    args = ['store_id']


class DowngradeAll(_Method):
    'Downgrade all files in all stores (stress test)'


class PurgeStore(_Method):
    'Purge references to a store'

    args = ['store_id']


class PurgeAll(_Method):
    'Purge all files in all stores (stress test)'


class Resolve(_Method):
    'Resolve Dmedia file ID into a regular file path'

    args = ['file_id']


class AllocateTmp(_Method):
    'Allocate a temporary file for rendering or import'


class HashAndMove(_Method):
    'Allocate a temporary file for rendering or import'

    args = ['tmp_filename']
    
    
class Snapshot(_Method):
    'Create a snapshot of a database [EXPERIMENTAL]'

    args = ['dbname']


class SnapshotAll(_Method):
    'Snapshot all databases [EXPERIMENTAL]'


class AutoFormat(_Method):
    "Set 'auto_format' to 'true' or 'false'"

    args = ['value']


class SkipInternal(_Method):
    "Set 'skip_internal' to 'true' or 'false'"

    args = ['value']


def get_authurl(env):
    if 'basic' not in env:
        return env['url']
    return 'http://{}:{}@localhost:{}/'.format(
        env['basic']['username'],
        env['basic']['password'],
        env['port']
    )


class futon(_Method):
    'Open CouchDB Futon UI in default web browser'

    def run(self, args):
        import json
        import subprocess
        env = json.loads(self.proxy.GetEnv())
        url = get_authurl(env) + '_utils/'
        subprocess.check_call(['/usr/bin/xdg-open', url])
        return url


parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version=dmedia.__version__)
parser.add_argument('--bus',
    help='DBus bus name; default is {!r}'.format(dmedia.BUS),
    default=dmedia.BUS
)
parser.add_argument('method', nargs='?')
parser.add_argument('args', nargs='*')
args = parser.parse_args()


if not args.method:
    parser.print_help()
    print('')
    print_methods()
    sys.exit(0)

if args.method not in methods:
    print_methods()
    print('')
    error('Unknown method {!r}'.format(args.method))

cls = methods[args.method]
if len(args.args) != len(cls.args):
    print_usage(cls)
    print('')
    msg = ngettext(
        '{!r} takes exactly {} argument',
        '{!r} takes exactly {} arguments',
        len(cls.args)
    )
    error(msg.format(args.method, len(cls.args)))

method = cls(args.bus)
print(method.run(args.args))