event db handling slightly more robust

now there is larigira-dbmanage: a simple CLI to add/list events (atm
it's too simple to be really good; but can be useful for testing)
This commit is contained in:
boyska 2015-01-24 02:52:32 +01:00
parent 6f0c335d2d
commit 22bb84d1d4
No known key found for this signature in database
GPG key ID: 7395DCAE58289CA9
6 changed files with 76 additions and 10 deletions

1
.gitignore vendored
View file

@ -7,3 +7,4 @@ build
/*.egg
larigira.db
larigira.db_*
*.json

View file

@ -77,6 +77,7 @@ class EventSource(ParentedLet):
def do_business(self):
for alarm, action in self.model.get_all_alarms_expanded():
self.log.debug('scheduling {}'.format(alarm))
yield ('add', alarm, action)
@ -95,25 +96,32 @@ class Monitor(ParentedLet):
could call this method again
'''
now = datetime.now() + timedelta(seconds=self.conf['CACHING_TIME'])
when = next(timegenerate(timespec, now=now))
try:
when = next(timegenerate(timespec, now=now))
except:
logging.exception("Could not generate "
"an alarm from timespec {}".format(timespec))
delta = when - now
assert delta.total_seconds() > 0
self.log.info('Will run after %d seconds' % delta.total_seconds())
audiogen = gevent.spawn_later(delta.total_seconds(), audiogenerate,
audiospec)
self.running[timespec['_id']] = audiogen
self.running[timespec.eid] = audiogen
gevent.spawn_later(delta.total_seconds(),
self.source.reload_id,
timespec['_id'])
timespec.eid)
# FIXME: audiogen is ready in a moment between
# exact_time - CACHING_TIME and the exact_time
# atm we are just ignoring this "window", saying that any moment is
# fine
# the more correct thing will be to wait till that exact moment
# adding another spawn_later
audiogen.link(lambda g: self.log.info('should play %s' % str(g.value)))
audiogen.link(lambda g: self.send_to_parent('add', g.value))
audiogen.link_value(lambda g: self.log.info(
'should play %s' % str(g.value)))
audiogen.link_exception(lambda g: self.log.exception(
'Failure in audiogen {}'.format(audiospec)))
audiogen.link_value(lambda g: self.send_to_parent('add', g.value))
def _run(self):
self.source.start()

35
larigira/event_manage.py Normal file
View file

@ -0,0 +1,35 @@
from __future__ import print_function
import argparse
from pprint import pprint
from .event import EventModel
def main_list(args):
m = EventModel(args.file)
for alarm, action in m.get_all_alarms_expanded():
pprint(dict(alarm=alarm, action=action), indent=4)
def main_add(args):
m = EventModel(args.file)
m.add_event(dict(kind='frequency', interval=args.interval, start=1),
[dict(kind='mpd', howmany=1)]
)
def main():
p = argparse.ArgumentParser()
p.add_argument('-f', '--file', help="Filepath for DB", required=True)
sub = p.add_subparsers()
sub_list = sub.add_parser('list')
sub_list.set_defaults(func=main_list)
sub_add = sub.add_parser('add')
sub_add.add_argument('--interval', type=int, default=3600)
sub_add.set_defaults(func=main_add)
args = p.parse_args()
args.func(args)
if __name__ == '__main__':
main()

View file

@ -74,7 +74,10 @@ class Player(gevent.Greenlet):
def enqueue(self, songs):
mpd_client = self._get_mpd()
for song in songs:
mpd_client.addid(song, 1)
self.log.info('Adding {} to playlist'.format(song))
print(mpd_client.playlistid())
pos = min(1, len(mpd_client.playlistid()))
mpd_client.addid(song, pos)
def _run(self):
MpcWatcher(self.q, self.conf, client=None).start()
@ -106,6 +109,7 @@ def on_player_crash(*args, **kwargs):
def main():
# TODO: update conf from somewhere
conf['DB_URI'] = 'larigira.db'
logging.basicConfig(level=logging.DEBUG)
p = Player(conf)
p.start()
# TODO: if <someoption> create Monitor(p.q)

View file

@ -1,7 +1,9 @@
from __future__ import print_function
import logging
import gc
from greenlet import greenlet
from flask import current_app, Blueprint, Flask
from flask import current_app, Blueprint, Flask, jsonify
rpc = Blueprint('rpc', __name__, url_prefix='/api')
@ -21,13 +23,28 @@ def send_to_parent(kind, *args):
@rpc.route('/')
def rpc_index():
return 'So, what command would you like to give?'
rules = list(current_app.url_map.iter_rules())
return jsonify({'rules': [r.rule for r in rules
if r.rule.startswith('/api')]})
@rpc.route('/refresh')
def rpc_refresh():
send_to_parent('rpc')
return 'ok, put'
return jsonify(dict(status='ok'))
@rpc.route('/debug/running')
def rpc_wip():
greenlets = []
for ob in filter(lambda obj: isinstance(obj, greenlet),
gc.get_objects()):
greenlets.append({
'repr': repr(ob),
'class': ob.__class__.__name__,
'parent': repr(ob.parent)
})
return jsonify(dict(greenlets=greenlets))
def create_app(queue):

View file

@ -48,7 +48,8 @@ setup(name='larigira',
entry_points={
'console_scripts': ['larigira=larigira.mpc:main',
'larigira-timegen=larigira.timegen:main',
'larigira-audiogen=larigira.audiogen:main'],
'larigira-audiogen=larigira.audiogen:main',
'larigira-dbmanage=larigira.event_manage:main'],
'larigira.audiogenerators': [
'mpd = larigira.audiogen_mpdrandom:generate_by_artist',
'static = larigira.audiogen_static:generate',