-
Notifications
You must be signed in to change notification settings - Fork 477
/
rsync.py
736 lines (603 loc) · 26.4 KB
/
rsync.py
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
# Copyright 2017 iXsystems, Inc.
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#####################################################################
import asyncio
import asyncssh
import contextlib
import enum
import glob
import os
import shlex
from middlewared.common.attachment import LockableFSAttachmentDelegate
from middlewared.schema import accepts, Bool, Cron, Dict, Str, Int, List, Patch
from middlewared.validators import Range, Match
from middlewared.service import (
CallError, SystemServiceService, ValidationErrors, job, item_method, private, SharingService, TaskPathService,
)
import middlewared.sqlalchemy as sa
from middlewared.utils.osc import run_command_with_user_context
RSYNC_PATH_LIMIT = 1023
class RsyncReturnCode(enum.Enum):
# from rsync's "errcode.h"
OK = 0
SYNTAX = 1 # syntax or usage error
PROTOCOL = 2 # protocol incompatibility
FILESELECT = 3 # errors selecting input/output files, dirs
UNSUPPORTED = 4 # requested action not supported
STARTCLIENT = 5 # error starting client-server protocol
SOCKETIO = 10 # error in socket IO
FILEIO = 11 # error in file IO
STREAMIO = 12 # error in rsync protocol data stream
MESSAGEIO = 13 # errors with program diagnostics
IPC = 14 # error in IPC code
CRASHED = 15 # sibling crashed
TERMINATED = 16 # sibling terminated abnormally
SIGNAL1 = 19 # status returned when sent SIGUSR1
SIGNAL = 20 # status returned when sent SIGINT, SIGTERM, SIGHUP
WAITCHILD = 21 # some error returned by waitpid()
MALLOC = 22 # error allocating core memory buffers
PARTIAL = 23 # partial transfer
VANISHED = 24 # file(s) vanished on sender side
DEL_LIMIT = 25 # skipped some deletes due to --max-delete
TIMEOUT = 30 # timeout in data send/receive
CONTIMEOUT = 35 # timeout waiting for daemon connection
@classmethod
def nonfatals(cls):
return tuple([rc.value for rc in [
cls.OK,
cls.VANISHED,
cls.DEL_LIMIT
]])
class RsyncdModel(sa.Model):
__tablename__ = 'services_rsyncd'
id = sa.Column(sa.Integer(), primary_key=True)
rsyncd_port = sa.Column(sa.Integer(), default=873)
rsyncd_auxiliary = sa.Column(sa.Text())
class RsyncdService(SystemServiceService):
class Config:
service = "rsync"
service_model = 'rsyncd'
datastore_prefix = "rsyncd_"
@accepts(Dict(
'rsyncd_update',
Int('port', validators=[Range(min=1, max=65535)]),
Str('auxiliary', max_length=None),
update=True
))
async def do_update(self, data):
"""
Update Rsyncd Service Configuration.
`auxiliary` attribute can be used to pass on any additional parameters from rsyncd.conf(5).
"""
old = await self.config()
new = old.copy()
new.update(data)
await self._update_service(old, new)
return new
class RsyncModModel(sa.Model):
__tablename__ = 'services_rsyncmod'
id = sa.Column(sa.Integer(), primary_key=True)
rsyncmod_name = sa.Column(sa.String(120))
rsyncmod_comment = sa.Column(sa.String(120))
rsyncmod_path = sa.Column(sa.String(255))
rsyncmod_mode = sa.Column(sa.String(120), default="rw")
rsyncmod_maxconn = sa.Column(sa.Integer(), default=0)
rsyncmod_user = sa.Column(sa.String(120), default="nobody")
rsyncmod_group = sa.Column(sa.String(120), default="nobody")
rsyncmod_hostsallow = sa.Column(sa.Text())
rsyncmod_hostsdeny = sa.Column(sa.Text())
rsyncmod_auxiliary = sa.Column(sa.Text())
rsyncmod_enabled = sa.Column(sa.Boolean())
class RsyncModService(SharingService):
share_task_type = 'Rsync Module'
class Config:
datastore = 'services.rsyncmod'
datastore_prefix = 'rsyncmod_'
datastore_extend = 'rsyncmod.rsync_mod_extend'
@private
async def rsync_mod_extend(self, data):
data['hostsallow'] = data['hostsallow'].split()
data['hostsdeny'] = data['hostsdeny'].split()
data['mode'] = data['mode'].upper()
return data
@private
async def common_validation(self, data, schema_name):
verrors = ValidationErrors()
await self.validate_path_field(data, schema_name, verrors)
for entity in ('user', 'group'):
value = data.get(entity)
try:
await self.middleware.call(f'{entity}.get_{entity}_obj', {f'{entity}name': value})
except Exception:
verrors.add(
f'{schema_name}.{entity}',
f'Please specify a valid {entity}'
)
verrors.check()
data['hostsallow'] = ' '.join(data['hostsallow'])
data['hostsdeny'] = ' '.join(data['hostsdeny'])
data['mode'] = data['mode'].lower()
return data
@accepts(Dict(
'rsyncmod_create',
Bool('enabled', default=True),
Str('name', validators=[Match(r'[^/\]]')]),
Str('comment'),
Str('path', required=True, max_length=RSYNC_PATH_LIMIT),
Str('mode', enum=['RO', 'RW', 'WO']),
Int('maxconn'),
Str('user', default='nobody'),
Str('group', default='nobody'),
List('hostsallow', items=[Str('hostsallow')], default=[]),
List('hostsdeny', items=[Str('hostdeny')], default=[]),
Str('auxiliary', max_length=None),
register=True,
))
async def do_create(self, data):
"""
Create a Rsyncmod module.
`path` represents the path to a dataset. Path length is limited to 1023 characters maximum as per the limit
enforced by FreeBSD. It is possible that we reach this max length recursively while transferring data. In that
case, the user must ensure the maximum path will not be too long or modify the recursed path to shorter
than the limit.
`maxconn` is an integer value representing the maximum number of simultaneous connections. Zero represents
unlimited.
`hostsallow` is a list of patterns to match hostname/ip address of a connecting client. If list is empty,
all hosts are allowed.
`hostsdeny` is a list of patterns to match hostname/ip address of a connecting client. If the pattern is
matched, access is denied to the client. If no client should be denied, this should be left empty.
`auxiliary` attribute can be used to pass on any additional parameters from rsyncd.conf(5).
"""
data = await self.common_validation(data, 'rsyncmod_create')
data['id'] = await self.middleware.call(
'datastore.insert',
self._config.datastore,
data,
{'prefix': self._config.datastore_prefix}
)
await self._service_change('rsync', 'reload')
return await self._get_instance(data['id'])
@accepts(Int('id'), Patch('rsyncmod_create', 'rsyncmod_update', ('attr', {'update': True})))
async def do_update(self, id, data):
"""
Update Rsyncmod module of `id`.
"""
module = await self.get_instance(id)
module.update(data)
module = await self.common_validation(module, 'rsyncmod_update')
module.pop(self.locked_field)
await self.middleware.call(
'datastore.update',
self._config.datastore,
id,
module,
{'prefix': self._config.datastore_prefix}
)
await self._service_change('rsync', 'reload')
return await self.get_instance(id)
@accepts(Int('id'))
async def do_delete(self, id):
"""
Delete Rsyncmod module of `id`.
"""
return await self.middleware.call('datastore.delete', self._config.datastore, id)
class RsyncTaskModel(sa.Model):
__tablename__ = 'tasks_rsync'
id = sa.Column(sa.Integer(), primary_key=True)
rsync_path = sa.Column(sa.String(255))
rsync_remotehost = sa.Column(sa.String(120))
rsync_remotemodule = sa.Column(sa.String(120))
rsync_desc = sa.Column(sa.String(120))
rsync_minute = sa.Column(sa.String(100), default="00")
rsync_hour = sa.Column(sa.String(100), default="*")
rsync_daymonth = sa.Column(sa.String(100), default="*")
rsync_month = sa.Column(sa.String(100), default='*')
rsync_dayweek = sa.Column(sa.String(100), default="*")
rsync_user = sa.Column(sa.String(60))
rsync_recursive = sa.Column(sa.Boolean(), default=True)
rsync_times = sa.Column(sa.Boolean(), default=True)
rsync_compress = sa.Column(sa.Boolean(), default=True)
rsync_archive = sa.Column(sa.Boolean(), default=False)
rsync_delete = sa.Column(sa.Boolean(), default=False)
rsync_quiet = sa.Column(sa.Boolean(), default=False)
rsync_preserveperm = sa.Column(sa.Boolean(), default=False)
rsync_preserveattr = sa.Column(sa.Boolean(), default=False)
rsync_extra = sa.Column(sa.Text())
rsync_enabled = sa.Column(sa.Boolean(), default=True)
rsync_mode = sa.Column(sa.String(20), default='module')
rsync_remotepath = sa.Column(sa.String(255))
rsync_direction = sa.Column(sa.String(10), default='PUSH')
rsync_remoteport = sa.Column(sa.SmallInteger(), default=22)
rsync_delayupdates = sa.Column(sa.Boolean(), default=True)
class RsyncTaskService(TaskPathService):
share_task_type = 'Rsync'
class Config:
datastore = 'tasks.rsync'
datastore_prefix = 'rsync_'
datastore_extend = 'rsynctask.rsync_task_extend'
datastore_extend_context = 'rsynctask.rsync_task_extend_context'
@private
async def rsync_task_extend(self, data, context):
data['extra'] = shlex.split(data['extra'].replace('"', r'"\"').replace("'", r'"\"'))
for field in ('mode', 'direction'):
data[field] = data[field].upper()
Cron.convert_db_format_to_schedule(data)
data['job'] = context['jobs'].get(data['id'])
return data
@private
async def rsync_task_extend_context(self, extra):
jobs = {}
for j in await self.middleware.call("core.get_jobs", [("method", "=", "rsynctask.run")],
{"order_by": ["id"]}):
try:
task_id = int(j["arguments"][0])
except (IndexError, ValueError):
continue
if task_id in jobs and jobs[task_id]["state"] == "RUNNING":
continue
jobs[task_id] = j
return {
"jobs": jobs,
}
@private
async def validate_rsync_task(self, data, schema):
verrors = ValidationErrors()
# Windows users can have spaces in their usernames
# http://www.freebsd.org/cgi/query-pr.cgi?pr=164808
username = data.get('user')
if ' ' in username:
verrors.add(f'{schema}.user', 'User names cannot have spaces')
raise verrors
user = None
with contextlib.suppress(KeyError):
user = await self.middleware.call('dscache.get_uncached_user', username)
if not user:
verrors.add(f'{schema}.user', f'Provided user "{username}" does not exist')
raise verrors
await self.validate_path_field(data, schema, verrors)
remote_host = data.get('remotehost')
if not remote_host:
verrors.add(f'{schema}.remotehost', 'Please specify a remote host')
if data.get('extra'):
data['extra'] = ' '.join(data['extra'])
else:
data['extra'] = ''
mode = data.get('mode')
if not mode:
verrors.add(f'{schema}.mode', 'This field is required')
remote_module = data.get('remotemodule')
if mode == 'MODULE' and not remote_module:
verrors.add(f'{schema}.remotemodule', 'This field is required')
if mode == 'SSH':
remote_port = data.get('remoteport')
if not remote_port:
verrors.add(f'{schema}.remoteport', 'This field is required')
remote_path = data.get('remotepath')
if not remote_path:
verrors.add(f'{schema}.remotepath', 'This field is required')
search = os.path.join(user['pw_dir'], '.ssh', 'id_[edr]*')
exclude_from_search = os.path.join(user['pw_dir'], '.ssh', 'id_[edr]*pub')
key_files = set(glob.glob(search)) - set(glob.glob(exclude_from_search))
if not key_files:
verrors.add(
f'{schema}.user',
'In order to use rsync over SSH you need a user'
' with a private key (DSA/ECDSA/RSA) set up in home dir.'
)
else:
for file in glob.glob(search):
if '.pub' not in file:
# file holds a private key and it's permissions should be 600
if os.stat(file).st_mode & 0o077 != 0:
verrors.add(
f'{schema}.user',
f'Permissions {oct(os.stat(file).st_mode & 0o777)} for {file} are too open. Please '
f'correct them by running chmod 600 {file}'
)
if(
data['enabled'] and data['validate_rpath'] and remote_path and remote_host and remote_port
):
if '@' in remote_host:
remote_username, remote_host = remote_host.rsplit('@', 1)
else:
remote_username = username
try:
async with await asyncio.wait_for(
asyncssh.connect(
remote_host, port=remote_port, username=remote_username,
client_keys=key_files, known_hosts=None
), timeout=5,
) as conn:
await conn.run(f'test -d {shlex.quote(remote_path)}', check=True)
except asyncio.TimeoutError:
verrors.add(
f'{schema}.remotehost',
'SSH timeout occurred. Remote path cannot be validated.'
)
except OSError as e:
if e.errno == 113:
verrors.add(
f'{schema}.remotehost',
f'Connection to the remote host {remote_host} on port {remote_port} failed.'
)
else:
verrors.add(
f'{schema}.remotehost',
e.__str__()
)
except asyncssh.DisconnectError as e:
verrors.add(
f'{schema}.remotehost',
f'Disconnect Error[ error code {e.code} ] was generated when trying to '
f'communicate with remote host {remote_host} and remote user {remote_username}.'
)
except asyncssh.ProcessError as e:
if e.code == '1':
verrors.add(
f'{schema}.remotepath',
'The Remote Path you specified does not exist or is not a directory.'
'Either create one yourself on the remote machine or uncheck the '
'validate_rpath field'
)
else:
verrors.add(
f'{schema}.remotepath',
f'Connection to Remote Host was successful but failed to verify '
f'Remote Path. {e.__str__()}'
)
except asyncssh.Error as e:
if e.__class__.__name__ in e.__str__():
exception_reason = e.__str__()
else:
exception_reason = e.__class__.__name__ + ' ' + e.__str__()
verrors.add(
f'{schema}.remotepath',
f'Remote Path could not be validated. An exception was raised. {exception_reason}'
)
elif data['enabled'] and data['validate_rpath']:
verrors.add(
f'{schema}.remotepath',
'Remote path could not be validated because of missing fields'
)
data.pop('validate_rpath', None)
# Keeping compatibility with legacy UI
for field in ('mode', 'direction'):
data[field] = data[field].lower()
return verrors, data
@accepts(Dict(
'rsync_task_create',
Str('path', required=True, max_length=RSYNC_PATH_LIMIT),
Str('user', required=True),
Str('remotehost'),
Int('remoteport'),
Str('mode', enum=['MODULE', 'SSH'], default='MODULE'),
Str('remotemodule'),
Str('remotepath'),
Bool('validate_rpath', default=True),
Str('direction', enum=['PULL', 'PUSH'], default='PUSH'),
Str('desc'),
Cron(
'schedule',
defaults={'minute': '00'},
),
Bool('recursive'),
Bool('times'),
Bool('compress'),
Bool('archive'),
Bool('delete'),
Bool('quiet'),
Bool('preserveperm'),
Bool('preserveattr'),
Bool('delayupdates'),
List('extra', items=[Str('extra')]),
Bool('enabled', default=True),
register=True,
))
async def do_create(self, data):
"""
Create a Rsync Task.
See the comment in Rsyncmod about `path` length limits.
`remotehost` is ip address or hostname of the remote system. If username differs on the remote host,
"username@remote_host" format should be used.
`mode` represents different operating mechanisms for Rsync i.e Rsync Module mode / Rsync SSH mode.
`remotemodule` is the name of remote module, this attribute should be specified when `mode` is set to MODULE.
`remotepath` specifies the path on the remote system.
`validate_rpath` is a boolean which when sets validates the existence of the remote path.
`direction` specifies if data should be PULLED or PUSHED from the remote system.
`compress` when set reduces the size of the data which is to be transmitted.
`archive` when set makes rsync run recursively, preserving symlinks, permissions, modification times, group,
and special files.
`delete` when set deletes files in the destination directory which do not exist in the source directory.
`preserveperm` when set preserves original file permissions.
.. examples(websocket)::
Create a Rsync Task which pulls data from a remote system every 5 minutes.
:::javascript
{
"id": "6841f242-840a-11e6-a437-00e04d680384",
"msg": "method",
"method": "rsynctask.create",
"params": [{
"enabled": true,
"schedule": {
"minute": "5",
"hour": "*",
"dom": "*",
"month": "*",
"dow": "*"
},
"desc": "Test rsync task",
"user": "root",
"mode": "MODULE",
"remotehost": "root@192.168.0.10",
"compress": true,
"archive": true,
"direction": "PULL",
"path": "/mnt/vol1/rsync_dataset",
"remotemodule": "remote_module1"
}]
}
"""
verrors, data = await self.validate_rsync_task(data, 'rsync_task_create')
if verrors:
raise verrors
Cron.convert_schedule_to_db_format(data)
data['id'] = await self.middleware.call(
'datastore.insert',
self._config.datastore,
data,
{'prefix': self._config.datastore_prefix}
)
await self.middleware.call('service.restart', 'cron')
return await self.get_instance(data['id'])
@accepts(
Int('id', validators=[Range(min=1)]),
Patch('rsync_task_create', 'rsync_task_update', ('attr', {'update': True}))
)
async def do_update(self, id, data):
"""
Update Rsync Task of `id`.
"""
old = await self.query(filters=[('id', '=', id)], options={'get': True})
old.pop('job')
new = old.copy()
new.update(data)
verrors, data = await self.validate_rsync_task(new, 'rsync_task_update')
if verrors:
raise verrors
Cron.convert_schedule_to_db_format(new)
new.pop(self.locked_field)
await self.middleware.call(
'datastore.update',
self._config.datastore,
id,
new,
{'prefix': self._config.datastore_prefix}
)
await self.middleware.call('service.restart', 'cron')
return await self.get_instance(id)
@accepts(Int('id'))
async def do_delete(self, id):
"""
Delete Rsync Task of `id`.
"""
res = await self.middleware.call('datastore.delete', self._config.datastore, id)
await self.middleware.call('service.restart', 'cron')
return res
@private
async def commandline(self, id):
"""
Helper method to generate the rsync command avoiding code duplication.
"""
rsync = await self._get_instance(id)
path = shlex.quote(rsync['path'])
line = ['rsync']
for name, flag in (
('archive', '-a'),
('compress', '-z'),
('delayupdates', '--delay-updates'),
('delete', '--delete-delay'),
('preserveattr', '-X'),
('preserveperm', '-p'),
('recursive', '-r'),
('times', '-t'),
):
if rsync[name]:
line.append(flag)
if rsync['extra']:
line.append(' '.join(rsync['extra']))
# Do not use username if one is specified in host field
# See #5096 for more details
if '@' in rsync['remotehost']:
remote = rsync['remotehost']
else:
remote = f'"{rsync["user"]}"@{rsync["remotehost"]}'
if rsync['mode'] == 'MODULE':
module_args = [path, f'{remote}::"{rsync["remotemodule"]}"']
if rsync['direction'] != 'PUSH':
module_args.reverse()
line += module_args
else:
line += [
'-e',
f'"ssh -p {rsync["remoteport"]} -o BatchMode=yes -o StrictHostKeyChecking=yes"'
]
path_args = [path, f'{remote}:"{shlex.quote(rsync["remotepath"])}"']
if rsync['direction'] != 'PUSH':
path_args.reverse()
line += path_args
if rsync['quiet']:
line += ['>', '/dev/null', '2>&1']
return ' '.join(line)
@item_method
@accepts(Int('id'))
@job(lock=lambda args: args[-1], lock_queue_size=1, logs=True)
def run(self, job, id):
"""
Job to run rsync task of `id`.
Output is saved to job log excerpt (not syslog).
"""
rsync = self.middleware.call_sync('rsynctask.get_instance', id)
if rsync['locked']:
self.middleware.call_sync('rsynctask.generate_locked_alert', id)
return
commandline = self.middleware.call_sync('rsynctask.commandline', id)
cp = run_command_with_user_context(
commandline, rsync['user'], lambda v: job.logs_fd.write(v)
)
for klass in ('RsyncSuccess', 'RsyncFailed') if not rsync['quiet'] else ():
self.middleware.call_sync('alert.oneshot_delete', klass, rsync['id'])
if cp.returncode not in RsyncReturnCode.nonfatals():
if not rsync['quiet']:
self.middleware.call_sync('alert.oneshot_create', 'RsyncFailed', {
'id': rsync['id'],
'direction': rsync['direction'],
'path': rsync['path'],
})
raise CallError(
f'rsync command returned {cp.returncode}. Check logs for further information.'
)
elif not rsync['quiet']:
self.middleware.call_sync('alert.oneshot_create', 'RsyncSuccess', {
'id': rsync['id'],
'direction': rsync['direction'],
'path': rsync['path'],
})
class RsyncModuleFSAttachmentDelegate(LockableFSAttachmentDelegate):
name = 'rsync_module'
title = 'Rsync Module'
service = 'rsync'
service_class = RsyncModService
async def restart_reload_services(self, attachments):
await self._service_change('rsync', 'reload')
class RsyncFSAttachmentDelegate(LockableFSAttachmentDelegate):
name = 'rsync'
title = 'Rsync Task'
service_class = RsyncTaskService
resource_name = 'path'
async def restart_reload_services(self, attachments):
await self.middleware.call('service.restart', 'cron')
async def setup(middleware):
await middleware.call('pool.dataset.register_attachment_delegate', RsyncModuleFSAttachmentDelegate(middleware))
await middleware.call('pool.dataset.register_attachment_delegate', RsyncFSAttachmentDelegate(middleware))