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/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ python-capture-agent
4
+ ~~~~~~~~~~~~~~~~~~~~
5
+
6
+ :copyright: 2014-2015, Lars Kiesow <lkiesow@uos.de>
7
+ :license: LGPL – see LICENSE for more details.
8
+ '''
pyca/__main__.py ADDED
@@ -0,0 +1,140 @@
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
+ import getopt
11
+ import multiprocessing
12
+ import signal
13
+ import sys
14
+ from pyca import capture, config, schedule, ingest, ui, agentstate, utils
15
+ from pyca.db import get_session
16
+
17
+ # The services run in their own processes and rely on inheriting the state of
18
+ # the main process, like the configuration loaded from the file specified on
19
+ # the command line and the signal handlers. Only the fork start method does
20
+ # that, but it is no longer the default since Python 3.14.
21
+ fork_context = multiprocessing.get_context('fork')
22
+
23
+ USAGE = '''
24
+ Usage %s [OPTIONS] COMMAND
25
+
26
+ COMMANDS:
27
+ run -- Start all pyCA components except ui (default)
28
+ all -- Start all components (for testing only)
29
+ capture -- Start pyCA capture service
30
+ ingest -- Start pyCA ingest service
31
+ schedule -- Start pyCA schedule service
32
+ agentstate -- Start pyCA agentstate service
33
+ ui -- Start web based user interface
34
+
35
+ OPTIONS:
36
+ --help, -h -- Show this help',
37
+ --config=FILE, -c FILE -- Specify a config file',
38
+
39
+ CONFIGURATION:
40
+ PyCA will try to find a configuration in the following order:
41
+ - Configuration specified on the command line
42
+ - ./etc/pyca.conf
43
+ - /etc/pyca/pyca.conf
44
+ '''
45
+
46
+
47
+ def usage(retval=0):
48
+ '''Print usage information to stdout and exit.
49
+ '''
50
+ print(USAGE % sys.argv[0])
51
+ sys.exit(retval)
52
+
53
+
54
+ def sigint_handler(signum, frame):
55
+ '''Intercept sigint and terminate services gracefully.
56
+ '''
57
+ utils.terminate(True)
58
+
59
+
60
+ def sigterm_handler(signum, frame):
61
+ '''Intercept sigterm and terminate all processes.
62
+ '''
63
+ sigint_handler(signum, frame)
64
+ for process in fork_context.active_children():
65
+ process.terminate()
66
+ sys.exit(0)
67
+
68
+
69
+ def run_all(*modules):
70
+ '''Start all services.
71
+ '''
72
+ processes = [fork_context.Process(target=mod.run) for mod in modules]
73
+ for p in processes:
74
+ p.start()
75
+ for p in processes:
76
+ p.join()
77
+
78
+
79
+ def main():
80
+ # Check command line options
81
+ try:
82
+ opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['help', 'config='])
83
+ except getopt.GetoptError:
84
+ usage(1)
85
+
86
+ cfg = None
87
+ for opt, arg in opts:
88
+ if opt in ("-h", "--help"):
89
+ usage()
90
+ if opt in ('-c', '--config'):
91
+ cfg = arg
92
+ break
93
+
94
+ # Make sure we got only one command
95
+ if len(args) > 1:
96
+ usage(2)
97
+
98
+ try:
99
+ config.update_configuration(cfg)
100
+ except ValueError as e:
101
+ print(str(e))
102
+ sys.exit(4)
103
+
104
+ # Set signal handler
105
+ signal.signal(signal.SIGINT, sigint_handler)
106
+ signal.signal(signal.SIGTERM, sigterm_handler)
107
+
108
+ # Get the command with `run` as default
109
+ cmd = (args + ['run'])[0]
110
+
111
+ if cmd == 'run':
112
+ # ensure database is created first
113
+ get_session().close()
114
+ run_all(schedule, capture, ingest, agentstate)
115
+ elif cmd == 'all':
116
+ get_session().close()
117
+ signal.signal(signal.SIGINT, signal.default_int_handler)
118
+ fork_context.Process(
119
+ target=ui.app.run,
120
+ kwargs={'threaded': False}
121
+ ).start()
122
+ run_all(schedule, capture, ingest, agentstate)
123
+ elif cmd == 'schedule':
124
+ schedule.run()
125
+ elif cmd == 'capture':
126
+ capture.run()
127
+ elif cmd == 'ingest':
128
+ ingest.run()
129
+ elif cmd == 'agentstate':
130
+ agentstate.run()
131
+ elif cmd == 'ui':
132
+ signal.signal(signal.SIGINT, signal.default_int_handler)
133
+ ui.app.run(threaded=False)
134
+ else:
135
+ # Invalid command
136
+ usage(3)
137
+
138
+
139
+ if __name__ == '__main__':
140
+ main()
pyca/agentstate.py ADDED
@@ -0,0 +1,45 @@
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 set_service_status, update_agent_state, timestamp
11
+ from pyca.utils import terminate
12
+ from pyca.config import config
13
+ from pyca.db import Service, ServiceStatus
14
+ import logging
15
+ import sdnotify
16
+ import time
17
+
18
+ logger = logging.getLogger(__name__)
19
+ notify = sdnotify.SystemdNotifier()
20
+
21
+
22
+ def control_loop():
23
+ '''Main loop, updating the capture agent state.
24
+ '''
25
+ set_service_status(Service.AGENTSTATE, ServiceStatus.BUSY)
26
+ notify.notify('READY=1')
27
+ notify.notify('STATUS=Running')
28
+ while not terminate():
29
+ notify.notify('WATCHDOG=1')
30
+
31
+ next_update = timestamp() + config('agent', 'update_frequency')
32
+ while not terminate() and timestamp() < next_update:
33
+ time.sleep(0.1)
34
+
35
+ if not terminate():
36
+ update_agent_state()
37
+
38
+ logger.info('Shutting down agentstate service')
39
+ set_service_status(Service.AGENTSTATE, ServiceStatus.STOPPED)
40
+
41
+
42
+ def run():
43
+ '''Start the capture agent state process.
44
+ '''
45
+ control_loop()
pyca/capture.py ADDED
@@ -0,0 +1,218 @@
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 timestamp, try_mkdir, terminate
11
+ from pyca.utils import set_service_status, set_service_status_immediate
12
+ from pyca.utils import recording_state, update_event_status
13
+ from pyca.config import config
14
+ from pyca.db import get_session, RecordedEvent, UpcomingEvent, Status, \
15
+ Service, ServiceStatus, with_session
16
+ import glob
17
+ import logging
18
+ import os
19
+ import os.path
20
+ import sdnotify
21
+ import shlex
22
+ import signal
23
+ import subprocess
24
+ import sys
25
+ import time
26
+
27
+ logger = logging.getLogger(__name__)
28
+ notify = sdnotify.SystemdNotifier()
29
+ captureproc = None
30
+
31
+
32
+ def sigterm_handler(signum, frame):
33
+ '''Intercept sigterm and terminate all processes.
34
+ '''
35
+ if captureproc and captureproc.poll() is None:
36
+ captureproc.terminate()
37
+ terminate(True)
38
+ sys.exit(0)
39
+
40
+
41
+ @with_session
42
+ def start_capture(db, upcoming_event):
43
+ '''Start the capture process, creating all necessary files and directories
44
+ as well as ingesting the captured files if no backup mode is configured.
45
+ '''
46
+ logger.info('Start recording')
47
+
48
+ # First move event to recording_event table
49
+ event = db.query(RecordedEvent)\
50
+ .filter(RecordedEvent.uid == upcoming_event.uid)\
51
+ .filter(RecordedEvent.start == upcoming_event.start)\
52
+ .first()
53
+ if not event:
54
+ event = RecordedEvent(upcoming_event)
55
+ db.add(event)
56
+ db.commit()
57
+
58
+ try_mkdir(config('capture', 'directory'))
59
+ try_mkdir(event.directory())
60
+
61
+ # Set state
62
+ update_event_status(event, Status.RECORDING)
63
+ recording_state(event.uid, 'capturing')
64
+ set_service_status_immediate(Service.CAPTURE, ServiceStatus.BUSY)
65
+
66
+ # Recording
67
+ files = recording_command(event)
68
+ # [(flavor,path),…]
69
+ event.set_tracks(list(zip(config('capture', 'flavors'), files)))
70
+ db.commit()
71
+
72
+ # Set status
73
+ # If part files exist, its an partial recording
74
+ part_files = any([glob.glob(f'{f}-part-*') for f in files])
75
+ if part_files:
76
+ state = Status.PARTIAL_RECORDING
77
+ elif config('agent', 'backup_mode'):
78
+ state = Status.PAUSED_AFTER_RECORDING
79
+ else:
80
+ state = Status.FINISHED_RECORDING
81
+
82
+ logger.info("Set %s to %s", event.uid, Status.str(state))
83
+ update_event_status(event, state)
84
+ recording_state(event.uid, 'capture_finished')
85
+ set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE)
86
+
87
+ logger.info('Finished recording')
88
+
89
+
90
+ def safe_start_capture(event):
91
+ '''Start a capture process but make sure to catch any errors during this
92
+ process, log them but otherwise ignore them.
93
+ '''
94
+ try:
95
+ start_capture(event)
96
+ except Exception:
97
+ logger.exception('Recording failed')
98
+ # Update current status in Opencast
99
+ try:
100
+ set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE)
101
+ recording_state(event.uid, 'capture_error')
102
+ update_event_status(event, Status.FAILED_RECORDING)
103
+ except Exception:
104
+ logger.exception('Could not update recording status')
105
+
106
+
107
+ def recording_command(event):
108
+ '''Run the actual command to record the a/v material.
109
+ '''
110
+ conf = config('capture')
111
+ # Prepare command line
112
+ cmd = conf['command']
113
+ cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp())))
114
+ cmd = cmd.replace('{{dir}}', event.directory())
115
+ cmd = cmd.replace('{{name}}', event.name())
116
+ cmd = cmd.replace('{{previewdir}}', conf['preview_dir'])
117
+
118
+ # Parse files into list
119
+ files = (f.replace('{{dir}}', event.directory()) for f in conf['files'])
120
+ files = [f.replace('{{name}}', event.name()) for f in files]
121
+
122
+ # Move existing files from previous failed recordings
123
+ for f in files:
124
+ if not os.path.exists(f):
125
+ continue
126
+ # New filename
127
+ i = 0
128
+ while True:
129
+ new_filename = f'{f}-part-{i}'
130
+ if not os.path.exists(new_filename):
131
+ break
132
+ i += 1
133
+ # Move file
134
+ os.rename(f, new_filename)
135
+ logger.warning("Moved file %s to %s to keep it", f, new_filename)
136
+
137
+ # Signal configuration
138
+ sigterm_time = conf['sigterm_time']
139
+ sigkill_time = conf['sigkill_time']
140
+ sigcustom_time = conf['sigcustom_time']
141
+ sigcustom_time = 0 if sigcustom_time < 0 else event.end + sigcustom_time
142
+ sigterm_time = 0 if sigterm_time < 0 else event.end + sigterm_time
143
+ sigkill_time = 0 if sigkill_time < 0 else event.end + sigkill_time
144
+
145
+ # Launch capture command
146
+ logger.info(cmd)
147
+ args = shlex.split(cmd)
148
+ DEVNULL = getattr(subprocess, 'DEVNULL', os.open(os.devnull, os.O_RDWR))
149
+ captureproc = subprocess.Popen(args, stdin=DEVNULL)
150
+ hasattr(subprocess, 'DEVNULL') or os.close(DEVNULL)
151
+
152
+ # Set systemd status
153
+ notify.notify('STATUS=Capturing')
154
+
155
+ # Check process
156
+ while captureproc.poll() is None:
157
+ notify.notify('WATCHDOG=1')
158
+ if sigcustom_time and timestamp() > sigcustom_time:
159
+ logger.info("Sending custom signal to capture process")
160
+ captureproc.send_signal(conf['sigcustom'])
161
+ sigcustom_time = 0 # send only once
162
+ if sigterm_time and timestamp() > sigterm_time:
163
+ logger.info("Terminating capture process")
164
+ captureproc.terminate()
165
+ sigterm_time = 0 # send only once
166
+ elif sigkill_time and timestamp() > sigkill_time:
167
+ logger.warning("Killing capture process")
168
+ captureproc.kill()
169
+ sigkill_time = 0 # send only once
170
+ time.sleep(0.1)
171
+
172
+ # Remove preview files:
173
+ for preview in conf['preview']:
174
+ try:
175
+ os.remove(preview.replace('{{previewdir}}', conf['preview_dir']))
176
+ except OSError:
177
+ logger.warning('Could not remove preview files', exc_info=True)
178
+
179
+ # Check process for errors
180
+ exitcode = conf['exit_code']
181
+ if captureproc.poll() > 0 and captureproc.returncode != exitcode:
182
+ raise RuntimeError('Recording failed (%i)' % captureproc.returncode)
183
+
184
+ # Reset systemd status
185
+ notify.notify('STATUS=Waiting')
186
+
187
+ # files
188
+ return files
189
+
190
+
191
+ def control_loop():
192
+ '''Main loop of the capture agent, retrieving and checking the schedule as
193
+ well as starting the capture process if necessry.
194
+ '''
195
+ set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE)
196
+ notify.notify('READY=1')
197
+ notify.notify('STATUS=Waiting')
198
+ while not terminate():
199
+ notify.notify('WATCHDOG=1')
200
+ # Get next recording
201
+ session = get_session()
202
+ event = session.query(UpcomingEvent)\
203
+ .filter(UpcomingEvent.start <= timestamp())\
204
+ .filter(UpcomingEvent.end > timestamp())\
205
+ .first()
206
+ if event:
207
+ safe_start_capture(event)
208
+ session.close()
209
+ time.sleep(1.0)
210
+ logger.info('Shutting down capture service')
211
+ set_service_status(Service.CAPTURE, ServiceStatus.STOPPED)
212
+
213
+
214
+ def run():
215
+ '''Start the capture agent.
216
+ '''
217
+ signal.signal(signal.SIGTERM, sigterm_handler)
218
+ control_loop()
pyca/config.py ADDED
@@ -0,0 +1,180 @@
1
+ # -*- coding: utf-8 -*-
2
+ '''
3
+ Default configuration for pyCA.
4
+ '''
5
+
6
+ import configobj
7
+ import logging
8
+ import logging.handlers
9
+ import os
10
+ import socket
11
+ import sys
12
+ from validate import Validator
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ __CFG = '''
17
+ [agent]
18
+ name = string(default='')
19
+ update_frequency = integer(min=5, default=60)
20
+ cal_lookahead = integer(min=0, default=14)
21
+ backup_mode = boolean(default=false)
22
+ database = string(default='sqlite:///pyca.db')
23
+
24
+ [capture]
25
+ directory = string(default='./recordings')
26
+ command = string(default='ffmpeg -nostats -re -f lavfi -r 25 -i testsrc -t {{time}} {{dir}}/{{name}}.webm')
27
+ flavors = force_list(default=list('presenter/source'))
28
+ files = force_list(default=list('{{dir}}/{{name}}.webm'))
29
+ preview_dir = string(default='./recordings')
30
+ preview = force_list(default=list())
31
+ sigcustom = integer(min=1, default=2)
32
+ sigcustom_time = integer(min=-1, default=-1)
33
+ sigterm_time = integer(min=-1, default=-1)
34
+ sigkill_time = integer(min=-1, default=120)
35
+ exit_code = integer(min=0, max=255, default=0)
36
+
37
+ [ingest]
38
+ delay_max = integer(min=0, default=0)
39
+ delay_min = integer(min=0, default=0)
40
+ delete_after_upload = boolean(default=false)
41
+ upload_catalogs = boolean(default=false)
42
+ upload_rate = string(default='0')
43
+
44
+ [server]
45
+ url = string(default='https://develop.opencast.org')
46
+ auth_method = option('basic', 'digest', default='basic')
47
+ username = string(default='admin')
48
+ password = string(default='opencast')
49
+ insecure = boolean(default=False)
50
+ certificate = string(default='')
51
+ cookiefile = string(default='')
52
+ [[service_overrides]]
53
+
54
+ [ui]
55
+ username = string(default='admin')
56
+ password = string(default='opencast')
57
+ refresh_rate = integer(min=1, default=10)
58
+ url = string(default='http://localhost:5000')
59
+ log_command = string(default='')
60
+
61
+ [logging]
62
+ syslog = boolean(default=False)
63
+ stderr = boolean(default=True)
64
+ file = string(default='')
65
+ level = option('debug', 'info', 'warning', 'error', default='info')
66
+ format = string(default='[%(name)s:%(lineno)s:%(funcName)s()] [%(levelname)s] %(message)s')
67
+
68
+ [http]
69
+ timeout = integer(min=0, default=300)
70
+ connection_timeout = integer(min=0, default=180)
71
+
72
+ [services]
73
+ ''' # noqa
74
+
75
+ cfgspec = __CFG.split('\n')
76
+
77
+ __config = None
78
+
79
+
80
+ def configuration_file(cfgfile):
81
+ '''Find the best match for the configuration file.
82
+ '''
83
+ if cfgfile is not None:
84
+ return cfgfile
85
+ # If no file is explicitely specified, probe for the configuration file
86
+ # location.
87
+ cfg = './etc/pyca.conf'
88
+ if not os.path.isfile(cfg):
89
+ return '/etc/pyca/pyca.conf'
90
+ return cfg
91
+
92
+
93
+ def update_configuration(cfgfile=None):
94
+ '''Update configuration from file.
95
+
96
+ :param cfgfile: Configuration file to load.
97
+ '''
98
+ configobj.DEFAULT_INTERPOLATION = 'template'
99
+ cfgfile = configuration_file(cfgfile)
100
+ cfg = configobj.ConfigObj(cfgfile, configspec=cfgspec, encoding='utf-8')
101
+ validator = Validator()
102
+ val = cfg.validate(validator)
103
+ if val is not True:
104
+ raise ValueError('Invalid configuration: %s' % val)
105
+ if len(cfg['capture']['files']) != len(cfg['capture']['flavors']):
106
+ raise ValueError('List of files and flavors do not match')
107
+ if not cfg['agent']['name']:
108
+ cfg['agent']['name'] = 'pyca@' + socket.gethostname()
109
+ globals()['__config'] = cfg
110
+ logger_init()
111
+ if cfg['server'].get('url', '').endswith('/'):
112
+ logger.warning('Base URL ends with /. This is most likely a '
113
+ 'configuration error. The URL should contain nothing '
114
+ 'of the service paths.')
115
+ if cfg['ingest'].get('upload_rate'):
116
+ # Limit upload rate in bytes per second
117
+ upload_rate = cfg['ingest'].get('upload_rate').lower()
118
+ if upload_rate.endswith('m'):
119
+ upload_rate = upload_rate[0:-1] + '000000'
120
+ elif upload_rate.endswith('k'):
121
+ upload_rate = upload_rate[0:-1] + '000'
122
+ cfg['ingest']['upload_rate'] = int(upload_rate)
123
+ logger.info('Configuration loaded from %s', cfgfile)
124
+ check()
125
+ return cfg
126
+
127
+
128
+ def check():
129
+ '''Check configuration for sanity.
130
+ '''
131
+ if config('server')['insecure']:
132
+ logger.warning('HTTPS CHECKS ARE TURNED OFF. A SECURE CONNECTION IS '
133
+ 'NOT GUARANTEED')
134
+ if config('server')['certificate']:
135
+ # Ensure certificate exists and is readable
136
+ open(config('server')['certificate'], 'rb').close()
137
+ if config('agent')['backup_mode']:
138
+ logger.info('Agent runs in backup mode. No data will be sent to '
139
+ 'Opencast')
140
+
141
+
142
+ def config(*args):
143
+ '''Get a specific configuration value or the whole configuration, loading
144
+ the configuration file if it was not before.
145
+
146
+ :param key: optional configuration key to return
147
+ :type key: string
148
+ :return: Part of the configuration object containing the configuration
149
+ or configuration value.
150
+ If a part of the configuration object (e.g. configobj.Section) is
151
+ returned, it can be treated like a dictionary.
152
+ Returning None, if the configuration value is not found.
153
+ '''
154
+ cfg = __config or update_configuration()
155
+ for key in args:
156
+ if cfg is None:
157
+ return
158
+ cfg = cfg.get(key)
159
+ return cfg
160
+
161
+
162
+ def logger_init():
163
+ '''Initialize logger based on configuration
164
+ '''
165
+ handlers = []
166
+ logconf = config('logging')
167
+ if logconf['syslog']:
168
+ handlers.append(logging.handlers.SysLogHandler(address='/dev/log'))
169
+ if logconf['stderr']:
170
+ handlers.append(logging.StreamHandler(sys.stderr))
171
+ if logconf['file']:
172
+ handlers.append(logging.handlers.WatchedFileHandler(logconf['file']))
173
+ if logging.root.hasHandlers():
174
+ logging.root.handlers.clear()
175
+ for handler in handlers:
176
+ handler.setFormatter(logging.Formatter(logconf['format']))
177
+ logging.root.addHandler(handler)
178
+
179
+ logging.root.setLevel(logconf['level'].upper())
180
+ logger.info('Log level set to %s', logconf['level'])