pyca 4.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyca/db.py ADDED
@@ -0,0 +1,243 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ pyca.db
4
+ ~~~~~~~
5
+
6
+ Database specification for pyCA
7
+ '''
8
+
9
+ import json
10
+ import os.path
11
+ import string
12
+ from pyca.config import config
13
+ from sqlalchemy.ext.declarative import declarative_base
14
+ from sqlalchemy import Column, Integer, Text, LargeBinary, DateTime, \
15
+ create_engine
16
+ from sqlalchemy.orm import sessionmaker
17
+ from datetime import datetime
18
+ from functools import wraps
19
+ Base = declarative_base()
20
+
21
+
22
+ def init():
23
+ '''Initialize connection to database. Additionally the basic database
24
+ structure will be created if nonexistent.
25
+ '''
26
+ global engine
27
+ engine = create_engine(config('agent', 'database'))
28
+ Base.metadata.create_all(engine)
29
+
30
+
31
+ def get_session():
32
+ '''Get a session for database communication. If necessary a new connection
33
+ to the database will be established.
34
+
35
+ :return: Database session
36
+ '''
37
+ if 'engine' not in globals():
38
+ init()
39
+ Session = sessionmaker(bind=engine)
40
+ return Session()
41
+
42
+
43
+ def with_session(f):
44
+ """Wrapper for f to make a SQLAlchemy session present within the function
45
+
46
+ :param f: Function to call
47
+ :type f: Function
48
+ :raises e: Possible exception of f
49
+ :return: Result of f
50
+ """
51
+ @wraps(f)
52
+ def decorated(*args, **kwargs):
53
+ session = get_session()
54
+ try:
55
+ result = f(session, *args, **kwargs)
56
+ except Exception as e:
57
+ session.rollback()
58
+ raise e
59
+ finally:
60
+ session.close()
61
+ return result
62
+ return decorated
63
+
64
+
65
+ class Constants():
66
+
67
+ @classmethod
68
+ def values(cls):
69
+ for key, value in cls.__dict__.items():
70
+ if not key.startswith('_'):
71
+ yield value
72
+
73
+ @classmethod
74
+ def str(cls, value):
75
+ '''Convert status (id) to its string name.'''
76
+ for k, v in cls.__dict__.items():
77
+ if k[0] in string.ascii_uppercase and v == value:
78
+ return k.lower().replace('_', ' ')
79
+
80
+
81
+ class Status(Constants):
82
+ '''Event status definitions
83
+ '''
84
+ UPCOMING = 1
85
+ RECORDING = 2
86
+ FAILED_RECORDING = 3
87
+ FINISHED_RECORDING = 4
88
+ UPLOADING = 5
89
+ FAILED_UPLOADING = 6
90
+ FINISHED_UPLOADING = 7
91
+ PARTIAL_RECORDING = 8
92
+ PAUSED_AFTER_RECORDING = 9
93
+
94
+
95
+ class ServiceStatus(Constants):
96
+ '''Service status type definitions
97
+ '''
98
+ STOPPED = 1
99
+ IDLE = 2
100
+ BUSY = 3
101
+
102
+
103
+ class Service(Constants):
104
+ '''Service type definitions
105
+ '''
106
+ AGENTSTATE = 1
107
+ CAPTURE = 2
108
+ INGEST = 3
109
+ SCHEDULE = 4
110
+
111
+
112
+ # Database Schema Definition
113
+ class BaseEvent():
114
+ '''Database definition of an event.'''
115
+
116
+ __tablename__ = 'event'
117
+
118
+ uid = Column('uid', Text(), nullable=False, primary_key=True)
119
+ start = Column('start', Integer(), primary_key=True)
120
+ end = Column('end', Integer(), nullable=False)
121
+ title = Column('title', Text())
122
+ data = Column('data', LargeBinary(), nullable=False)
123
+ status = Column('status', Integer(), nullable=False,
124
+ default=Status.UPCOMING)
125
+ tracks = Column('tracks', LargeBinary(), nullable=True)
126
+
127
+ def get_data(self):
128
+ '''Load JSON data from event.
129
+ '''
130
+ return json.loads(self.data.decode('utf-8'))
131
+
132
+ def set_data(self, data):
133
+ '''Store data as JSON.
134
+ '''
135
+ # Python 3 wants bytes
136
+ self.data = json.dumps(data).encode('utf-8')
137
+
138
+ def name(self):
139
+ '''Returns the filesystem name of this event.
140
+ '''
141
+ return 'recording-%i-%s' % (self.start, self.uid)
142
+
143
+ def directory(self):
144
+ '''Returns recording directory of this event.
145
+ '''
146
+ return os.path.join(config('capture', 'directory'), self.name())
147
+
148
+ def remaining_duration(self, time):
149
+ '''Returns the remaining duration for a recording.
150
+ '''
151
+ return max(0, self.end - max(self.start, time))
152
+
153
+ def status_str(self):
154
+ '''Return status as string.
155
+ '''
156
+ return Status.str(self.status)
157
+
158
+ def get_tracks(self):
159
+ '''Load JSON track data from event.
160
+ '''
161
+ if not self.tracks:
162
+ return []
163
+ return json.loads(self.tracks.decode('utf-8'))
164
+
165
+ def set_tracks(self, tracks):
166
+ '''Store track data as JSON.
167
+ '''
168
+ self.tracks = json.dumps(tracks).encode('utf-8')
169
+
170
+ def __repr__(self):
171
+ '''Return a string representation of an artist object.
172
+
173
+ :return: String representation of object.
174
+ '''
175
+ return '<Event(start=%i, uid="%s")>' % (self.start, self.uid)
176
+
177
+ def serialize(self):
178
+ '''Serialize this object as dictionary usable for conversion to JSON.
179
+
180
+ :return: Dictionary representing this object.
181
+ '''
182
+ return {
183
+ 'type': 'event',
184
+ 'id': self.uid,
185
+ 'attributes': {
186
+ 'start': self.start,
187
+ 'end': self.end,
188
+ 'uid': self.uid,
189
+ 'title': self.title,
190
+ 'data': self.get_data(),
191
+ 'status': Status.str(self.status)
192
+ }
193
+ }
194
+
195
+
196
+ class UpcomingEvent(Base, BaseEvent):
197
+ '''List of upcoming events'''
198
+
199
+ __tablename__ = 'upcoming_event'
200
+
201
+
202
+ class RecordedEvent(Base, BaseEvent):
203
+ '''List of events pyca tried to record.'''
204
+
205
+ __tablename__ = 'recorded_event'
206
+
207
+ def __init__(self, event=None):
208
+ if event:
209
+ self.uid = event.uid
210
+ self.start = event.start
211
+ self.end = event.end
212
+ self.title = event.title
213
+ self.data = event.data
214
+ self.status = event.status
215
+
216
+
217
+ class ServiceStates(Base):
218
+ '''List of internal service states.'''
219
+
220
+ __tablename__ = 'service_states'
221
+
222
+ type = Column('type', Integer(), nullable=False, primary_key=True)
223
+ status = Column('status', Integer(), nullable=False,
224
+ default=ServiceStatus.STOPPED)
225
+
226
+ def __init__(self, service=None):
227
+ if service:
228
+ self.type = service.type
229
+ self.status = service.status
230
+
231
+
232
+ class UpstreamState(Base):
233
+ '''State of the upstream Opencast server.'''
234
+ __tablename__ = 'upstream_state'
235
+ url = Column('url', Text(), primary_key=True)
236
+ last_synced = Column('last_synced', DateTime())
237
+
238
+ @staticmethod
239
+ def update_sync_time(url):
240
+ s = get_session()
241
+ s.merge(UpstreamState(url=url, last_synced=datetime.utcnow()))
242
+ s.commit()
243
+ s.close()
pyca/ingest.py ADDED
@@ -0,0 +1,166 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ python-capture-agent
4
+ ~~~~~~~~~~~~~~~~~~~~
5
+
6
+ :copyright: 2014-2017, Lars Kiesow <lkiesow@uos.de>
7
+ :license: LGPL – see LICENSE for more details.
8
+ '''
9
+
10
+ from pyca.config import config
11
+ from pyca.db import get_session, RecordedEvent, Status, Service, ServiceStatus
12
+ from pyca.utils import http_request, service, set_service_status
13
+ from pyca.utils import set_service_status_immediate, recording_state
14
+ from pyca.utils import update_event_status, terminate
15
+ import logging
16
+ import pycurl
17
+ import random
18
+ import sdnotify
19
+ import shutil
20
+ import time
21
+
22
+ logger = logging.getLogger(__name__)
23
+ notify = sdnotify.SystemdNotifier()
24
+
25
+
26
+ def get_config_params(properties):
27
+ '''Extract the set of configuration parameters from the properties attached
28
+ to the schedule
29
+ '''
30
+ param = []
31
+ wdef = ''
32
+ for prop in properties.split('\n'):
33
+ if prop.startswith('org.opencastproject.workflow.config'):
34
+ key, val = prop.split('=', 1)
35
+ key = key.split('.')[-1]
36
+ param.append((key, val))
37
+ elif prop.startswith('org.opencastproject.workflow.definition'):
38
+ wdef = prop.split('=', 1)[-1]
39
+ return wdef, param
40
+
41
+
42
+ def ingest(event):
43
+ '''Ingest a finished recording to the Opencast server.
44
+ '''
45
+ # Update status
46
+ set_service_status(Service.INGEST, ServiceStatus.BUSY)
47
+ notify.notify('STATUS=Uploading')
48
+ recording_state(event.uid, 'uploading')
49
+ update_event_status(event, Status.UPLOADING)
50
+
51
+ # Select ingest service
52
+ # The ingest service to use is selected at random from the available
53
+ # ingest services to ensure that not every capture agent uses the same
54
+ # service at the same time
55
+ service_url = service('ingest', force_update=True)
56
+ # nosec: we do not need a secure random number here
57
+ service_url = service_url[random.randrange(0, len(service_url))] # nosec
58
+ logger.info('Selecting ingest service to use: ' + service_url)
59
+
60
+ # create mediapackage
61
+ logger.info('Creating new mediapackage')
62
+ mediapackage = http_request(service_url + '/createMediaPackage', timeout=0)
63
+
64
+ # extract workflow_def, workflow_config and add DC catalogs
65
+ prop = 'org.opencastproject.capture.agent.properties'
66
+ dcns = 'http://www.opencastproject.org/xsd/1.0/dublincore/'
67
+ for attachment in event.get_data().get('attach'):
68
+ data = attachment.get('data')
69
+ if attachment.get('x-apple-filename') == prop:
70
+ workflow_def, workflow_config = get_config_params(data)
71
+
72
+ # dublin core catalogs
73
+ elif attachment.get('fmttype') == 'application/xml' \
74
+ and dcns in data \
75
+ and config('ingest', 'upload_catalogs'):
76
+ name = attachment.get('x-apple-filename', '').rsplit('.', 1)[0]
77
+ logger.info('Adding %s DC catalog', name)
78
+ fields = [('mediaPackage', mediapackage),
79
+ ('flavor', 'dublincore/%s' % name),
80
+ ('dublinCore', data.encode('utf-8'))]
81
+ mediapackage = http_request(service_url + '/addDCCatalog', fields,
82
+ timeout=0)
83
+
84
+ else:
85
+ logger.info('Not uploading %s', attachment.get('x-apple-filename'))
86
+ continue
87
+
88
+ # add track
89
+ for (flavor, track) in event.get_tracks():
90
+ logger.info('Adding track (%s -> %s)', flavor, track)
91
+ track = track.encode('ascii', 'ignore')
92
+ fields = [('mediaPackage', mediapackage), ('flavor', flavor),
93
+ ('BODY1', (pycurl.FORM_FILE, track))]
94
+ mediapackage = http_request(service_url + '/addTrack', fields,
95
+ timeout=0)
96
+
97
+ # ingest
98
+ logger.info('Ingest recording')
99
+ fields = [('mediaPackage', mediapackage)]
100
+ if workflow_def:
101
+ fields.append(('workflowDefinitionId', workflow_def))
102
+ if event.uid:
103
+ fields.append(('workflowInstanceId',
104
+ event.uid.encode('ascii', 'ignore')))
105
+ fields += workflow_config
106
+ mediapackage = http_request(service_url + '/ingest', fields, timeout=0)
107
+
108
+ # Update status
109
+ recording_state(event.uid, 'upload_finished')
110
+ update_event_status(event, Status.FINISHED_UPLOADING)
111
+ if config('ingest', 'delete_after_upload'):
112
+ directory = event.directory()
113
+ logger.info("Removing uploaded event directory %s", directory)
114
+ shutil.rmtree(directory)
115
+ notify.notify('STATUS=Running')
116
+ set_service_status_immediate(Service.INGEST, ServiceStatus.IDLE)
117
+
118
+ logger.info('Finished ingest')
119
+
120
+
121
+ def safe_start_ingest(event):
122
+ '''Start a capture process but make sure to catch any errors during this
123
+ process, log them but otherwise ignore them.
124
+ '''
125
+ try:
126
+ ingest(event)
127
+ except Exception:
128
+ logger.exception('Something went wrong during the upload')
129
+ # Update state if something went wrong
130
+ recording_state(event.uid, 'upload_error')
131
+ update_event_status(event, Status.FAILED_UPLOADING)
132
+ set_service_status_immediate(Service.INGEST, ServiceStatus.IDLE)
133
+
134
+
135
+ def control_loop():
136
+ '''Main loop of the capture agent, retrieving and checking the schedule as
137
+ well as starting the capture process if necessry.
138
+ '''
139
+ set_service_status_immediate(Service.INGEST, ServiceStatus.IDLE)
140
+ notify.notify('READY=1')
141
+ notify.notify('STATUS=Running')
142
+ while not terminate():
143
+ notify.notify('WATCHDOG=1')
144
+ # Get next recording
145
+ session = get_session()
146
+ event = session.query(RecordedEvent)\
147
+ .filter(RecordedEvent.status ==
148
+ Status.FINISHED_RECORDING).first()
149
+ if event:
150
+ # nosec: we do not need a secure random number here
151
+ delay = random.randint(config('ingest', 'delay_min'), # nosec
152
+ config('ingest', 'delay_max'))
153
+ logger.info("Delaying ingest for %s seconds", delay)
154
+ time.sleep(delay)
155
+ safe_start_ingest(event)
156
+ session.close()
157
+ time.sleep(1.0)
158
+ logger.info('Shutting down ingest service')
159
+ set_service_status(Service.INGEST, ServiceStatus.STOPPED)
160
+
161
+
162
+ def run():
163
+ '''Start the capture agent.
164
+ '''
165
+
166
+ control_loop()
pyca/schedule.py ADDED
@@ -0,0 +1,133 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ python-capture-agent
4
+ ~~~~~~~~~~~~~~~~~~~~
5
+
6
+ :copyright: 2014-2017, Lars Kiesow <lkiesow@uos.de>
7
+ :license: LGPL – see LICENSE for more details.
8
+ '''
9
+
10
+ from pyca.utils import http_request, service, timestamp, terminate, \
11
+ set_service_status_immediate
12
+ from pyca.config import config
13
+ from pyca.db import get_session, UpcomingEvent, Service, ServiceStatus, \
14
+ UpstreamState, with_session
15
+ from base64 import b64decode
16
+ from datetime import datetime
17
+ import dateutil.parser
18
+ import logging
19
+ import pycurl
20
+ import sdnotify
21
+ import time
22
+ from urllib.parse import urlencode
23
+
24
+ logger = logging.getLogger(__name__)
25
+ notify = sdnotify.SystemdNotifier()
26
+
27
+
28
+ def parse_ical(vcal):
29
+ '''Parse Opencast schedule iCalendar file and return events as dict
30
+ '''
31
+ vcal = vcal.replace('\r\n ', '').replace('\r\n\r\n', '\r\n')
32
+ vevents = vcal.split('\r\nBEGIN:VEVENT\r\n')
33
+ del vevents[0]
34
+ events = []
35
+ for vevent in vevents:
36
+ event = {}
37
+ for line in vevent.split('\r\n'):
38
+ line = line.split(':', 1)
39
+ key = line[0].lower()
40
+ if len(line) <= 1 or key == 'end':
41
+ continue
42
+ if key.startswith('dt'):
43
+ event[key] = int(dateutil.parser.parse(line[1]).timestamp())
44
+ continue
45
+ if not key.startswith('attach'):
46
+ event[key] = line[1]
47
+ continue
48
+ # finally handle attachments
49
+ event['attach'] = event.get('attach', [])
50
+ attachment = {}
51
+ for x in [x.split('=') for x in line[0].split(';')]:
52
+ if x[0].lower() in ['fmttype', 'x-apple-filename']:
53
+ attachment[x[0].lower()] = x[1]
54
+ attachment['data'] = b64decode(line[1]).decode('utf-8')
55
+ event['attach'].append(attachment)
56
+ events.append(event)
57
+ return events
58
+
59
+
60
+ @with_session
61
+ def get_schedule(db):
62
+ '''Try to load schedule from the Matterhorn core. Returns a valid schedule
63
+ or None on failure.
64
+ '''
65
+ params = {'agentid': config('agent', 'name').encode('utf8')}
66
+ lookahead = config('agent', 'cal_lookahead') * 24 * 60 * 60
67
+ if lookahead:
68
+ params['cutoff'] = str((timestamp() + lookahead) * 1000)
69
+ uri = '%s/calendars?%s' % (service('scheduler')[0],
70
+ urlencode(params))
71
+ try:
72
+ vcal = http_request(uri)
73
+ UpstreamState.update_sync_time(config('server', 'url'))
74
+ except pycurl.error as e:
75
+ logger.error('Could not get schedule: %s', e)
76
+ return
77
+
78
+ try:
79
+ cal = parse_ical(vcal.decode('utf-8'))
80
+ except Exception:
81
+ logger.exception('Could not parse ical')
82
+ return
83
+ db.query(UpcomingEvent).delete()
84
+ for event in cal:
85
+ # Ignore events that have already ended
86
+ if event['dtend'] <= timestamp():
87
+ continue
88
+ e = UpcomingEvent()
89
+ e.start = event['dtstart']
90
+ e.end = event['dtend']
91
+ e.uid = event.get('uid')
92
+ e.title = event.get('summary')
93
+ e.set_data(event)
94
+ db.add(e)
95
+ db.commit()
96
+
97
+
98
+ def control_loop():
99
+ '''Main loop, retrieving the schedule.
100
+ '''
101
+ set_service_status_immediate(Service.SCHEDULE, ServiceStatus.BUSY)
102
+ notify.notify('READY=1')
103
+ while not terminate():
104
+ notify.notify('WATCHDOG=1')
105
+ # Try getting an updated schedule
106
+ get_schedule()
107
+ session = get_session()
108
+ next_event = session.query(UpcomingEvent)\
109
+ .filter(UpcomingEvent.end > timestamp())\
110
+ .order_by(UpcomingEvent.start)\
111
+ .first()
112
+ if next_event:
113
+ logger.info('Next scheduled recording: %s',
114
+ datetime.fromtimestamp(next_event.start))
115
+ notify.notify('STATUS=Next scheduled recording: %s' %
116
+ datetime.fromtimestamp(next_event.start))
117
+ else:
118
+ logger.info('No scheduled recording')
119
+ notify.notify('STATUS=No scheduled recording')
120
+ session.close()
121
+
122
+ next_update = timestamp() + config('agent', 'update_frequency')
123
+ while not terminate() and timestamp() < next_update:
124
+ time.sleep(0.1)
125
+
126
+ logger.info('Shutting down schedule service')
127
+ set_service_status_immediate(Service.SCHEDULE, ServiceStatus.STOPPED)
128
+
129
+
130
+ def run():
131
+ '''Start the capture agent.
132
+ '''
133
+ control_loop()
pyca/ui/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ Simple UI telling about the current state of the capture agent.
4
+ '''
5
+ from flask import Flask, send_from_directory, redirect, url_for, make_response
6
+ from prometheus_client import generate_latest, CONTENT_TYPE_LATEST
7
+ from pyca.ui import capture_devices_collector, process_status_collector, recordings_collector # noqa
8
+ from pyca.config import config
9
+ from pyca.ui.utils import requires_auth
10
+ import os.path
11
+
12
+ __base_dir__ = os.path.abspath(os.path.dirname(__file__))
13
+ app = Flask(
14
+ __name__,
15
+ template_folder=os.path.join(__base_dir__, 'templates'),
16
+ static_folder=os.path.join(__base_dir__, 'static'))
17
+
18
+ import pyca.ui.jsonapi # noqa
19
+
20
+
21
+ @app.route('/')
22
+ @requires_auth
23
+ def home():
24
+ '''Serve the status page of the capture agent.
25
+ '''
26
+ refresh_rate = config('ui', 'refresh_rate')
27
+
28
+ return redirect(url_for(
29
+ 'static', filename='index.html', refresh=refresh_rate))
30
+
31
+
32
+ @app.route("/img/<int:image_id>")
33
+ @requires_auth
34
+ def serve_image(image_id):
35
+ '''Serve the preview image with the given id
36
+ '''
37
+ try:
38
+ preview_dir = config('capture', 'preview_dir')
39
+ filepath = config('capture', 'preview')[image_id]
40
+ filepath = filepath.replace('{{previewdir}}', preview_dir)
41
+ filepath = os.path.abspath(filepath)
42
+ if os.path.isfile(filepath):
43
+ directory, filename = filepath.rsplit('/', 1)
44
+ response = send_from_directory(directory, filename)
45
+ response.cache_control.no_cache = True
46
+ return response
47
+ except (IndexError, KeyError):
48
+ pass
49
+ return '', 404
50
+
51
+
52
+ @app.route('/metrics')
53
+ @requires_auth
54
+ def prometheus_metrics():
55
+ r = make_response(generate_latest())
56
+ r.content_type = CONTENT_TYPE_LATEST
57
+ return r
@@ -0,0 +1,32 @@
1
+ from prometheus_client.metrics_core import GaugeMetricFamily
2
+ from prometheus_client.registry import REGISTRY
3
+
4
+ import glob
5
+
6
+
7
+ class CaptureDevicesCollector(object):
8
+ '''Return metrics about available capture devices.
9
+ '''
10
+
11
+ def __init__(self, registry=REGISTRY):
12
+ registry.register(self)
13
+
14
+ def collect(self):
15
+ devices = GaugeMetricFamily(
16
+ 'video_devices',
17
+ 'Available video devices',
18
+ labels=['device']
19
+ )
20
+
21
+ device_list = glob.glob('/dev/video*')
22
+
23
+ for device in device_list:
24
+ devices.add_metric(
25
+ [device],
26
+ value=1.0
27
+ )
28
+
29
+ yield devices
30
+
31
+
32
+ CAPTURE_DEVICES_COLLECTOR = CaptureDevicesCollector()