id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
10,500
test_stats.py
zatosource_zato/code/zato-common/test/zato/common/test_stats.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main, TestCase # Zato from zato.common.util.stats import collect_current_usage # ################################################################################################################################ # ################################################################################################################################ class StatsTestCase(TestCase): def test_collect_current_usage_one_elem(self): value1 = 24 last_timestamp1 = '2021-06-13T19:46:43.910465' last_duration1 = 0.216 data = [{ 'value': value1, 'last_timestamp': last_timestamp1, 'last_duration': last_duration1, }] result = collect_current_usage(data) self.assertEqual(result['value'], value1) self.assertEqual(result['last_timestamp'], last_timestamp1) self.assertEqual(result['last_duration'], last_duration1) # ################################################################################################################################ def test_collect_current_usage_multiple_elems(self): value1 = 24 last_timestamp1 = '2021-11-22T11:22:33.445566' last_duration1 = 0.216 value2 = 297 last_timestamp2 = '2020-10-20T10:20:30.405060' last_duration2 = 82 value3 = 51 last_timestamp3 = '2022-12-22T12:22:32.425262' last_duration3 = 219 data = [ {'value': value1, 'last_timestamp': last_timestamp1, 'last_duration': last_duration1}, {'value': value2, 'last_timestamp': last_timestamp2, 'last_duration': last_duration2}, {'value': value3, 'last_timestamp': last_timestamp3, 'last_duration': last_duration3}, ] result = collect_current_usage(data) self.assertEqual(result['value'], value1 + value2 + value3) self.assertEqual(result['last_timestamp'], last_timestamp3) self.assertEqual(result['last_duration'], last_duration3) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
2,751
Python
.py
51
47.098039
130
0.421583
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,501
test_scheduler.py
zatosource_zato/code/zato-common/test/zato/common/test_scheduler.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import time from datetime import datetime, timedelta from random import choice, seed from unittest import TestCase # Bunch from bunch import Bunch # crontab from crontab import CronTab # ciso8601 try: from zato.common.util.api import parse_datetime except ImportError: from dateutil.parser import parse as parse_datetime # gevent from gevent import sleep, spawn # mock from mock import patch # Zato from zato.common.api import SCHEDULER from zato.common.test import is_like_cid, rand_bool, rand_date_utc, rand_int, rand_string from zato.scheduler.backend import Interval, Job, Scheduler seed() DEFAULT_CRON_DEFINITION = '* * * * *' class RLock: def __init__(self): self.called = 0 def __enter__(self): self.called += 1 def __exit__(self, exc_type, exc_val, exc_tb): return True def dummy_callback(*args, **kwargs): pass def get_job(name=None, interval_in_seconds=None, start_time=None, max_repeats=None, callback=None, prefix='job'): name = name or '{}-{}'.format(prefix, rand_string()) interval_in_seconds = interval_in_seconds or rand_int() start_time = start_time or rand_date_utc() callback = callback or dummy_callback return Job(rand_int(), name, SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(in_seconds=interval_in_seconds), start_time, callback, max_repeats=max_repeats) def iter_cb(scheduler, stop_time): """ Stop the scheduler after stop_time is reached (test_wait_time seconds from test's start time) - which should plenty enough for all the jobs to be spawned and the iteration loop to """ if datetime.utcnow() >= stop_time: scheduler.keep_running = False def get_scheduler_config(): config = Bunch() config.on_job_executed_cb = dummy_callback config._add_startup_jobs = False config._add_scheduler_jobs = False config.startup_jobs = [] config.odb = None config.job_log_level = 'info' return config class IntervalTestCase(TestCase): def test_interval_has_in_seconds(self): in_seconds = rand_int() interval = Interval(in_seconds=in_seconds) self.assertEqual(interval.in_seconds, in_seconds) def test_interval_compute_in_seconds(self): for days, hours, minutes, seconds, expected in ( (55, 83, 69, 75, 5055015.0), (31, 2, 6, 23, 2685983.0), (68, 55, 57, 82, 6076702.0), (0, 69, 42, 12, 250932.0), (0, 48, 0, 17, 172817.0), (0, 0, 192, 17, 11537.0), (0, 0, 7, 0, 420.0), (0, 0, 0, 32, 32.0)): # noqa interval = Interval(days, hours, minutes, seconds) self.assertEqual(interval.in_seconds, expected) class JobTestCase(TestCase): def setUp(self): class _datetime(datetime): class datetime: @staticmethod def utcnow(): return self.now @staticmethod def timedelta(*args, **kwargs): return timedelta(*args, **kwargs) self._datetime = _datetime def check_ctx(self, ctx, job, interval_in_seconds, max_repeats, idx, cb_kwargs, len_runs_ctx, job_type=SCHEDULER.JOB_TYPE.INTERVAL_BASED): self.assertEqual(ctx['name'], job.name) self.assertEqual(ctx['max_repeats'], job.max_repeats) self.assertDictEqual(ctx['cb_kwargs'], job.cb_kwargs) if job_type == SCHEDULER.JOB_TYPE.INTERVAL_BASED: self.assertEqual(ctx['interval_in_seconds'], interval_in_seconds) else: self.assertEqual(ctx['cron_definition'], DEFAULT_CRON_DEFINITION) self.assertEqual(ctx['max_repeats'], max_repeats) self.assertEqual(ctx['current_run'], idx) self.assertDictEqual(ctx['cb_kwargs'], cb_kwargs) func = self.assertFalse if idx < len_runs_ctx else self.assertTrue func(ctx['max_repeats_reached']) # Don't check an exact time. Simply parse it out and confirm it's in the past. start_time = parse_datetime(ctx['start_time']) now = datetime.utcnow() self.assertTrue(start_time < now, 'start_time:`{}` is not less than now:`{}`'.format(start_time, now)) self.assertTrue(is_like_cid(ctx['cid'])) def test_clone(self): interval = Interval(seconds=5) start_time = datetime.utcnow() def callback(): pass def on_max_repeats_reached_cb(): pass job = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, interval, start_time) job.callback = callback job.on_max_repeats_reached_cb = on_max_repeats_reached_cb clone = job.clone() sleep(0.1) for name in 'name', 'interval', 'cb_kwargs', 'max_repeats', 'is_active': expected = getattr(job, name) given = getattr(clone, name) self.assertEqual(expected, given, '{} != {} ({})'.format(expected, given, name)) self.assertEqual(job.start_time, clone.start_time) self.assertIs(job.callback, clone.callback) self.assertIs(job.on_max_repeats_reached_cb, clone.on_max_repeats_reached_cb) def test_get_context(self): id = rand_int() name = rand_string() start_time = rand_date_utc() interval_in_seconds = rand_int() max_repeats_reached = rand_bool() current_run, max_repeats = rand_int(count=2) cb_kwargs = {rand_string():rand_string()} for job_type in SCHEDULER.JOB_TYPE.INTERVAL_BASED, SCHEDULER.JOB_TYPE.CRON_STYLE: interval=Interval(in_seconds=interval_in_seconds) if \ job_type == SCHEDULER.JOB_TYPE.INTERVAL_BASED else CronTab(DEFAULT_CRON_DEFINITION) job = Job(id, name, job_type, cb_kwargs=cb_kwargs, interval=interval) job.start_time = start_time job.current_run = current_run job.max_repeats = max_repeats job.max_repeats_reached = max_repeats_reached if job_type == SCHEDULER.JOB_TYPE.CRON_STYLE: job.cron_definition = DEFAULT_CRON_DEFINITION ctx = job.get_context() cid = ctx.pop('cid') self.assertTrue(is_like_cid(cid)) expected = { 'current_run': current_run, 'id': id, 'name': name, 'start_time': start_time.isoformat(), 'max_repeats': max_repeats, 'max_repeats_reached': max_repeats_reached, 'cb_kwargs': cb_kwargs, 'type': job_type, } if job_type == SCHEDULER.JOB_TYPE.CRON_STYLE: expected['cron_definition'] = job.cron_definition else: expected['interval_in_seconds'] = job.interval.in_seconds self.assertDictEqual(ctx, expected) def test_main_loop_keep_running_false(self): job = get_job() job.keep_running = False self.assertTrue(job.main_loop()) self.assertFalse(job.keep_running) self.assertFalse(job.max_repeats_reached) self.assertEqual(job.current_run, 0) def test_main_loop_max_repeats_reached(self): runs_ctx = [] def callback(ctx): runs_ctx.append(ctx) cb_kwargs = { rand_string():rand_string(), rand_string():rand_string() } interval_in_seconds = 0.01 max_repeats = choice(range(2, 5)) job = get_job(interval_in_seconds=interval_in_seconds, max_repeats=max_repeats) job.callback = callback job.cb_kwargs = cb_kwargs self.assertTrue(job.main_loop()) sleep(0.2) len_runs_ctx = len(runs_ctx) self.assertEqual(len_runs_ctx, max_repeats) self.assertFalse(job.keep_running) self.assertIs(job.callback, callback) for idx, ctx in enumerate(runs_ctx, 1): self.check_ctx(ctx, job, interval_in_seconds, max_repeats, idx, cb_kwargs, len_runs_ctx) def test_main_loop_sleep_spawn_called(self): wait_time = 0.2 sleep_time = rand_int() now_values = [parse_datetime('2019-12-23 22:19:03'), parse_datetime('2021-05-13 17:35:48')] sleep_history = [] spawn_history = [] sleep_time_history = [] def sleep(value): if value != wait_time: sleep_history.append(value) def spawn(*args, **kwargs): spawn_history.append([args, kwargs]) def get_sleep_time(*args, **kwargs): sleep_time_history.append(args[1]) return sleep_time with patch('gevent.sleep', sleep): with patch('zato.scheduler.backend.Job._spawn', spawn): with patch('zato.scheduler.backend.Job.get_sleep_time', get_sleep_time): for now in now_values: self.now = now with patch('zato.scheduler.backend.datetime', self._datetime): for job_type in SCHEDULER.JOB_TYPE.CRON_STYLE, SCHEDULER.JOB_TYPE.INTERVAL_BASED: max_repeats = choice(range(2, 5)) cb_kwargs = { rand_string():rand_string(), rand_string():rand_string() } interval = Interval(seconds=sleep_time) if job_type == SCHEDULER.JOB_TYPE.INTERVAL_BASED \ else CronTab(DEFAULT_CRON_DEFINITION) job = Job(rand_int(), rand_string(), job_type, interval, max_repeats=max_repeats) if job.type == SCHEDULER.JOB_TYPE.CRON_STYLE: job.cron_definition = DEFAULT_CRON_DEFINITION job.cb_kwargs = cb_kwargs job.start_time = datetime.utcnow() job.callback = dummy_callback self.assertTrue(job.main_loop()) time.sleep(0.5) self.assertEqual(max_repeats, len(sleep_history)) self.assertEqual(max_repeats, len(spawn_history)) for item in sleep_history: self.assertEqual(sleep_time, item) for idx, (callback, ctx_dict) in enumerate(spawn_history, 1): self.assertEqual(2, len(callback)) callback = callback[1] self.check_ctx( ctx_dict['ctx'], job, sleep_time, max_repeats, idx, cb_kwargs, len(spawn_history), job_type) self.assertIs(callback, dummy_callback) del sleep_history[:] del spawn_history[:] for item in sleep_time_history: self.assertEqual(item, now) del sleep_time_history[:] def test_run(self): data = {'main_loop_called':False, 'sleep': False} def main_loop(): data['main_loop_called'] = True def sleep(value): data['sleep'] = value # Should not be executed if start_time is None start_time = datetime.utcnow() + timedelta(seconds=1.2) with patch('gevent.sleep', sleep): job = get_job() job.main_loop = main_loop job.start_time = start_time job.run() self.assertTrue(data['main_loop_called']) self.assertEqual(data['sleep'], 1) def test_hash_eq(self): job1 = get_job(name='a') job2 = get_job(name='a') job3 = get_job(name='b') self.assertEqual(job1, job2) self.assertNotEquals(job1, job3) self.assertNotEquals(job2, job3) self.assertEqual(hash(job1), hash('a')) self.assertEqual(hash(job2), hash('a')) self.assertEqual(hash(job3), hash('b')) def test_get_sleep_time(self): now = parse_datetime('2015-11-27 19:13:37.274') job1 = Job(1, 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=5), now) self.assertEqual(job1.get_sleep_time(now), 5) job2 = Job(2, 'b', SCHEDULER.JOB_TYPE.CRON_STYLE, CronTab(DEFAULT_CRON_DEFINITION), now) self.assertEqual(job2.get_sleep_time(now), 22.726) class JobStartTimeTestCase(TestCase): def setUp(self): class _datetime(datetime): class datetime: @staticmethod def utcnow(): return self.now @staticmethod def timedelta(*args, **kwargs): return timedelta(*args, **kwargs) self._datetime = _datetime def check_get_start_time(self, start_time, now, expected): start_time = parse_datetime(start_time) self.now = parse_datetime(now) expected = parse_datetime(expected) interval = 1 # Days data = {'start_time':[], 'now':[]} def wait_iter_cb(start_time, now, *ignored): data['start_time'].append(start_time) data['now'].append(now) with patch('zato.scheduler.backend.datetime', self._datetime): interval = Interval(days=interval) job = Job(rand_int(), rand_string(), SCHEDULER.JOB_TYPE.INTERVAL_BASED, start_time=start_time, interval=interval) job.wait_iter_cb = wait_iter_cb job.wait_sleep_time = 0.1 self.assertEqual(job.start_time, expected) self.assertTrue(job.keep_running) self.assertFalse(job.max_repeats_reached) self.assertIs(job.max_repeats_reached_at, None) spawn(job.run) sleep(0.2) len_start_time = len(data['start_time']) len_now = len(data['now']) self.assertNotEquals(len_start_time, 0) self.assertNotEquals(len_now, 0) for item in data['start_time']: self.assertEqual(expected, item) for item in data['now']: self.assertEqual(self.now, item) def test_get_start_time_result_in_future(self): self.check_get_start_time('2017-03-20 19:11:37', '2017-03-21 15:11:37', '2017-03-21 19:11:37') def test_get_start_time_last_run_in_past_next_run_in_future(self): self.check_get_start_time('2017-03-20 19:11:37', '2017-03-21 21:11:37', '2017-03-22 19:11:37') def test_get_start_time_last_run_in_past_next_run_in_past(self): start_time = parse_datetime('2017-03-20 19:11:23') self.now = parse_datetime('2019-05-13 05:19:37') expected = parse_datetime('2017-04-04 19:11:23') with patch('zato.scheduler.backend.datetime', self._datetime): interval = Interval(days=3) job = Job(rand_int(), rand_string(), SCHEDULER.JOB_TYPE.INTERVAL_BASED, start_time=start_time, interval=interval, max_repeats=5) self.assertFalse(job.keep_running) self.assertTrue(job.max_repeats_reached) self.assertEqual(job.max_repeats_reached_at, expected) self.assertFalse(job.start_time) class SchedulerTestCase(TestCase): def test_create(self): data = {'spawned_jobs': 0} def on_job_executed(*ignored): pass def job_run(*ignored): pass def spawn(scheduler_instance, func): self.assertIs(func, job_run) data['spawned_jobs'] += 1 with patch('zato.scheduler.backend.Scheduler._spawn', spawn): scheduler = Scheduler(get_scheduler_config(), None) scheduler.lock = RLock() scheduler.on_job_executed = on_job_executed job1 = get_job() job1.run = job_run job2 = get_job() job2.run = job_run job3 = get_job(name=job2.name) job3.run = job_run job4 = get_job() job5 = get_job() job6 = get_job(prefix='inactive') job6.is_active = False scheduler.create(job1) scheduler.create(job2) # These two won't be added because scheduler.jobs is a set hashed by a job's name. scheduler.create(job2) scheduler.create(job3) # The first one won't be spawned but the second one will. scheduler.create(job4, spawn=False) scheduler.create(job5, spawn=True) # Won't be added anywhere nor spawned because it's inactive. scheduler.create(job6) self.assertEqual(scheduler.lock.called, 7) self.assertEqual(len(scheduler.jobs), 5) self.assertIn(job1, scheduler.jobs) self.assertIn(job2, scheduler.jobs) self.assertIs(job1.callback, scheduler.on_job_executed) self.assertIs(job2.callback, scheduler.on_job_executed) self.assertEqual(data['spawned_jobs'], 4) def test_run(self): test_wait_time = 0.3 sched_sleep_time = 0.1 data = {'sleep': [], 'jobs':set()} def _sleep(value): data['sleep'].append(value) def spawn_job(job): data['jobs'].add(job) def job_run(self): pass job1, job2, job3 = [get_job(str(x)) for x in range(3)] # Already run out of max_repeats and should not be started job4 = Job(rand_int(), rand_string(), SCHEDULER.JOB_TYPE.INTERVAL_BASED, start_time=parse_datetime('1997-12-23 21:24:27'), interval=Interval(seconds=5), max_repeats=3) job1.run = job_run job2.run = job_run job3.run = job_run job4.run = job_run config = Bunch() config.on_job_executed_cb = dummy_callback config._add_startup_jobs = False config._add_scheduler_jobs = False config.startup_jobs = [] config.odb = None config.job_log_level = 'info' scheduler = Scheduler(get_scheduler_config(), None) scheduler.spawn_job = spawn_job scheduler.lock = RLock() scheduler.sleep = _sleep scheduler.sleep_time = sched_sleep_time scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) scheduler.create(job1, spawn=False) scheduler.create(job2, spawn=False) scheduler.create(job3, spawn=False) scheduler.create(job4, spawn=False) scheduler.run() self.assertEqual(3, len(data['jobs'])) self.assertTrue(scheduler.lock.called) for item in data['sleep']: self.assertEqual(sched_sleep_time, item) for job in job1, job2, job3: self.assertIn(job, data['jobs']) self.assertNotIn(job4, data['jobs']) def test_on_max_repeats_reached(self): test_wait_time = 0.5 job_sleep_time = 0.02 job_max_repeats = 3 data = {'job':None, 'called':0} job = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job.wait_sleep_time = job_sleep_time # Just to make sure it's inactive by default. self.assertTrue(job.is_active) scheduler = Scheduler(get_scheduler_config(), None) data['old_on_max_repeats_reached'] = scheduler.on_max_repeats_reached def on_max_repeats_reached(job): data['job'] = job data['called'] += 1 data['old_on_max_repeats_reached'](job) scheduler.on_max_repeats_reached = on_max_repeats_reached scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) scheduler.create(job) scheduler.run() now = datetime.utcnow() # Now the job should have reached the max_repeats limit within the now - test_wait_time period. self.assertIs(job, data['job']) self.assertEqual(1, data['called']) self.assertTrue(job.max_repeats_reached) self.assertFalse(job.keep_running) self.assertTrue(job.max_repeats_reached_at < now) self.assertTrue(job.max_repeats_reached_at >= now + timedelta(seconds=-test_wait_time)) # Having run out of max_repeats it should not be active now. self.assertFalse(job.is_active) def test_delete(self): test_wait_time = 0.5 job_sleep_time = 10 job_max_repeats = 30 job1 = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job1.wait_sleep_time = job_sleep_time job2 = Job(rand_int(), 'b', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job2.wait_sleep_time = job_sleep_time scheduler = Scheduler(get_scheduler_config(), None) scheduler.lock = RLock() scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) scheduler.create(job1) scheduler.create(job2) scheduler.run() scheduler.unschedule(job1) self.assertIn(job2, scheduler.jobs) self.assertNotIn(job1, scheduler.jobs) self.assertFalse(job1.keep_running) # run - 1 # create - 2 # delete - 1 # on_max_repeats_reached - 0 (because of how long it takes to run job_max_repeats with test_wait_time) # 1+2+1 = 4 self.assertEqual(scheduler.lock.called, 4) def test_job_greenlets(self): data = {'spawned':[], 'stopped': []} class FakeGreenlet: def __init__(_self, run): _self.run = _self._run = run def kill(_self, *args, **kwargs): data['stopped'].append([_self, args, kwargs]) def spawn(scheduler_instance, job, *args, **kwargs): g = FakeGreenlet(job) data['spawned'].append(g) return g with patch('zato.scheduler.backend.Scheduler._spawn', spawn): test_wait_time = 0.5 job_sleep_time = 10 job_max_repeats = 30 job1 = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job1.wait_sleep_time = job_sleep_time job2 = Job(rand_int(), 'b', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job2.wait_sleep_time = job_sleep_time scheduler = Scheduler(get_scheduler_config(), None) scheduler.lock = RLock() scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) scheduler.create(job1) scheduler.create(job2) scheduler.run() self.assertEqual(scheduler.job_greenlets[job1.name]._run, job1.run) self.assertEqual(scheduler.job_greenlets[job2.name]._run, job2.run) self.assertTrue(job1.keep_running) self.assertTrue(job2.keep_running) scheduler.unschedule(job1) self.assertFalse(job1.keep_running) self.assertTrue(job2.keep_running) self.assertNotIn(job1.name, scheduler.job_greenlets) self.assertEqual(scheduler.job_greenlets[job2.name]._run, job2.run) self.assertEqual(len(data['stopped']), 1) g, args, kwargs = data['stopped'][0] self.assertIs(g.run.im_func, job1.run.im_func) # That's how we know it was job1 deleted not job2 self.assertIs(args, ()) self.assertDictEqual(kwargs, {'timeout':2.0, 'block':False}) def test_edit(self): def callback(): pass def on_max_repeats_reached_cb(): pass start_time = datetime.utcnow() test_wait_time = 0.5 job_interval1, job_interval2 = 2, 3 job_sleep_time = 10 job_max_repeats1, job_max_repeats2 = 20, 30 scheduler = Scheduler(get_scheduler_config(), None) scheduler.lock = RLock() scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) def check(scheduler, job, label): self.assertIn(job.name, scheduler.job_greenlets) self.assertIn(job, scheduler.jobs) self.assertEqual(1, len(scheduler.job_greenlets)) self.assertEqual(1, len(scheduler.jobs)) self.assertIs(job.run.im_func, scheduler.job_greenlets.values()[0]._run.im_func) clone = list(scheduler.jobs)[0] for name in 'name', 'interval', 'cb_kwargs', 'max_repeats', 'is_active': expected = getattr(job, name) given = getattr(clone, name) self.assertEqual(expected, given, '{} != {} ({})'.format(expected, given, name)) job_cb = job.callback clone_cb = clone.callback job_on_max_cb = job.on_max_repeats_reached_cb clone_on_max_cb = clone.on_max_repeats_reached_cb if label == 'first': self.assertEqual(job.start_time, clone.start_time) self.assertIs(job_cb.im_func, clone_cb.im_func) self.assertIs(job_on_max_cb.im_func, clone_on_max_cb.im_func) else: self.assertEqual(job.start_time, clone.start_time) self.assertIs(clone_cb.im_func, scheduler.on_job_executed.im_func) self.assertIs(clone_on_max_cb.im_func, scheduler.on_max_repeats_reached.im_func) job1 = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=job_interval1), start_time, max_repeats=job_max_repeats1) job1.callback = callback job1.on_max_repeats_reached_cb = on_max_repeats_reached_cb job1.wait_sleep_time = job_sleep_time job2 = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=job_interval2), start_time, max_repeats=job_max_repeats2) job2.callback = callback job2.on_max_repeats_reached_cb = on_max_repeats_reached_cb job2.wait_sleep_time = job_sleep_time scheduler.run() scheduler.create(job1) sleep(test_wait_time) # We have only job1 at this point check(scheduler, job1, 'first') # Removes job1 along the way .. scheduler.edit(job2) # .. so now job2 is the now removed job1. check(scheduler, job2, 'second') def test_on_job_executed_cb(self): data = {'runs':[], 'ctx':[]} def get_context(): ctx = {'name': rand_string(), 'type':SCHEDULER.JOB_TYPE.INTERVAL_BASED} data['ctx'].append(ctx) return ctx def on_job_executed_cb(ctx): data['runs'].append(ctx) test_wait_time = 0.5 job_sleep_time = 0.1 job_max_repeats = 10 job = Job(rand_int(), 'a', SCHEDULER.JOB_TYPE.INTERVAL_BASED, Interval(seconds=0.1), max_repeats=job_max_repeats) job.wait_sleep_time = job_sleep_time job.get_context = get_context scheduler = Scheduler(get_scheduler_config(), None) scheduler.lock = RLock() scheduler.iter_cb = iter_cb scheduler.iter_cb_args = (scheduler, datetime.utcnow() + timedelta(seconds=test_wait_time)) scheduler.on_job_executed_cb = on_job_executed_cb scheduler.create(job, spawn=False) scheduler.run() self.assertEqual(len(data['runs']), len(data['ctx'])) for idx, item in enumerate(data['runs']): self.assertEqual(data['ctx'][idx], item)
28,281
Python
.py
585
36.664957
145
0.594457
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,502
test_util.py
zatosource_zato/code/zato-common/test/zato/common/test_util.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from pathlib import Path from tempfile import TemporaryDirectory from unittest import TestCase # Bunch from bunch import Bunch # lxml from lxml import etree # Zato from zato.common.util import api as util_api, StaticConfig from zato.common.util.search import SearchResults from zato.common.py23_ import maxint from zato.common.test.tls_material import ca_cert # ################################################################################################################################ # ################################################################################################################################ class UtilsTestCase(TestCase): def test_uncamelify(self): original = 'ILikeToReadWSDLDocsNotReallyNOPENotMeQ' expected1 = 'i-like-to-read-wsdl-docs-not-really-nope-not-me-q' self.assertEqual(util_api.uncamelify(original), expected1) # ################################################################################################################################ # ################################################################################################################################ class XPathTestCase(TestCase): def test_validate_xpath(self): self.assertRaises(etree.XPathSyntaxError, util_api.validate_xpath, 'a b c') self.assertTrue(util_api.validate_xpath('//node')) # ################################################################################################################################ # ################################################################################################################################ class TLSTestCase(TestCase): def test_validate_tls_cert_from_payload(self): info = util_api.get_tls_from_payload(ca_cert) self.assertEqual(info, 'C=AU; CN=CA2') def test_replace_private_key(self): self.maxDiff = maxint payload = '{"value": "-----BEGIN RSA PRIVATE KEY-----\\r\\nMIIJKQIBAAKCAgEA0nRSiWO6a68MQNxRcgUgDwHSB6ldSCAr6Xl9otadBN02fN6V\\r\\nZdFU4M5Gv+IEFpkgngStGHFyfAjX2pXXiL4Zpvggbzbiyg42y3s6vnE2I33NtEUd\\r\\nn3W5XiHBTUjzh7oETfK5lW1TnYXFBPBMSUjBzyQ1IUq9YZp3+HGLfB08ijsz7azZ\\r\\n35IvlTT12GbS09+85+Mtik+ABEtSiUbBpgZv\\/W0qNj35Rky1Q\\/U236QJOjPQzG8p\\r\\nE12ep1AQECsSWAv3VpQoLHQFLMrLsfHNKAkTFpE0p3z3vjtc9P\\/ihxf+b5bA0R4s\\r\\nmbfnG1HNauLs73Y6P2K7PRa+LoQe5C4ljJ6KFNakRYkieSs5Ic4kRZxdr5BgamuH\\r\\n5nXYbKmDs9wFYE3s4CpHpEJip377utnodXU2W3F67uS4GS6nmBDa07xPJD\\/2NV9E\\r\\n3xTXTJXhxDdqnheIhm5u1rXPbqqp6F12mSFanTgNEd2Fa17o8lzvwJ6xfVr9rm1a\\r\\nxROA1gv0SEJFV9pCMB3U3X9L3Kf+xqzO\\/kxQOx3dyEFYYvfSuVm1CW\\/VWcuDXiFv\\r\\nYdgjubNOkYjqjzrYq\\/4Ef47NekLBidD+K\\/+\\/YjnQ55e4KDe780iI8euuFANTM471\\r\\n6FzU0kqelo360mb5h16CIqVBmCDXTcntqtpnlq2Xu2fsz3AdyyFNvWyk2GECAwEA\\r\\nAQKCAgBzE+A9+CZr06Ajp1Vxv5O0IQ6z2cyEL\\/NTC3fDnw7lJgExbpTKxBhhhOny\\r\\n6qfJo5nOTkhIYWB0qnE9uUnOIATu5Cb4KU8BpZwY0B1jHYy5A4WD2XdFRp5B9rs4\\r\\ng3eG9BR+ewc3yjw6mncNKEjOmdZAalATEEdWI50OYSggiewcuhq\\/EBFiyxDxya\\/U\\r\\n0QTfjixBsFuqkaYysu1C20nwevyp2xOF7YVtB2zm6CNFTvEsvkCiSPZw\\/HRQkNr3\\r\\nvFWfh4uL8B+3jwl1YL7ZYpsIFU42vNfJ7e+aOeOupG096cTbR9fPgWxp8cGRkr18\\r\\ngPGGT2OyXU59LP55eQ1bQFCP\\/\\/EITdxPaIgviD9tAiEdwhWTKzKCPDLNw83d9baX\\r\\nMI\\/b4vRCLdnN3c7bhrffdJWRT\\/5\\/yCcqdZrgPQkLrv2r6klbhyrFVKeDWJYusNKu\\r\\ntcYFoq8qZO0nzW5OKpMvBgdxUh\\/PrpBCDKB\\/YxpxL5Vvc2TY1yLFZyx2YaJVpupe\\r\\nEdxCgdjh1SMjQjPb9g5vlVX13EOdY8PXWZoYDe0qB\\/DY7NPeUEIADhIsGTR0KHZK\\r\\nnk77h4Qn3d91GcZaqyhor8y5x3TTA+QDRImFfOkhI+PRobjb3XLDRK34jETXuW0u\\r\\nyOL2ULLKFDW\\/uBSBQ+3Gc+VINx06wuRIQOAgw8P07QRMR7+Q8QKCAQEA9AlYhXEv\\r\\nvjiRXxETZEpzVuSSQNp82bzfXEBYGG9Mt9pdWpR24obgWehsrXUZDAEyZYSu66SQ\\r\\nyhd0WStzo+b0fLY5vF1OLetYMuHkSSRttB6IIfO0aZqj3o4f8H\\/2JBz0XpNJKV1B\\r\\nbzPZ5DTVZ2qXUBU9RxpOzpET1kv1RzN8Is78L8bE4HYNcgySkoQaXxQG8\\/soq2Rs\\r\\ndbI1FzTEVWNvj+vIfDaF0r70lQgAoNqYqIL6pnnqM12hq8SH8WI7Ao2a30UQgEEO\\r\\nrnle76oyZZfILt0V2GUu31hLjDPEy8sgQCtnGOKh6C2XMZw\\/krfelRrU1V0XAzun\\r\\n9zeD+woOg2sCjwKCAQEA3MWFgto72Yk6RTKvqtXnuVCLKtdnOC9QIGWkPDwtdGkO\\r\\nLukgzew6NBwl4VIWKdSbue6EHi9oj7OYcc949J9Z6BDyEWWF3xwi+G9Y\\/4csAult\\r\\nrpSz+y6feM3KlrF9oYltMoPAjbwCP8KqncXQCRkmIrah8OPBO+4xLzpj+yOLF7GV\\r\\nYizlk5yWa1W+63nuDgc+QUAgN+dSNECigyxlsenR+Nbup6KR7nkMWSaDCyP7GN3E\\r\\n\\/J8qG5rno0gwMQIVl4HiYVNMCywpooeog3fPvj87eAD0e+SNwUi4edw7Azz9IkEB\\r\\nN+\\/iQC1IVuCvgef1usnQnepEkwmNZhBOZoUcH3YuDwKCAQEArsTur4qTDaEHg1UA\\r\\nVUf4eFdz4pxW470fHbs7HCzBfb4WM2O2DJ9ZlyocgtEk4fMNe6TdfQc7ZnALtDyp\\r\\nMc2adKIwkRUlgz9TyAT87+D17BQdnGsjXqoQB7gzaZLK3awa2oySzdvqm9A\\/kO7B\\r\\nkrHEsea0HvLZU5iU41k8zQQzN96Sv0iUAMiq8m3Mnr+a\\/1KhdCQASVa\\/Uj8RRJBW\\r\\nt2xiHmlXCJYnmvmEwiKcCJbk03ISPh17u9OnkBNM5HNcHYT6UEHvAlsVP6DOe8eh\\r\\nFh7wj5doKLS2L9\\/VIxCENQtBCpPK3wiXuWbFLBNheBrUfmZb3H4xl\\/AmZ6dLjwLx\\r\\nx+5gQwKCAQBAvEZ+7SEZk4ybl9Y84MY257A3GrxwlCcJqOQ0qWymsttu0\\/tDhp42\\r\\ng350CI7pKyeSqKbi9wHRCVeNH8oW6NcDHlzszvknR+fVM0lEfE1ieTIpO\\/9eivhG\\r\\nAwoBkAAHqvVzF4ERzmxWZ+2Bn+x1joNJMIZhzVbvDNQtRhDlJjH1+6OTCxkyZHsS\\r\\n9Cysfa9ZO7R8i6Im4lSPb9h3YEBdn\\/Nq5RNL4naqF6KQTaOlU6KgUv8dGErPl2eO\\r\\n0G8ZH8RXDcXkxfkJWaTHvMGj8zDeV0pH0PffkFAkuf8l9Hb1Zx\\/OuILz9QpByUVp\\r\\n\\/C5aiDrcz6q1c2kyOF3W7Lcghq2NaCjvAoIBAQDcoBxNP6+km\\/AgTjIQMtU2GusZ\\r\\nxzIKyItpkjYON8GyYJGMTr8twqhhomsW8nrodZAeqo\\/nUvjKGWebjR2ohEsRfqgN\\r\\n6eMTmbEYZDjnxiQyFlc6BwUvRhlaVlFAh3AquYEGd5aKbt5+k9798j1EPhFODFLM\\r\\nhhs6wd00A0den+X\\/j8u6Hv6yIZC5w7E\\/BL+bGFKUSeJTQsVa8+IO\\/2sVXcNXKJtT\\r\\no2DjN0BYoLePapQ5QBimN8SzenAU32QHH+LSdnGHsT97F232p8eaM5quhTTJ7325\\r\\nOaOmzFG5jrdqyNeIOrFTk5nYyQvEpzAVFp87VdLikFMYMyeWC6dIF+9PDk6O\\r\\n-----END RSA PRIVATE KEY-----"}'# noqa: E501 replaced = util_api.replace_private_key(payload) self.assertEqual(replaced, '{"value": "-----BEGIN RSA PRIVATE KEY-----\******n-----END RSA PRIVATE KEY-----"}') # noqa: W605 # ################################################################################################################################ # ################################################################################################################################ class TestUpdateBindPort(TestCase): def test_update_bind_port_zeromq(self): config1 = Bunch() config1.address = 'tcp://*:37047' util_api.update_bind_port(config1, 0) self.assertEqual(config1.address, 'tcp://*:37047') self.assertEqual(config1.bind_port, 37047) config2 = Bunch() config2.address = 'tcp://*:47047' util_api.update_bind_port(config2, 3) self.assertEqual(config2.address, 'tcp://*:47050') self.assertEqual(config2.bind_port, 47050) # ################################################################################################################################ def test_update_bind_port_websocket(self): config1 = Bunch() config1.address = 'ws://0.0.0.0:36190' util_api.update_bind_port(config1, 0) self.assertEqual(config1.address, 'ws://0.0.0.0:36190') self.assertEqual(config1.bind_port, 36190) config2 = Bunch() config2.address = 'wss://example.com:16251' util_api.update_bind_port(config2, 3) self.assertEqual(config2.address, 'wss://example.com:16254') self.assertEqual(config2.bind_port, 16254) # ################################################################################################################################ # ################################################################################################################################ class TestAPIKeyUsername(TestCase): def test_update_apikey_username(self): config = Bunch(header='x-aaa') util_api.update_apikey_username_to_channel(config) self.assertEqual(config.header, 'HTTP_X_AAA') # ################################################################################################################################ # ################################################################################################################################ class StaticConfigTestCase(TestCase): def test_read_file_no_directories(self): with TemporaryDirectory() as base_dir: file_dir = os.path.join(base_dir) file_name = 'foo.txt' file_path = os.path.join(file_dir, file_name) contents = 'This is a test.' Path(file_path).write_text(contents) static_config = StaticConfig(base_dir) static_config.read_file(file_path, file_name) value = static_config[file_name] self.assertEqual(value, contents) # ################################################################################################################################ def test_read_file_with_one_directory(self): with TemporaryDirectory() as base_dir: level1 = 'abc' file_dir = os.path.join(base_dir, level1) file_name = 'foo.txt' file_path = os.path.join(file_dir, file_name) contents = 'This is a test.' Path(file_dir).mkdir(parents=True) Path(file_path).write_text(contents) static_config = StaticConfig(base_dir) static_config.read_file(file_path, file_name) value = static_config[level1][file_name] self.assertEqual(value, contents) # ################################################################################################################################ def test_read_file_with_nested_directory(self): with TemporaryDirectory() as base_dir: level1 = 'abc' level2 = 'zxc' level3 = 'qwe' file_dir = os.path.join(base_dir, *[level1, level2, level3]) file_name = 'foo.txt' file_path = os.path.join(file_dir, file_name) contents = 'This is a test.' Path(file_dir).mkdir(parents=True) Path(file_path).write_text(contents) static_config = StaticConfig(base_dir) static_config.read_file(file_path, file_name) value = static_config[level1][level2][level3][file_name] self.assertEqual(value, contents) # ################################################################################################################################ # ################################################################################################################################ class SearchResultsTestCase(TestCase): def test_from_list(self): data_list = [ # Page 1 'item1', 'item2', 'item3', # Page 2 'item4', 'item5', 'item6', # Page 3 'item7', 'item8', 'item9', # Page 3 'item10', 'item11', 'item12', ] # Which page are we on in this result object cur_page = 2 # How many results to return in each page page_size = 3 search_results = SearchResults.from_list(data_list, cur_page, page_size, needs_sort=False) search_results = search_results.to_dict() self.assertIsInstance(search_results, dict) self.assertEqual(search_results['num_pages'], 4) self.assertEqual(search_results['cur_page'], 2) self.assertEqual(search_results['prev_page'], 1) self.assertEqual(search_results['next_page'], 3) self.assertEqual(search_results['page_size'], 3) self.assertEqual(search_results['total'], 12) self.assertTrue(search_results['has_prev_page']) self.assertTrue(search_results['has_next_page']) self.assertListEqual( search_results['result'], ['item9', 'item8', 'item7'] ) # ################################################################################################################################ # ################################################################################################################################
12,147
Python
.py
163
66.300613
3,623
0.574595
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,503
test_sql_publish_with_retry.py
zatosource_zato/code/zato-common/test/zato/common/publish/test_sql_publish_with_retry.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from contextlib import closing from unittest import main # Zato from zato.common.api import PUBSUB from zato.common.odb.api import PoolStore, SessionWrapper from zato.common.odb.model import PubSubSubscription from zato.common.odb.query.pubsub.publish import PublishWithRetryManager, sql_publish_with_retry from zato.common.test import CommandLineTestCase from zato.common.test.wsx_ import WSXChannelManager from zato.common.typing_ import cast_ from zato.common.util.api import fs_safe_now from zato.common.util.time_ import utcnow_as_ms from zato.server.pubsub import Subscription # ################################################################################################################################ # ################################################################################################################################ if 0: from sqlalchemy import Column from zato.common.typing_ import anydict, callable_, callnone, dictlist, strlist Column = Column # ################################################################################################################################ # ################################################################################################################################ PubSubSubscriptionTable = PubSubSubscription.__table__ PubSubSubscriptionDelete = PubSubSubscriptionTable.delete # ################################################################################################################################ # ################################################################################################################################ class SQLPublishWithRetryTestCase(CommandLineTestCase): def setUp(self) -> 'None': # This test case requires for MySQL connection details to be available through environment variables. # If they are not specified, the test is skipped. database = os.environ.get('ZATO_ODB_DATABASE') if not database: self.should_run = False return # If we are here, it means that the test run and we need to set up everything. else: self.should_run = True # Prepare the SQL configuration name = 'Test.Connection' config = { 'name': name, 'is_active': True, 'engine': 'mysql+pymysql', 'fs_sql_config': {}, 'ping_query': 'select 1+1', 'host': os.environ['ZATO_ODB_HOST'], 'port': os.environ['ZATO_ODB_PORT'], 'username': os.environ['ZATO_ODB_USERNAME'], 'password': os.environ['ZATO_ODB_PASSWORD'], 'db_name': database, } self.store = PoolStore() self.store[name] = config self.odb = SessionWrapper() self.odb.init_session(name, config, self.store[name].pool) self.odb.pool.ping({}) # ################################################################################################################################ def get_gd_msg_list( self, topic_name:'str', topic_id:'int', sub_key:'str', pubsub_endpoint_id:'int', ext_client_id:'str', ) -> 'dictlist': return [{ 'cluster_id': 1, 'data': 'abc', 'data_prefix': 'abc', 'data_prefix_short': 'abc', 'deliver_to_sk': [], 'delivery_count': 0, 'delivery_status': '2', 'expiration': 2, 'expiration_time': 3.1, 'expiration_time_iso': '', 'ext_client_id': ext_client_id, 'ext_pub_time': '0.9', 'ext_pub_time_iso': '', 'group_id': '', 'has_gd': True, 'in_reply_to': '', 'is_in_sub_queue': True, 'mime_type': 'text/plain', 'position_in_group': 1, 'pub_correl_id': '', 'pub_msg_id': 'zpsm001', 'pub_pattern_matched': 'pub=/*', 'pub_time': '1.1', 'pub_time_iso': '', 'published_by_id': pubsub_endpoint_id, 'recv_time': 1.0, 'recv_time_iso': '', 'reply_to_sk': [], 'server_name': '', 'server_pid': 0, 'size': 3, 'sub_key': '', 'sub_pattern_matched': {sub_key: 'sub=/*'}, 'topic_id': topic_id, 'topic_name': topic_name, 'zato_ctx': '{\n\n}' }] # ################################################################################################################################ def create_sql_sub( self, new_session_func:'callable_', pubsub_endpoint_id:'int', sub_key:'str', topic_id:'int' ) -> 'anydict': with closing(new_session_func()) as session: sub = PubSubSubscription() sub.sub_key = sub_key sub.endpoint_id = pubsub_endpoint_id sub.topic_id = topic_id sub.creation_time = utcnow_as_ms() sub.sub_pattern_matched = 'sub=/*' sub.is_durable = True sub.has_gd = True sub.active_status = PUBSUB.QUEUE_ACTIVE_STATUS.FULLY_ENABLED.id sub.is_staging_enabled = False sub.delivery_method = PUBSUB.DELIVERY_METHOD.NOTIFY.id sub.delivery_data_format = 'text/plain' sub.wrap_one_msg_in_list = True sub.delivery_max_size = 111 sub.delivery_max_retry = 1 sub.delivery_err_should_block = False sub.wait_sock_err = 1 sub.wait_non_sock_err = 1 session.add(sub) session.commit() dict_info = sub.asdict() return dict_info # ################################################################################################################################ def _run_test(self, before_queue_insert_func:'callnone', should_collect_ctx:'bool') -> 'PublishWithRetryManager': # If we are here, it means that we can proceed. now_safe = fs_safe_now() topic_name = f'/wsx.pubsub.test.{now_safe}.1' topics = [topic_name] with WSXChannelManager(self, needs_pubsub=True, run_cli=True, topics=topics) as ctx: now = 1.0 cid = 'cid.zxc' sub_key = f'zpsk.{now_safe}' cluster_id = 1 pub_counter = 1 ext_client_id = 'ext.client.id.1' new_session_func = self.odb.session topic_id = ctx.topic_name_to_id[topic_name] gd_msg_list = self.get_gd_msg_list(topic_name, topic_id, sub_key, ctx.pubsub_endpoint_id, ext_client_id) subscriptions_by_topic = [] with closing(self.odb.session()) as session: sub_info = self.create_sql_sub( new_session_func, ctx.pubsub_endpoint_id, sub_key, topic_id ) sub_info['topic_name'] = topic_name sub_info['task_delivery_interval'] = 1 sub_info['ext_client_id'] = ext_client_id sub = Subscription(sub_info) subscriptions_by_topic.append(sub) publish_with_retry_manager = sql_publish_with_retry( now = now, cid = cid, topic_id = topic_id, topic_name = topic_name, cluster_id = cluster_id, pub_counter = pub_counter, session = session, new_session_func = new_session_func, before_queue_insert_func = before_queue_insert_func, gd_msg_list = gd_msg_list, subscriptions_by_topic = subscriptions_by_topic, should_collect_ctx = should_collect_ctx, ) return publish_with_retry_manager # ################################################################################################################################ def test_sql_publish_with_retry_no_updates_no_context(self): # Skip the test if we are not to run. if not self.should_run: return # In this test, we do not update the subscription list at all, # assuming rather that everything should be published as it is given on input. before_queue_insert_func = None should_collect_ctx = False # Run the test .. publish_with_retry_manager = self._run_test(before_queue_insert_func, should_collect_ctx) # .. and confirm the result. self.assertListEqual(publish_with_retry_manager.ctx_history, []) # ################################################################################################################################ def test_sql_publish_with_retry_no_updates_collect_ctx(self): # Skip the test if we are not to run. if not self.should_run: return # In this test, we do not update the subscription list at all, but we collect context information. before_queue_insert_func = None should_collect_ctx = True # Run the test .. publish_with_retry_manager = self._run_test(before_queue_insert_func, should_collect_ctx) # .. and confirm the result. self.assertListEqual(publish_with_retry_manager.ctx_history, ['Counter -> 1:1', 'Result -> True']) # ################################################################################################################################ def test_sql_publish_with_retry_one_sub_delete_sub(self): # Skip the test if we are not to run. if not self.should_run: return def _before_queue_insert_func( publish_with_retry_manager:'PublishWithRetryManager', sub_keys_by_topic:'strlist' ) -> 'None': session = publish_with_retry_manager.new_session_func() session.execute( PubSubSubscriptionDelete().\ where(cast_('Column', PubSubSubscription.sub_key).in_(sub_keys_by_topic)) ) session.commit() # In this test, we update the subscription list and we collect context information. before_queue_insert_func = _before_queue_insert_func should_collect_ctx = True # Run the test .. publish_with_retry_manager = self._run_test(before_queue_insert_func, should_collect_ctx) # .. and confirm the result. self.assertListEqual(publish_with_retry_manager.ctx_history, ['Counter -> 1:1', 'Result -> False', 'Queue insert OK -> False', 'Sub by topic -> []', 'Counter -> 1:2', 'Result -> True']) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': # stdlib import logging log_level = logging.INFO log_format = '%(asctime)s - %(levelname)s - %(process)d:%(threadName)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=log_level, format=log_format) _ = main() # ################################################################################################################################ # ################################################################################################################################
11,873
Python
.py
244
38.040984
130
0.46613
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,504
test_json_to_dataclass.py
zatosource_zato/code/zato-common/test/zato/common/marshall_/test_json_to_dataclass.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main, TestCase # Zato from zato.common.ext.dataclasses import dataclass, field from zato.common.marshal_.api import MarshalAPI, Model from zato.common.test import rand_int, rand_string from zato.common.test.marshall_ import CreateUserRequest, Role, TestService, User from zato.common.typing_ import cast_, list_field, dictlist, strlistnone # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.marshal_.api import ModelCtx from zato.server.service import Service ModelCtx = ModelCtx Service = Service # ################################################################################################################################ # ################################################################################################################################ class JSONToDataclassTestCase(TestCase): def test_unmarshall(self): request_id = rand_int() user_name = rand_string() locality = rand_string() role_type1 = 111 role_type2 = 222 role_name1 = 'role.name.111' role_name2 = 'role.name.222' data = { 'request_id': request_id, 'user': { 'user_name': user_name, 'address': { 'locality': locality, } }, 'role_list': [ {'type': role_type1, 'name': role_name1}, {'type': role_type2, 'name': role_name2}, ] } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, CreateUserRequest) # type: CreateUserRequest self.assertIs(type(result), CreateUserRequest) self.assertIsInstance(result.user, User) self.assertEqual(result.request_id, request_id) self.assertEqual(result.user.user_name, user_name) self.assertIsInstance(result.role_list, list) self.assertEqual(len(result.role_list), 2) role1 = result.role_list[0] # type: Role role2 = result.role_list[1] # type: Role self.assertIsInstance(role1, Role) self.assertIsInstance(role2, Role) self.assertEqual(role1.type, role_type1) self.assertEqual(role1.name, role_name1) self.assertEqual(role2.type, role_type2) self.assertEqual(role2.name, role_name2) # ################################################################################################################################ def test_unmarshall_optional_list_of_strings_given_on_input(self): elem1 = rand_string() elem2 = rand_string() elem3 = rand_string() my_list = [elem1, elem2, elem3] @dataclass class MyRequest(Model): my_list: strlistnone = list_field() request1 = { 'my_list': my_list } service = None api = MarshalAPI() result = api.from_dict(cast_('Service', service), request1, MyRequest) # type: MyRequest self.assertListEqual(my_list, cast_('list', result.my_list)) # ################################################################################################################################ def test_unmarshall_optional_list_of_strings_not_given_on_input(self): @dataclass class MyRequest(Model): my_list: strlistnone = list_field() request1 = {} service = None api = MarshalAPI() result = api.from_dict(cast_('Service', service), request1, MyRequest) # type: MyRequest self.assertListEqual([], cast_('list', result.my_list)) # ################################################################################################################################ def test_unmarshall_default(self): request_id = rand_int() user_name = rand_string() locality = rand_string() @dataclass class CreateAdminRequest(CreateUserRequest): admin_type: str = field(default='MyDefaultValue') # type: ignore data = { 'request_id': request_id, 'user': { 'user_name': user_name, 'address': { 'locality': locality, } }, 'role_list': [], } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, CreateAdminRequest) # type: CreateAdminRequest self.assertIs(type(result), CreateAdminRequest) self.assertIsInstance(result.user, User) self.assertEqual(result.request_id, request_id) self.assertEqual(result.admin_type, CreateAdminRequest.admin_type) self.assertEqual(result.user.user_name, user_name) # ################################################################################################################################ def test_unmarshall_and_run_after_created(self): request_id = 123456789 user_name = 'my.user.name' locality = 'my.locality' @dataclass class MyRequestWithAfterCreated(CreateUserRequest): def after_created(self, ctx:'ModelCtx') -> 'None': if not isinstance(ctx.service, TestService): raise ValueError('Expected for service class to be {} instead of {}'.format( TestService, type(ctx.service))) if not isinstance(ctx.data, dict): # type: ignore raise ValueError('Expected for service class to be a dict instead of {}'.format(type(ctx.data))) request_id = ctx.data['request_id'] user_name = ctx.data['user']['user_name'] if request_id != 123456789: raise ValueError('Value of request_id should be 123456789 instead of `{}`'.format(request_id)) if user_name != 'my.user.name': raise ValueError('Value of request_id should be "my.user.name"instead of `{}`'.format(user_name)) if locality != 'my.locality': raise ValueError('Value of locality should be "my.locality"instead of `{}`'.format(locality)) data = { 'request_id': request_id, 'user': { 'user_name': user_name, 'address': { 'locality': locality, } }, 'role_list': [], } service = cast_('Service', TestService()) api = MarshalAPI() api.from_dict(service, data, MyRequestWithAfterCreated) # ################################################################################################################################ def test_unmarshall_input_is_a_dataclass(self): @dataclass(init=False) class MyModel(Model): my_field: str expected_value = 'abc' data = {'my_field': expected_value} service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, MyModel) # type: MyModel self.assertEqual(result.my_field, expected_value) # ################################################################################################################################ def test_unmarshall_input_is_a_dictlist(self): @dataclass(init=False) class MyModel(Model): my_field: dictlist expected_value = [{ 'abc':111, 'zxc':222 }] data = {'my_field': expected_value} service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, MyModel) # type: MyModel self.assertEqual(result.my_field, expected_value) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
8,727
Python
.py
178
39.308989
130
0.463607
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,505
test_to_json.py
zatosource_zato/code/zato-common/test/zato/common/marshall_/test_to_json.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from json import loads from unittest import main # BSON (MongoDB) from bson import ObjectId # Zato from zato.common.ext.dataclasses import dataclass from zato.common.marshal_.api import Model from zato.common.test import BaseSIOTestCase # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class User(Model): user_name: str # ################################################################################################################################ # ################################################################################################################################ class ToJSONTestCase(BaseSIOTestCase): def test_serialize_string(self): # Test data user_name = 'abc' user = User() user.user_name = user_name serialized = user.to_json() deserialized = loads(serialized) self.assertDictEqual(deserialized, {'user_name': user_name}) # ################################################################################################################################ def test_serialize_bson_mongodb_object_id(self): # Test data user_name = '123456789012345678901234' # ObjectId expects input in this format user_name_object_id = ObjectId(user_name) user = User() user.user_name = user_name_object_id # type: ignore serialized = user.to_json() deserialized = loads(serialized) self.assertDictEqual(deserialized, {'user_name': user_name}) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
2,478
Python
.py
46
49.413043
130
0.353674
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,506
__init__.py
zatosource_zato/code/zato-common/test/zato/common/marshall_/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,507
test_validation.py
zatosource_zato/code/zato-common/test/zato/common/marshall_/test_validation.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main, TestCase # Zato from zato.common.ext.dataclasses import dataclass from zato.common.marshal_.api import ElementIsNotAList, ElementMissing, MarshalAPI, Model from zato.common.test import rand_int, rand_string from zato.common.test.marshall_ import Address, AddressWithDefaults, CreateAttrListRequest, CreatePhoneListRequest, \ CreateUserRequest, LineParent, WithAny from zato.common.typing_ import cast_, dictlist # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.server.service import Service Service = Service # ################################################################################################################################ # ################################################################################################################################ class ValidationTestCase(TestCase): def test_validate_top_simple_elem_missing(self): # Input is entirely missing here data = {} service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateUserRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /request_id') # ################################################################################################################################ def test_validate_top_level_dict_missing(self): request_id = rand_int() # The user element is entirely missing here data = { 'request_id': request_id, 'role_list': [], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateUserRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /user') # ################################################################################################################################ def test_validate_nested_dict_missing(self): request_id = rand_int() user_name = rand_string() # The address element is entirely missing here data = { 'request_id': request_id, 'user': { 'user_name': user_name, }, 'role_list': [], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateUserRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /user/address') # ################################################################################################################################ def test_unmarshall_top_level_list_elem_missing(self): request_id = rand_int() user_name = rand_string() locality = rand_string() role_type1 = 111 role_type2 = 222 role_name1 = 'role.name.111' role_name2 = 'role.name.222' data = { 'request_id': request_id, 'user': { 'user_name': user_name, 'address': { 'locality': locality, } }, 'role_list': [ # Element name is missing here {'type': role_type1, 'ZZZ': role_name1}, {'type': role_type2, 'name': role_name2}, ] } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateUserRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /role_list[0]/name') # ################################################################################################################################ def test_unmarshall_top_level_list_dict_empty(self): data = { 'attr_list': [{}], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateAttrListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /attr_list[0]/name') # ################################################################################################################################ def test_unmarshall_top_level_list_dict_missing(self): data = { 'attr_list': [], } service = cast_('Service', None) api = MarshalAPI() result = cast_('CreateAttrListRequest', api.from_dict(service, data, CreateAttrListRequest)) # It is not an error to send a list that is empty, # which is unlike not sending the list at all (as checked in other tests). self.assertListEqual(result.attr_list, []) # ################################################################################################################################ def test_unmarshall_top_level_list_0(self): data = { 'attr_list': [ {'type':'type_0'}, ], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateAttrListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /attr_list[0]/name') # ################################################################################################################################ def test_unmarshall_top_level_list_1(self): data = { 'attr_list': [ {'type':'type_0', 'name':'name_0'}, {'type':'type_1'}, ], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateAttrListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /attr_list[1]/name') # ################################################################################################################################ def test_unmarshall_top_level_list_5(self): data = { 'attr_list': [ {'type':'type_0', 'name':'name_0'}, {'type':'type_1', 'name':'name_1'}, {'type':'type_2', 'name':'name_2'}, {'type':'type_3', 'name':'name_3'}, {'type':'type_4', 'name':'name_4'}, {'type':'type_5'}, ], } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreateAttrListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /attr_list[5]/name') # ################################################################################################################################ def test_unmarshall_nested_list_elem_missing_0(self): data = { 'phone_list': [ {'attr_list': [ # noqa: JS101 {'type':'type_0'}, ]}, # noqa: JS102 ] } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreatePhoneListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /phone_list[0]/attr_list[0]/name') # ################################################################################################################################ def test_unmarshall_nested_list_elem_missing_1(self): data = { 'phone_list': [ {'attr_list': [ # noqa: JS101 {'type':'type_0', 'name':'name_0'}, {'type':'type_1', 'ZZZZ':'name_1'}, ]}, # noqa: JS102 ] } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreatePhoneListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /phone_list[0]/attr_list[1]/name') # ################################################################################################################################ def test_unmarshall_nested_list_elem_missing_1_1(self): data = { 'phone_list': [ {'attr_list': [{'type':'type_0_0', 'name':'name_0_0'}, {'type':'type_0_1', 'name':'name_0_1'},]}, {'attr_list': [{'type':'type_1_0', 'name':'name_1_0'}, {'type':'type_1_1', 'name':'name_1_1'}]}, {'attr_list': [{'type':'type_2_0', 'name':'name_2_0'}, {'type':'type_2_1', 'ZZZZ':'name_2_1'}]}, ] } service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementMissing) as cm: api.from_dict(service, data, CreatePhoneListRequest) e = cm.exception # type: ElementMissing self.assertEqual(e.reason, 'Element missing: /phone_list[2]/attr_list[1]/name') # ################################################################################################################################ def test_unmarshall_optional_missing(self): data = { 'locality': 'abc' } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, Address) # type: Address # This, we can test self.assertEqual(result.locality, data['locality']) # Here, it suffices that we can access these attributes, no matter what their value is. # We check their default values in other tests. result.post_code result.details result.characteristics # ################################################################################################################################ def test_unmarshall_any_should_be_mapped_to_its_default_form(self): data = {} service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, WithAny) # type: WithAny # This should map to None self.assertIsNone(result.str1) # But these two use use their default factories to produce default values self.assertListEqual(cast_('list', result.list1), []) self.assertDictEqual(cast_('dict', result.dict1), {}) # ################################################################################################################################ def test_unmarshall_top_level_list_is_a_default_list(self): # There is no input (and attr_list is a list that is missing but it has a default_factory returning a list) data = {} service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, CreateAttrListRequest) self.assertListEqual(result.attr_list, []) # ################################################################################################################################ def test_unmarshall_optional_empty(self): data = { 'locality': 'abc', 'post_code': '', 'details': {}, 'characteristics': [], } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, Address) # type: Address self.assertEqual(result.locality, data['locality']) self.assertEqual(result.post_code, '') self.assertEqual(result.details, {}) self.assertListEqual(result.characteristics, []) # type: ignore # ################################################################################################################################ def test_unmarshall_optional_missing_default_not_given(self): data = { 'locality': 'abc', 'post_code': '', 'details': {}, 'characteristics': [], } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, Address) # type: Address self.assertEqual(result.locality, data['locality']) self.assertEqual(result.post_code, '') self.assertEqual(result.details, {}) self.assertListEqual(result.characteristics, []) # type: ignore # ################################################################################################################################ def test_unmarshall_optional_default_given(self): data = { 'locality': 'abc', 'post_code': '', 'details': {}, 'characteristics': [], } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, AddressWithDefaults) # type: AddressWithDefaults self.assertEqual(result.locality, data['locality']) self.assertEqual(result.post_code, '') self.assertEqual(result.details, {}) self.assertListEqual(result.characteristics, []) # type: ignore # ################################################################################################################################ def test_extra_top_level_no_value_in_current_dict(self): # Note that locality does not exist in the input dict .. data = {} # .. but it does exist in extra data, which is why we expect to find it in the result later on. extra = { 'locality': 'qwerty' } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, Address, extra=extra) # type: Address self.assertEqual(result.locality, extra['locality']) self.assertEqual(result.post_code, '') self.assertEqual(result.details, {}) self.assertListEqual(result.characteristics, []) # type: ignore # ################################################################################################################################ def test_extra_top_level_with_value_in_current_dict(self): data_value = 'zzz' extra_value = 'qqq' # Note that locality exists both here .. data = { 'locality': data_value } # .. as well as here. The one from the extra dictionary will override the default one. extra = { 'locality': extra_value } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, Address, extra=extra) # type: Address self.assertEqual(result.locality, extra_value) self.assertEqual(result.post_code, '') self.assertEqual(result.details, {}) self.assertListEqual(result.characteristics, []) # type: ignore # We still expect for dictionaries to be the same as originally, # i.e. extra should not permanently overwrite the data dictionary or the other way around. self.assertEqual(data['locality'], data_value) self.assertEqual(extra['locality'], extra_value) # ################################################################################################################################ def test_extra_non_top_level(self): child_value = 'zzz' parent_value = 'qqq' extra_value = '123' # Note that name exists both here .. data = { 'name': parent_value, 'details': { 'name': child_value } } # .. as well as here. However, the extra data should override only the parent data, # .. not what the child model contains. This is because extra applies only to root, top-level elements. extra = { 'name': extra_value } service = cast_('Service', None) api = MarshalAPI() result = api.from_dict(service, data, LineParent, extra=extra) # type: LineParent self.assertEqual(result.name, extra_value) self.assertEqual(result.details.name, child_value) # We still expect for dictionaries to be the same as originally, # i.e. extra should not permanently overwrite either of dictionaries or the other way around. self.assertEqual(data['name'], parent_value) self.assertEqual(extra['name'], extra_value) # ################################################################################################################################ def test_unmarshall_input_is_a_dictlist_invalid_input(self): @dataclass(init=False) class MyModel(Model): my_field: dictlist data = {'my_field': 123} service = cast_('Service', None) api = MarshalAPI() with self.assertRaises(ElementIsNotAList) as cm: api.from_dict(service, data, MyModel) e = cm.exception # type: ElementIsNotAList self.assertEqual(e.reason, 'Element is not a list: /my_field') # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
18,513
Python
.py
366
41.128415
130
0.461337
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,508
test_attach.py
zatosource_zato/code/zato-common/test/zato/common/marshall_/test_attach.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main # Zato from zato.common.ext.dataclasses import dataclass from zato.common.marshal_.api import Model from zato.common.marshal_.simpleio import DataClassSimpleIO from zato.common.test import BaseSIOTestCase from zato.server.service import Service # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class User(Model): user_name: str # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class MyRequest(Model): request_id: int user: User # ################################################################################################################################ # ################################################################################################################################ class SIOAttachTestCase(BaseSIOTestCase): def test_attach_sio(self): class MyService(Service): class SimpleIO: input = MyRequest DataClassSimpleIO.attach_sio(None, self.get_server_config(), MyService) self.assertIsInstance(MyService._sio, DataClassSimpleIO) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
2,280
Python
.py
39
55.205128
130
0.305169
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,509
test_api.py
zatosource_zato/code/zato-common/test/zato/common/util/test_api.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from pathlib import Path from unittest import main, TestCase from uuid import uuid4 # Zato from zato.common.util.file_system import resolve_path # ################################################################################################################################ # ################################################################################################################################ class UtilAPITestCase(TestCase): def test_resolve_path_home_directory(self): # Local aliases suffix = '/test/abc' home_dir = Path.home().as_posix() # Before expansion .. path = '~' + suffix # .. what we expect to receive after expansion .. expected = home_dir + suffix # type: ignore # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ def test_resolve_path_env_variable_start(self): # Local aliases env_01_name = 'Zato_Test_Env_01' # Skip this test if there are no test environment variables in this system if not (env_01 := os.environ.get('Zato_Test_Env_01')): return # Local aliases prefix = '/hello' suffix = '/test/abc' # Before expansion .. path = prefix + '$' + env_01_name + suffix # .. what we expect to receive after expansion .. expected = prefix + env_01 + suffix # type: ignore # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ def test_resolve_path_env_variable_middle(self): # Local aliases env_02_name = 'Zato_Test_Env_02' # Skip this test if there are no test environment variables in this system if not (env_02 := os.environ.get('Zato_Test_Env_02')): return # Local aliases prefix = '/hello/' suffix = '/test/abc' # Before expansion .. path = prefix + '$' + env_02_name + suffix # .. what we expect to receive after expansion .. expected = prefix + env_02 + suffix # type: ignore # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ def test_resolve_path_env_variable_end(self): # Local aliases env_03_name = 'Zato_Test_Env_03' # Skip this test if there are no test environment variables in this system if not (env_03 := os.environ.get('Zato_Test_Env_03')): return # Local aliases prefix = '/hello/' # Before expansion .. path = prefix + '$' + env_03_name # .. what we expect to receive after expansion .. expected = prefix + env_03 # type: ignore # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ def test_resolve_path_multiple_env_variables(self): # Local aliases env_01_name = 'Zato_Test_Env_01' env_02_name = 'Zato_Test_Env_02' env_03_name = 'Zato_Test_Env_03' # Skip this test if there are no test environment variables in this system if not (env_01 := os.environ.get('Zato_Test_Env_01')): return if not (env_02 := os.environ.get('Zato_Test_Env_02')): return if not (env_03 := os.environ.get('Zato_Test_Env_03')): return # Local aliases prefix = '/hello/' # Before expansion .. path = prefix + '$' + env_01_name + '/' + '$' + env_02_name + '/' + '$' + env_03_name # .. what we expect to receive after expansion .. expected = prefix + env_01 + '/' + env_02 + '/' + env_03 # type: ignore # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ def test_resolve_path_missing_env_variable(self): # Local aliases random = uuid4().hex # Such an environment variable will not exist env_missing = 'Zato_Test_Env_' + random # Before expansion .. path = '/hello/' + '$' + env_missing # .. on output, we expect the same path .. expected = path # .. do resolve it .. resolved = resolve_path(path) # .. and confirm that it was resolved correctly. self.assertEqual(resolved, expected) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
6,060
Python
.py
123
41.422764
130
0.449532
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,510
test_hot_deploy_.py
zatosource_zato/code/zato-common/test/zato/common/util/test_hot_deploy_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from unittest import main, TestCase # Zato from zato.common.api import HotDeploy from zato.common.typing_ import cast_ from zato.common.util.hot_deploy_ import extract_pickup_from_items, get_project_info # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.hot_deploy_ import HotDeployProject HotDeployProject = HotDeployProject # ################################################################################################################################ # ################################################################################################################################ class HotDeployTestCase(TestCase): def xtest_extract_pickup_from_items(self): # Skip this test if we do not have an environment variable # pointing to a directory with a test project. if not (root_dir := os.environ.get('Zato_Test_Hot_Deploy_Project_Root_1')): # type: ignore return # We expect for the source to be kept in this directory # Prepare test data .. base_dir = '/my-base-dir' name0 = f'{HotDeploy.UserPrefix}.name.1' value0 = 'relative/path' name1 = f'{HotDeploy.UserPrefix}.name.2' value1 = '/absolute/path' name2 = f'{HotDeploy.UserPrefix}.project.1' value2 = root_dir # .. build a dictionary for the extracting function to process .. pickup_config = { name0: {'pickup_from': value0}, name1: {'pickup_from': value1}, name2: {'pickup_from': value2}, } # .. expected test data on output .. project0_src_dir = os.path.join(root_dir, 'project0', 'subdir0', 'src') project1_src_dir = os.path.join(root_dir, 'project1', 'subdir1', 'src') for idx, item in enumerate(extract_pickup_from_items(base_dir, pickup_config, HotDeploy.Source_Directory)): # This was a relative path that should have been turned into an absolute one .. if idx == 0: expected = os.path.join(base_dir, value0) self.assertEqual(item, expected) # .. this was an absolute path so we should have been given the same value back .. elif idx == 1: expected = value1 self.assertEqual(item, expected) elif idx == 2: # .. there should be two projects on output .. self.assertEqual(len(item), 2) # .. do extract them .. project0 = cast_('HotDeployProject', item[0]) project1 = cast_('HotDeployProject', item[1]) # .. and run the assertions now .. self.assertEqual(str(project0.sys_path_entry), project0_src_dir) self.assertEqual(str(project1.sys_path_entry), project1_src_dir) else: raise Exception(f'Unexpected idx -> {idx} and item -> {item} ') # ################################################################################################################################ def test_get_project_info(self): # Skip this test if we do not have an environment variable # pointing to a directory with a test project. if not (root_dir := os.environ.get('Zato_Test_Hot_Deploy_Project_Root_2')): # type: ignore return # Local aliases src_dir = HotDeploy.Source_Directory project_name = 'project2' full_src_dir = os.path.join(root_dir, project_name, src_dir) # Prepare test data expected_sys_path_entry = full_src_dir # We expect for this information to have been built if not (project_info := get_project_info(root_dir, src_dir)): raise Exception('Expect for project information to be returned') # There should be one project on output self.assertEqual(len(project_info), 1) # Extract the project we have been given .. project_info = project_info[0] # .. run assertions .. self.assertEqual(str(project_info.sys_path_entry), expected_sys_path_entry) for item in project_info.pickup_from_path: print(111, item) # .. there should be 13 paths extracted .. self.assertEqual(len(project_info.pickup_from_path), 13) # .. create local variables for the ease of testing .. full_esb_dir = os.path.join(full_src_dir, 'corp', 'esb') # esb_common = str(project_info.pickup_from_path[0]) esb_model_common = str(project_info.pickup_from_path[1]) esb_adapter_common = str(project_info.pickup_from_path[2]) esb_core_common = str(project_info.pickup_from_path[3]) esb_util = str(project_info.pickup_from_path[4]) esb_core_util = str(project_info.pickup_from_path[5]) esb_channel_edu_util = str(project_info.pickup_from_path[6]) esb_model = str(project_info.pickup_from_path[7]) esb_model_hr = str(project_info.pickup_from_path[8]) esb_core = str(project_info.pickup_from_path[9]) esb_channel = str(project_info.pickup_from_path[10]) esb_channel_edu = str(project_info.pickup_from_path[11]) esb_adapter = str(project_info.pickup_from_path[12]) # expected_esb_common = os.path.join(full_esb_dir, 'common') expected_esb_model_common = os.path.join(full_esb_dir, 'model', 'common') expected_esb_adapter_common = os.path.join(full_esb_dir, 'adapter', 'common') expected_esb_core_common = os.path.join(full_esb_dir, 'core', 'common') expected_esb_util = os.path.join(full_esb_dir, 'util') expected_esb_core_util = os.path.join(full_esb_dir, 'core', 'util') expected_esb_channel_edu_util = os.path.join(full_esb_dir, 'channel', 'edu', 'util') expected_esb_model = os.path.join(full_esb_dir, 'model') expected_esb_model_hr = os.path.join(full_esb_dir, 'model', 'hr') expected_esb_core = os.path.join(full_esb_dir, 'core') expected_esb_channel = os.path.join(full_esb_dir, 'channel') expected_esb_channel_edu = os.path.join(full_esb_dir, 'channel', 'edu') expected_esb_adapter = os.path.join(full_esb_dir, 'adapter') # self.assertEqual(esb_common, expected_esb_common) self.assertEqual(esb_model_common, expected_esb_model_common) self.assertEqual(esb_adapter_common, expected_esb_adapter_common) self.assertEqual(esb_core_common, expected_esb_core_common) self.assertEqual(esb_util, expected_esb_util) self.assertEqual(esb_core_util, expected_esb_core_util) self.assertEqual(esb_channel_edu_util, expected_esb_channel_edu_util) self.assertEqual(esb_model, expected_esb_model) self.assertEqual(esb_model_hr, expected_esb_model_hr) self.assertEqual(esb_core, expected_esb_core) self.assertEqual(esb_channel, expected_esb_channel) self.assertEqual(esb_channel_edu, expected_esb_channel_edu) self.assertEqual(esb_adapter, expected_esb_adapter) # # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
8,333
Python
.py
139
50.942446
130
0.523903
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,511
test_config.py
zatosource_zato/code/zato-common/test/zato/common/util/test_config.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main, TestCase # Zato from zato.common.api import Secret_Shadow from zato.common.typing_ import cast_ from zato.common.util.config import replace_query_string_items # Zato - Cython from zato.simpleio import SecretConfig from zato.simpleio import SIOServerConfig # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_ from zato.server.base.parallel import ParallelServer ParallelServer = ParallelServer # ################################################################################################################################ # ################################################################################################################################ class ConfigTestCase(TestCase): def test_replace_query_string_items(self): class _Server: sio_config = None # Prepare individual pieces of the secrets configuration exact = {'xApiKey', 'token'} prefixes = {'secret_prefix_', 'password_prefix_'} suffixes = {'_secret_suffix', '_password_suffix'} # Build the configuration of secrets first secret_config:'any_' = SecretConfig() secret_config.exact = exact secret_config.prefixes = prefixes secret_config.suffixes = suffixes sio_config:'any_' = SIOServerConfig() sio_config.secret_config = secret_config _server = cast_('ParallelServer', _Server()) _server.sio_config = sio_config data01 = 'wss://hello?xApiKey=123' data02 = 'wss://hello?xApiKey=123&token=456' data03 = 'wss://hello?xApiKey=123&token=456&abc=111' data04 = 'wss://hello?abc=111&xApiKey=123&token=456&zxc=456' data05 = 'https://hello?secret_prefix_1=123&1_secret_suffix=456' data06 = 'https://hello?password_prefix_2=123&2_password_suffix=456' data01_expected = f'wss://hello?xApiKey={Secret_Shadow}' data02_expected = f'wss://hello?xApiKey={Secret_Shadow}&token={Secret_Shadow}' data03_expected = f'wss://hello?xApiKey={Secret_Shadow}&token={Secret_Shadow}&abc=111' data04_expected = f'wss://hello?abc=111&xApiKey={Secret_Shadow}&token={Secret_Shadow}&zxc=456' data05_expected = f'https://hello?secret_prefix_1={Secret_Shadow}&1_secret_suffix={Secret_Shadow}' data06_expected = f'https://hello?password_prefix_2={Secret_Shadow}&2_password_suffix={Secret_Shadow}' data01_replaced = replace_query_string_items(_server, data01) data02_replaced = replace_query_string_items(_server, data02) data03_replaced = replace_query_string_items(_server, data03) data04_replaced = replace_query_string_items(_server, data04) data05_replaced = replace_query_string_items(_server, data05) data06_replaced = replace_query_string_items(_server, data06) self.assertEqual(data01_replaced, data01_expected) self.assertEqual(data02_replaced, data02_expected) self.assertEqual(data03_replaced, data03_expected) self.assertEqual(data04_replaced, data04_expected) self.assertEqual(data05_replaced, data05_expected) self.assertEqual(data06_replaced, data06_expected) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
4,169
Python
.py
69
54.231884
130
0.518146
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,512
test_google.py
zatosource_zato/code/zato-common/test/zato/common/util/cloud/test_google.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main, TestCase # Zato from zato.common.util.cloud.google import get_api_list # ################################################################################################################################ # ################################################################################################################################ class UtilCloudGoogleTestCase(TestCase): def test_get_api_list(self): # Get a list of all the APIs available .. api_list = get_api_list() # We do not know how many APIs we are going to receive as this is outside our control. # But we do know there will be hundreds of them. min_api_list_len = 200 actual_api_list_len = len(api_list) # Make sure we have at least that many results self.assertGreater(actual_api_list_len, min_api_list_len) # Find a sample API description and confirm its contents. api_title = 'Drive API' api_version = 'v3' for item in api_list: if item.title == api_title and item.version == api_version: self.assertEqual(item.name, 'drive') self.assertEqual(item.id, 'drive:v3') break else: raise Exception(f'API description not found -> {api_title}') # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
2,051
Python
.py
37
49.054054
130
0.386193
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,513
__init__.py
zatosource_zato/code/zato-common/src/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,514
__init__.py
zatosource_zato/code/zato-common/src/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__)
287
Python
.py
8
34.375
64
0.683636
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,515
mssql_direct.py
zatosource_zato/code/zato-common/src/zato/common/mssql_direct.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import getLogger from traceback import format_exc # SQLAlchemy from sqlalchemy.pool import QueuePool as SAQueuePool from sqlalchemy.pool.dbapi_proxy import _DBProxy # Zato from zato.common.api import MS_SQL # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import stranydict # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ def get_queue_pool(pool_kwargs): class _QueuePool(SAQueuePool): def __init__(self, creator, *args, **kwargs): super(_QueuePool, self).__init__(creator, **pool_kwargs) return _QueuePool # ################################################################################################################################ class SimpleSession: """ A simple object simulating SQLAlchemy sessions. """ def __init__(self, api:'MSSQLDirectAPI') -> 'None': self.api = api def __call__(self): return self def execute(self, *args, **kwargs): return self.api.execute(*args, **kwargs) def callproc(self, *args, **kwargs): return self.api.callproc(*args, **kwargs) def ping(self, *args, **kwargs): return self.api.ping(*args, **kwargs) # ################################################################################################################################ class MSSQLDirectAPI: """ An object through which MS SQL connections can be obtained and stored procedures invoked. """ name = MS_SQL.ZATO_DIRECT ping_query = 'SELECT 1' def __init__( self, name, # type: str pool_size, # type: int connect_kwargs, # type: stranydict extra # type: stranydict ) -> 'None': # PyTDS import pytds # Max. overflow is user-configurable max_overflow = extra.get('max_overflow', 0) self._name = name self._connect_kwargs = connect_kwargs self._pool_kwargs = { 'pool_size': pool_size, 'max_overflow': max_overflow, # This is a pool-level checkout timeout, not an SQL query-level one # so we do not need to make it configurable 'timeout': 3 } self._pool = _DBProxy(pytds, get_queue_pool(self._pool_kwargs)) # ################################################################################################################################ def connect(self): return self._pool.connect(**self._connect_kwargs) # ################################################################################################################################ def dispose(self): self._pool.dispose() # ################################################################################################################################ def execute(self, *args, **kwargs): conn = None try: conn = self.connect() with conn.cursor() as cursor: cursor.execute(*args, **kwargs) return cursor.fetchall() finally: if conn: conn.close() # ################################################################################################################################ def ping(self): return self.execute(self.ping_query) # ################################################################################################################################ def _return_proc_rows(self, conn, proc_name, params=None): """ Calls a procedure and returns all the rows it produced as a single list. """ # Result to return result = [] # This is optional in case getting a new cursor will fail cursor = None # Will be set to True in the exception block has_exception = False try: # Obtain a connection from pool conn = self.connect() # Get a new cursor cursor = conn.cursor() # Call the proceudre cursor.callproc(proc_name, params or []) while True: result.append(cursor.fetchall()) if not cursor.nextset(): break except Exception: has_exception = True logger.warning(format_exc()) raise finally: if cursor: cursor.close() conn.commit() conn.close() # Return the result only if there was no exception along the way if not has_exception: return result # ################################################################################################################################ def _yield_proc_rows(self, conn, proc_name, params=None): """ Calls a procedure and yields all the rows it produced, one by one. """ # This is optional in case getting a new cursor will fail cursor = None try: # Get a new cursor cursor = conn.cursor() # Call the proceudre cursor.callproc(proc_name, params or []) while True: yield cursor.fetchall() if not cursor.nextset(): break except Exception: logger.warning(format_exc()) raise finally: if cursor: cursor.close() conn.commit() conn.close() # ################################################################################################################################ def callproc(self, name, params=None, use_yield=False): params = params or [] # Obtain a connection from pool conn = self.connect() return self._yield_proc_rows(conn, name, params) if use_yield else self._return_proc_rows(conn, name, params) # ################################################################################################################################
6,894
Python
.py
151
37.18543
130
0.39988
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,516
http_.py
zatosource_zato/code/zato-common/src/zato/common/http_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from copy import deepcopy from http.client import responses # https://tools.ietf.org/html/rfc6585 TOO_MANY_REQUESTS = 429 HTTP_RESPONSES = deepcopy(responses) HTTP_RESPONSES[TOO_MANY_REQUESTS] = 'Too Many Requests'
465
Python
.py
13
34.307692
82
0.769058
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,517
vault_.py
zatosource_zato/code/zato-common/src/zato/common/vault_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato try: from zato.vault.client import VAULT # For pyflakes, otherwise it doesn't know that other parts of Zato import VAULT from here VAULT = VAULT except ImportError: pass
349
Python
.py
12
26.416667
93
0.720721
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,518
json_.py
zatosource_zato/code/zato-common/src/zato/common/json_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # JSON libraries used by Zato tend to be changed from time to time # and this is the place where .dumps and .loads can be imported from # so as not to require each part of Zato to know what library to use, # unless they have some specific needs in which case they can just # import their own required library themselves. # stdlib from datetime import date, timezone from json import load, loads # BSON from bson import ObjectId # uJSON try: from ujson import dump, dumps as json_dumps except ImportError: from json import dump, dumps as json_dumps # Zato from zato.common.typing_ import datetime_, datetimez # ################################################################################################################################ # ################################################################################################################################ # These are needed for pyflakes # Note that dumps is defined in a function below dump = dump load = load loads = loads # ################################################################################################################################ # ################################################################################################################################ _utc = timezone.utc # ################################################################################################################################ # ################################################################################################################################ def _ensure_serializable(value, simple_type=(str, dict, int, float, list, tuple, set)): if value is not None: if not isinstance(value, simple_type): # Useful in various contexts if isinstance(value, (date, datetime_, datetimez)): # If it should be a time-zone-aware datetime object # but it does not have any TZ, assume UTC. if isinstance(value, datetimez): if not value.tzinfo: value = value.replace(tzinfo=_utc) # Now, we can format it as a string object value = value.isoformat() # Always use Unicode elif isinstance(value, bytes): value = value.decode('utf8') # For MongoDB queries elif isinstance(value, ObjectId): value = 'ObjectId({})'.format(value) else: # We do not know how to serialize it raise TypeError('Cannot serialize `{}` ({})'.format(value, type(value))) return value # ################################################################################################################################ def dumps(data, indent=4): if data is not None: if isinstance(data, dict): for key, value in data.items(): data[key] = _ensure_serializable(value) else: data = _ensure_serializable(data) return json_dumps(data, indent=indent) # ################################################################################################################################
3,351
Python
.py
66
43.863636
130
0.436866
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,519
hot_deploy_.py
zatosource_zato/code/zato-common/src/zato/common/hot_deploy_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from dataclasses import dataclass # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import path_, pathlist # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class HotDeployProject: sys_path_entry: 'path_' pickup_from_path:'pathlist' # ################################################################################################################################ # ################################################################################################################################ # # These are default patterns that can be extended in runtime # via the HotDeploy.Env.Pickup_Patterns environment variable. # pickup_order_patterns = [ ' common*/**', ' util*/**', ' model*/**', ' core*/**', ' channel*/**', ' adapter*/**', ' **/enmasse*.y*ml', ] # ################################################################################################################################ # ################################################################################################################################
1,718
Python
.py
34
48.029412
130
0.249253
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,520
sftp.py
zatosource_zato/code/zato-common/src/zato/common/sftp.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # ################################################################################################################################ # ################################################################################################################################ class SFTPOutput: """ Represents output resulting from execution of SFTP command(s). """ __slots__ = 'is_ok', 'cid', 'command', 'command_no', 'stdout', 'stderr', 'details', 'response_time' def __init__(self, cid, command_no, command=None, is_ok=None, stdout=None, stderr=None, details=None, response_time=None): # type: (str, int, str, bool, str, str, str) -> None self.cid = cid self.command_no = command_no self.command = command self.is_ok = is_ok self.stdout = stdout self.stderr = stderr self.details = details self.response_time = response_time # ################################################################################################################################ def __str__(self): return '<{} at {}, cid:{}, command_no:{}, is_ok:{}, rt:{}>'.format(self.__class__.__name__, hex(id(self)), self.cid, self.command_no, self.is_ok, self.response_time) # ################################################################################################################################ def strip_stdout_prefix(self): if self.stdout: out = [] for line in self.stdout.splitlines(): if not line.startswith('sftp>'): out.append(line) self.stdout = '\n'.join(out) # ################################################################################################################################ def to_dict(self): # type: () -> dict return { 'is_ok': self.is_ok, 'cid': self.cid, 'command': self.command, 'command_no': self.command_no, 'stdout': self.stdout, 'stderr': self.stderr, 'details': self.details, 'response_time': self.response_time, } # ################################################################################################################################ @staticmethod def from_dict(data): # type: (dict) -> SFTPOutput return SFTPOutput(**data) # ################################################################################################################################ # ################################################################################################################################
2,893
Python
.py
54
45.907407
130
0.359192
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,521
microopt.py
zatosource_zato/code/zato-common/src/zato/common/microopt.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from logging import LogRecord from sys import exc_info def logging_Logger_log(self, level, msg, args, exc_info=None, extra=None, _LogRecord=LogRecord, _exc_info=exc_info): """ Overrides logging.Logger._log to gain a tiny but tangible performance boost (1%-3%). """ try: fn, lno, func = self.findCaller() except ValueError: fn, lno, func = '(unknown file)', 0, '(unknown function)' if exc_info: if not isinstance(exc_info, tuple): exc_info = _exc_info() record = _LogRecord(self.name, level, fn, lno, msg, args, exc_info, func) if extra is not None: record.__dict__.update(extra) if not self.disabled: if self.filters: if self.filter(record): self.callHandlers(record) else: self.callHandlers(record)
1,085
Python
.py
28
32.714286
116
0.651718
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,522
settings_db.py
zatosource_zato/code/zato-common/src/zato/common/settings_db.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals """ A set of settings kept in an SQLite database. """ # stdlib import os from logging import getLogger # SQLAlchemy from sqlalchemy import Column, create_engine, Integer, Sequence, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ Base = declarative_base() # ################################################################################################################################ class Setting(Base): __tablename__ = 'settings' __table_args__ = (UniqueConstraint('name'), {}) id = Column(Integer, Sequence('settings_seq'), primary_key=True) name = Column(String(200), nullable=False) value = Column(Text, nullable=True) data_type = Column(String(20), nullable=False) # ################################################################################################################################ class DATA_TYPE: INTEGER = 'integer' STRING = 'string' data_type_handler = { DATA_TYPE.INTEGER: int, DATA_TYPE.STRING: lambda value: value, } # ################################################################################################################################ class SettingsDB: """ Keeps simple settings in an SQLite database. It's new in 3.0 so to ease in migration from pre-3.0 releases the class takes care itself of making sure that its underlying database actually exists - a future Zato version will simply assume that it does. """ def __init__(self, db_path, session): self.db_path = db_path self.session = session # Older environments did not have this database if not os.path.exists(self.db_path): self.create_db() def get_engine(self): return create_engine('sqlite:///{}'.format(self.db_path)) def create_db(self): Base.metadata.create_all(self.get_engine()) def get(self, name, default=None, needs_object=False): data = self.session.query(Setting).\ filter(Setting.name==name).\ first() or None if needs_object: return data return data_type_handler[data.data_type](data.value) if data else default def set(self, name, value, data_type=DATA_TYPE.INTEGER): s = self.get(name, needs_object=True) or Setting() s.name = name s.value = value s.data_type = data_type self.session.add(s) self.session.commit() # ################################################################################################################################
3,097
Python
.py
66
41.818182
130
0.502996
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,523
haproxy.py
zatosource_zato/code/zato-common/src/zato/common/haproxy.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from logging import getLogger from tempfile import NamedTemporaryFile from traceback import format_exc # Zato from zato.common.util.api import make_repr, timeouting_popen from zato.common.util.open_ import open_r logger = getLogger(__name__) # We'll wait up to that many seconds for HAProxy to validate the config file. HAPROXY_VALIDATE_TIMEOUT = 0.6 # Statistics commands understood by HAproxy 1.3.x and newer. Note that the # command numbers must be consecutively increasing across HAProxy versions. haproxy_stats = { ('1', '3'): { # A special command interpreted by the agent as a request for # describing the commands available 0: ('ZATO_DESCRIBE_COMMANDS', 'Describe commands'), 1: ('show info', 'Show info'), 2: ('show stat', 'Show stats'), 3: ('show errors', 'Show errors'), 4: ('show sess', 'Show sessions'), }, ('1', '4'): { } } # timeout_id -> name, value in milliseconds timeouts = { 1: (250, '250ms'), 2: (500, '500ms'), 3: (1000, '1s'), 4: (3000, '3s'), 5: (5000, '10s'), 6: (30000, '30s') } http_log = { 1: ('nolog', 'No log'), 2: ('httplog', 'HTTP log'), } tcp_log = { 1: ('nolog', 'No log'), 2: ('tcplog', 'TCP log'), } reversed_http_log = {v[0]: k for k, v in http_log.items()} reversed_tcp_log = {v[0]: k for k, v in tcp_log.items()} class Config: """ An object for representing a HAProxy configuration file. """ def __init__(self): self.global_ = {} self.defaults = {} self.backend = {'bck_http_plain': {}} self.frontend = {'front_http_plain': {}} def __repr__(self): return make_repr(self) def set_value(self, name, data): if name == 'global:log': host, port, facility, level = data self.global_['log'] = {} self.global_['log']['host'] = host self.global_['log']['port'] = port self.global_['log']['facility'] = facility self.global_['log']['level'] = level elif name == 'global:stats_socket': stats_socket = data[0] self.global_['stats_socket'] = stats_socket elif name == 'defaults:timeout connect': timeout = data[0] self.defaults['timeout_connect'] = timeout elif name == 'defaults:timeout client': timeout = data[0] self.defaults['timeout_client'] = timeout elif name == 'defaults:timeout server': timeout = data[0] self.defaults['timeout_server'] = timeout elif name == 'defaults:stats uri': stats_uri = data[0] self.defaults['stats_uri'] = stats_uri elif name.startswith('backend bck_http_plain:server'): backend_name, address, port, extra = data extra = extra.strip() backend_name = backend_name.split('http_plain--')[1] self.backend['bck_http_plain'][backend_name] = {} self.backend['bck_http_plain'][backend_name]['address'] = address self.backend['bck_http_plain'][backend_name]['port'] = port self.backend['bck_http_plain'][backend_name]['extra'] = extra elif name == 'backend bck_http_plain:option httpchk': method, path = data self.backend['bck_http_plain']['option_httpchk'] = {} self.backend['bck_http_plain']['option_httpchk']['method'] = method self.backend['bck_http_plain']['option_httpchk']['path'] = path elif name == 'frontend front_http_plain:monitor-uri': path = data[0] self.frontend['front_http_plain']['monitor_uri'] = path elif name == 'frontend front_http_plain:option log-http-requests': option = reversed_http_log[data[0]] self.frontend['front_http_plain']['log_http_requests'] = option elif name == 'frontend front_http_plain:bind': address, port = data self.frontend['front_http_plain']['bind'] = {} self.frontend['front_http_plain']['bind']['address'] = address self.frontend['front_http_plain']['bind']['port'] = port elif name == 'frontend front_http_plain:maxconn': maxconn = data[0] self.frontend['front_http_plain']['maxconn'] = maxconn else: msg = 'Could not parse config, name:[{name}], data:[{data}]'.format(name=name, data=data) logger.error(msg) raise Exception(msg) def validate_haproxy_config(config_data, haproxy_command): """ Writes the config into a temporary file and validates it using the HAProxy's -c check mode. """ try: with NamedTemporaryFile(prefix='zato-tmp') as tf: tf.write(config_data.encode('utf8')) tf.flush() common_msg = 'config_file:`{}`' common_msg = common_msg.format(open_r(tf.name).read()) timeout_msg = 'HAProxy didn\'t respond in `{}` seconds. ' rc_non_zero_msg = 'Failed to validate the config file using HAProxy. ' command = [haproxy_command, '-c', '-f', tf.name] timeouting_popen(command, HAPROXY_VALIDATE_TIMEOUT, timeout_msg, rc_non_zero_msg, common_msg) except Exception: msg = 'Caught an exception, e:`{}`'.format(format_exc()) logger.error(msg) raise Exception(msg)
5,638
Python
.py
132
34.689394
105
0.597118
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,524
simpleio_.py
zatosource_zato/code/zato-common/src/zato/common/simpleio_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato - Cython from zato.simpleio import BoolConfig, Elem, IntConfig, SecretConfig, SIOServerConfig # Python 2/3 compatibility from zato.common.py23_.past.builtins import basestring, unicode # ################################################################################################################################ if 0: from zato.common.typing_ import any_ from zato.cy.simpleio import BoolConfig as PyBoolConfig from zato.cy.simpleio import IntConfig as PyIntConfig from zato.cy.simpleio import SecretConfig as PySecretConfig from zato.cy.simpleio import SIOServerConfig as PySIOServerConfig PyBoolConfig = PyBoolConfig PyIntConfig = PyIntConfig PySecretConfig = PySecretConfig PySIOServerConfig = PySIOServerConfig # ################################################################################################################################ # ################################################################################################################################ def get_bytes_to_str_encoding(): return 'utf8' # ################################################################################################################################ default_input_required_name = 'input_required' default_input_optional_name = 'input_optional' default_output_required_name = 'output_required' default_output_optional_name = 'output_optional' default_value = 'default_value' default_input_value = 'default_input_value' default_output_value = 'default_output_value' default_response_elem = 'response' default_skip_empty_keys = False default_skip_empty_request_keys = False default_skip_empty_response_keys = False default_prefix_as_is = 'a' default_prefix_bool = 'b' default_prefix_csv = 'c' default_prefix_date = 'date' default_prefix_date_time = 'dt' default_prefix_dict = 'd' default_prefix_dict_list = 'dl' default_prefix_float = 'f' default_prefix_int = 'i' default_prefix_list = 'l' default_prefix_text = 't' default_prefix_uuid = 'u' simple_io_conf_contents = f""" [bool] exact= prefix=by_, has_, is_, may_, needs_, should_ suffix= [int] exact=id prefix= suffix=_count, _id, _size, _size_min, _size_max, _timeout [secret] exact=auth_data, auth_token, password, password1, password2, secret_key, tls_pem_passphrase, token, api_key, apiKey, xApiKey prefix= suffix= [bytes_to_str] encoding={{bytes_to_str_encoding}} [default] default_value= default_input_value= default_output_value= response_elem=response skip_empty_keys = False skip_empty_request_keys = False skip_empty_response_keys = False # Configuration below is reserved for future use input_required_name = "input_required" input_optional_name = "input_optional" output_required_name = "output_required" output_optional_name = "output_optional" prefix_as_is = {default_prefix_as_is} prefix_bool = {default_prefix_bool} prefix_csv = {default_prefix_csv} prefix_date = {default_prefix_date} prefix_date_time = {default_prefix_date_time} prefix_dict = {default_prefix_dict} prefix_dict_list = {default_prefix_dict_list} prefix_float = {default_prefix_float} prefix_int = {default_prefix_int} prefix_list = {default_prefix_list} prefix_text = {default_prefix_text} prefix_uuid = {default_prefix_uuid} """.lstrip() # ################################################################################################################################ def c18n_sio_fs_config(sio_fs_config): for name in 'bool', 'int', 'secret': config_entry = sio_fs_config[name] exact = config_entry.get('exact') or [] exact = exact if isinstance(exact, list) else [exact] prefix = config_entry.get('prefix') or [] prefix = prefix if isinstance(prefix, list) else [prefix] suffix = config_entry.get('suffix') or [] suffix = suffix if isinstance(suffix, list) else [suffix] config_entry.exact = set(exact) config_entry.prefix = set(prefix) config_entry.suffix = set(suffix) for key, value in sio_fs_config.get('default', {}).items(): if isinstance(value, basestring): if not isinstance(value, unicode): value = value.decode('utf8') sio_fs_config.default[key] = value # ################################################################################################################################ def get_sio_server_config(sio_fs_config): c18n_sio_fs_config(sio_fs_config) sio_server_config = SIOServerConfig() # type: PySIOServerConfig bool_config = BoolConfig() # type: PyBoolConfig bool_config.exact = sio_fs_config.bool.exact bool_config.prefixes = sio_fs_config.bool.prefix bool_config.suffixes = sio_fs_config.bool.suffix int_config = IntConfig() # type: PyIntConfig int_config.exact = sio_fs_config.int.exact int_config.prefixes = sio_fs_config.int.prefix int_config.suffixes = sio_fs_config.int.suffix secret_config = SecretConfig() # type: PySecretConfig secret_config.exact = sio_fs_config.secret.exact secret_config.prefixes = sio_fs_config.secret.prefix secret_config.suffixes = sio_fs_config.secret.suffix sio_server_config.bool_config = bool_config sio_server_config.int_config = int_config sio_server_config.secret_config = secret_config sio_fs_config_default = sio_fs_config.get('default') if sio_fs_config_default: sio_server_config.input_required_name = sio_fs_config.default.get('input_required_name', default_input_required_name) sio_server_config.input_optional_name = sio_fs_config.default.get('input_optional_name', default_input_optional_name) sio_server_config.output_required_name = sio_fs_config.default.get('output_required_name', default_output_required_name) sio_server_config.output_optional_name = sio_fs_config.default.get('output_optional_name', default_output_optional_name) sio_server_config.default_value = sio_fs_config.default.get('default_value', default_value) sio_server_config.default_input_value = sio_fs_config.default.get('default_input_value', default_input_value) sio_server_config.default_output_value = sio_fs_config.default.get('default_output_value', default_output_value) sio_server_config.response_elem = sio_fs_config.default.get('response_elem', default_response_elem) sio_server_config.skip_empty_keys = sio_fs_config.default.get('skip_empty_keys', default_skip_empty_keys) sio_server_config.skip_empty_request_keys = sio_fs_config.default.get( 'skip_empty_request_keys', default_skip_empty_request_keys) sio_server_config.skip_empty_response_keys = sio_fs_config.default.get( 'skip_empty_response_keys', default_skip_empty_response_keys) sio_server_config.prefix_as_is = sio_fs_config.default.get('prefix_as_is', default_prefix_as_is) sio_server_config.prefix_bool = sio_fs_config.default.get('prefix_bool', default_prefix_bool) sio_server_config.prefix_csv = sio_fs_config.default.get('prefix_csv', default_prefix_csv) sio_server_config.prefix_date = sio_fs_config.default.get('prefix_date', default_prefix_date) sio_server_config.prefix_date_time = sio_fs_config.default.get('prefix_date_time', default_prefix_date_time) sio_server_config.prefix_dict = sio_fs_config.default.get('prefix_dict', default_prefix_dict) sio_server_config.prefix_dict_list = sio_fs_config.default.get('prefix_dict_list', default_prefix_dict_list) sio_server_config.prefix_float = sio_fs_config.default.get('prefix_float', default_prefix_float) sio_server_config.prefix_int = sio_fs_config.default.get('prefix_int', default_prefix_int) sio_server_config.prefix_list = sio_fs_config.default.get('prefix_list', default_prefix_list) sio_server_config.prefix_text = sio_fs_config.default.get('prefix_text', default_prefix_text) sio_server_config.prefix_uuid = sio_fs_config.default.get('prefix_uuid', default_prefix_uuid) else: sio_server_config.input_required_name = default_input_required_name sio_server_config.input_optional_name = default_input_optional_name sio_server_config.output_required_name = default_output_required_name sio_server_config.output_optional_name = default_output_optional_name sio_server_config.default_value = default_value sio_server_config.default_input_value = default_input_value sio_server_config.default_output_value = default_output_value sio_server_config.response_elem = default_response_elem sio_server_config.skip_empty_keys = default_skip_empty_keys sio_server_config.skip_empty_request_keys = default_skip_empty_request_keys sio_server_config.skip_empty_response_keys = default_skip_empty_response_keys bytes_to_str_encoding = sio_fs_config.bytes_to_str.encoding if not isinstance(bytes_to_str_encoding, unicode): bytes_to_str_encoding = bytes_to_str_encoding.decode('utf8') sio_server_config.bytes_to_str_encoding = bytes_to_str_encoding sio_server_config.json_encoder.bytes_to_str_encoding = bytes_to_str_encoding return sio_server_config # ################################################################################################################################ def drop_sio_elems(elems:'any_', *to_drop:'any_') -> 'any_': out = list(set(elems)) for out_elem in out: out_name = out_elem.name if isinstance(out_elem, Elem) else out_elem for drop_elem in to_drop: if out_name == drop_elem: out.remove(out_elem) return out # ################################################################################################################################
10,031
Python
.py
181
50.60221
130
0.644147
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,525
user.py
zatosource_zato/code/zato-common/src/zato/common/user.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # ################################################################################################################################ class User: """ A business-level user, e.g. a person on whose behalf a given service runs. """ # ################################################################################################################################
606
Python
.py
11
52.818182
130
0.395586
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,526
log_message.py
zatosource_zato/code/zato-common/src/zato/common/log_message.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # The constants below don't use the Bunch class because we don't need to iterate # over them at all. # LMC stands for the 'log message code' # CID stands for the 'correlation ID' CID_LENGTH = 24 NULL_LMC = '0000.0000' NULL_CID = '0' * CID_LENGTH
488
Python
.py
13
36
82
0.732906
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,527
hl7.py
zatosource_zato/code/zato-common/src/zato/common/hl7.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ class HL7Exception(Exception): """ A common class for raising HL7 parsing-related exceptions. """ data: 'str' inner_exc: 'Exception | None' exc_message: 'str' def __init__( self, exc_message, # type: str data, # type: str inner_exc=None # type: Exception | None ) -> 'None': self.exc_message = exc_message self.data = data self.inner_exc = inner_exc # ################################################################################################################################ # ################################################################################################################################
1,121
Python
.py
24
41.958333
130
0.312557
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,528
in_ram.py
zatosource_zato/code/zato-common/src/zato/common/in_ram.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime # gevent from gevent.lock import RLock # ################################################################################################################################ # ################################################################################################################################ utcnow = datetime.utcnow # ################################################################################################################################ # ################################################################################################################################ class InRAMStore: """ Base class for stores keeping data in RAM, optionally synchronising it to persistent storage. """ def __init__(self, sync_threshold, sync_interval): # type: (int, int) -> None # Sync to storage once in that many events .. self.sync_threshold = sync_threshold # .. or once in that many seconds. self.sync_interval = sync_interval # Total events received since startup self.total_events = 0 # How many events we have received since the last synchronisation with persistent storage self.num_events_since_sync = 0 # Reset each time we synchronise in-RAM state with the persistent storage self.last_sync_time = utcnow() # Maps action opcodes to actual methods so that the latter do not have to be looked up in runtime self.opcode_to_func = {} # A coarse-grained update lock used while modifying the in-RAM database or DB key locks self.update_lock = RLock() # Maps DB keys to fine-grained locks self.key_lock = {} # Interal usage counters and telemetry self.telemetry = {} # ################################################################################################################################ def get_lock(self, key): # type: (str) -> RLock with self.update_lock: key_lock = self.key_lock.get(key) if not key_lock: key_lock = RLock() self.key_lock[key] = key_lock return key_lock # ################################################################################################################################ def should_sync(self): # type: () -> bool sync_by_threshold = self.num_events_since_sync % self.sync_threshold == 0 sync_by_time = (utcnow() - self.last_sync_time).total_seconds() >= self.sync_interval return sync_by_threshold or sync_by_time # ################################################################################################################################ def sync_state(self): raise NotImplementedError('InRAMStore.sync_state') # ################################################################################################################################ def post_modify_state(self): # .. update counters .. self.num_events_since_sync += 1 self.total_events += 1 # .. check if sync is needed only if our class implements the method .. if self.sync_state: # .. check if we should sync RAM with persistent storage .. if self.should_sync(): # .. save in persistent storage .. self.sync_state() # .. update metadata. self.num_events_since_sync = 0 self.last_sync_time = utcnow() # ################################################################################################################################ def access_state(self, opcode, data): # type: (str, object) -> None with self.update_lock: # Maps the incoming upcode to an actual function to handle data .. func = self.opcode_to_func[opcode] # .. store in RAM .. func(data) # .. update metadata and, possibly, sync state (storage). self.post_modify_state() # ################################################################################################################################ # ################################################################################################################################
4,492
Python
.py
81
47.358025
130
0.413769
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,529
exception.py
zatosource_zato/code/zato-common/src/zato/common/exception.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from http.client import BAD_REQUEST, CONFLICT, FORBIDDEN, INTERNAL_SERVER_ERROR, METHOD_NOT_ALLOWED, NOT_FOUND, \ SERVICE_UNAVAILABLE, UNAUTHORIZED # Zato from zato.common.http_ import HTTP_RESPONSES # ################################################################################################################################ # ################################################################################################################################ # https://tools.ietf.org/html/rfc6585 TOO_MANY_REQUESTS = 429 # ################################################################################################################################ # ################################################################################################################################ class ZatoException(Exception): """ Base class for all Zato custom exceptions. """ def __init__(self, cid=None, msg=None): super(ZatoException, self).__init__(msg) self.cid = cid self.msg = msg def __repr__(self): return '<{} at {} cid:`{}`, msg:`{}`>'.format( self.__class__.__name__, hex(id(self)), self.cid, self.msg) __str__ = __repr__ # ################################################################################################################################ class ServiceMissingException(ZatoException): pass # ################################################################################################################################ class RuntimeInvocationError(ZatoException): pass # ################################################################################################################################ class ClientSecurityException(ZatoException): """ An exception for signalling errors stemming from security problems on the client side, such as invalid username or password. """ # ################################################################################################################################ class ConnectionException(ZatoException): """ Encountered a problem with an external connections, such as to AMQP brokers. """ # ################################################################################################################################ class TimeoutException(ConnectionException): pass # ################################################################################################################################ class StatusAwareException(ZatoException): """ Raised when the underlying error condition can be easily expressed as one of the HTTP status codes. """ def __init__(self, cid, msg, status, needs_msg=False): super(StatusAwareException, self).__init__(cid, msg) self.status = status self.reason = HTTP_RESPONSES[status] self.needs_msg = needs_msg def __repr__(self): return '<{} at {} cid:`{}`, status:`{}`, msg:`{}`>'.format( self.__class__.__name__, hex(id(self)), self.cid, self.status, self.msg) # ################################################################################################################################ class HTTPException(StatusAwareException): pass # ################################################################################################################################ class ParsingException(ZatoException): """ Raised when the error is to do with parsing of documents, such as an input XML document. """ # ################################################################################################################################ class NoDistributionFound(ZatoException): """ Raised when an attempt is made to import services from a Distutils2 archive or directory but they don't contain a proper Distutils2 distribution. """ def __init__(self, path): super(NoDistributionFound, self).__init__(None, 'No Disutils distribution in path:[{}]'.format(path)) # ################################################################################################################################ class Inactive(ZatoException): """ Raised when an attempt was made to use an inactive resource, such as an outgoing connection or a channel. """ def __init__(self, name): super(Inactive, self).__init__(None, '`{}` is inactive'.format(name)) # ################################################################################################################################ # ################################################################################################################################ # Below are HTTP exceptions class Reportable(HTTPException): def __init__(self, cid, msg, status, needs_msg=False): super(ClientHTTPError, self).__init__(cid, msg, status, needs_msg) # Backward compatibility with pre 3.0 ClientHTTPError = Reportable # ################################################################################################################################ class BadRequest(Reportable): def __init__(self, cid, msg='Bad request', needs_msg=False): super(BadRequest, self).__init__(cid, msg, BAD_REQUEST, needs_msg) # ################################################################################################################################ class Conflict(Reportable): def __init__(self, cid, msg): super(Conflict, self).__init__(cid, msg, CONFLICT) # ################################################################################################################################ class Forbidden(Reportable): def __init__(self, cid, msg='You are not allowed to access this resource', *ignored_args, **ignored_kwargs): super(Forbidden, self).__init__(cid, msg, FORBIDDEN) # ################################################################################################################################ class MethodNotAllowed(Reportable): def __init__(self, cid, msg): super(MethodNotAllowed, self).__init__(cid, msg, METHOD_NOT_ALLOWED) # ################################################################################################################################ class NotFound(Reportable): def __init__(self, cid, msg): super(NotFound, self).__init__(cid, msg, NOT_FOUND) # ################################################################################################################################ class Unauthorized(Reportable): def __init__(self, cid, msg, challenge): super(Unauthorized, self).__init__(cid, msg, UNAUTHORIZED) self.challenge = challenge # ################################################################################################################################ class TooManyRequests(Reportable): def __init__(self, cid, msg): super(TooManyRequests, self).__init__(cid, msg, TOO_MANY_REQUESTS) # ################################################################################################################################ class InternalServerError(Reportable): def __init__(self, cid, msg='Internal server error'): super(InternalServerError, self).__init__(cid, msg, INTERNAL_SERVER_ERROR) # ################################################################################################################################ class ServiceUnavailable(Reportable): def __init__(self, cid, msg): super(ServiceUnavailable, self).__init__(cid, msg, SERVICE_UNAVAILABLE) # ################################################################################################################################ class PubSubSubscriptionExists(BadRequest): pass # ################################################################################################################################ class ConnectorClosedException(Exception): def __init__(self, exc, message): self.inner_exc = exc super().__init__(message) # ################################################################################################################################ class IBMMQException(Exception): pass # ################################################################################################################################
8,481
Python
.py
137
57.59854
130
0.375181
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,530
kv_data.py
zatosource_zato/code/zato-common/src/zato/common/kv_data.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato from datetime import datetime, timedelta from zato.common.odb.model import KVData as KVDataModel from zato.common.typing_ import dataclass, optional # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.odb.api import SessionWrapper SessionWrapper = SessionWrapper # ################################################################################################################################ # ################################################################################################################################ utcnow = datetime.utcnow default_expiry_time = datetime(year=2345, month=12, day=31) # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class KeyCtx: key: str value: optional[str] = None data_type: str = 'string' creation_time: datetime = None expiry_time: optional[datetime] = None # ################################################################################################################################ # ################################################################################################################################ class KVDataAPI: def __init__(self, cluster_id, session_wrapper): # type: (int, SessionWrapper) -> None self.cluster_id = cluster_id self.session_wrapper = session_wrapper # ################################################################################################################################ def _get_session(self): return self.session_wrapper.session() # ################################################################################################################################ def get(self, key): # type: (str) -> optional[KeyCtx] # We always operate on bytes key = key.encode('utf8') if isinstance(key, str) else key # Get a new SQL session .. session = self._get_session() # .. prepare the query .. query = session.query(KVDataModel).\ filter(KVDataModel.cluster_id==self.cluster_id).\ filter(KVDataModel.key==key).\ filter(KVDataModel.expiry_time > utcnow()) # .. run it .. result = query.first() # type: KVDataModel # .. convert the result to a business object .. if result: ctx = KeyCtx() ctx.key = result.key.decode('utf8') ctx.value = result.value ctx.data_type = result.data_type ctx.creation_time = result.creation_time ctx.expiry_time = result.expiry_time if ctx.value: ctx.value = ctx.value.decode('utf8') return ctx # ################################################################################################################################ def set(self, key, value, expiry_sec=None, expiry_time=None): # type: (str, str, int, datetime) ctx = KeyCtx() ctx.key = key ctx.value = value ctx.expiry_time = expiry_time if expiry_time else utcnow() + timedelta(seconds=expiry_sec) self.set_with_ctx(ctx) # ################################################################################################################################ def set_with_ctx(self, ctx, data_type='string'): # type: (KeyCtx, str) -> None key = ctx.key.encode('utf8') if isinstance(ctx.key, str) else ctx.key value = ctx.value.encode('utf8') if isinstance(ctx.value, str) else ctx.value item = KVDataModel() item.cluster_id = self.cluster_id item.key = key item.value = value item.creation_time = ctx.creation_time or utcnow() item.expiry_time = ctx.expiry_time or default_expiry_time session = self._get_session() session.add(item) session.commit() # ################################################################################################################################ # ################################################################################################################################
4,706
Python
.py
86
48
130
0.379904
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,531
ccsid_.py
zatosource_zato/code/zato-common/src/zato/common/ccsid_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ class CCSIDConfig: """ This is a mapping of CCSID to character encodings used by Python, e.g. CCSID 1208 -> utf-8 in Python. In runtime, if a given CCSID cannot be looked up, Zato will assume 1208 = UTF-8. Details: https://en.wikipedia.org/wiki/CCSID """ default_ccsid = 1208 default_encoding = 'utf8' encoding_map = { 273: 'cp273', 367: 'ascii', 424: 'cp424', 437: 'cp437', 500: 'cp500', 737: 'cp737', 775: 'cp775', 813: 'iso8859_7', 819: 'iso8859_1', 850: 'cp850', 852: 'cp852', 855: 'cp855', 857: 'cp857', 860: 'cp860', 861: 'cp861', 862: 'cp862', 863: 'cp863', 864: 'cp864', 865: 'cp865', 866: 'cp866', 869: 'cp869', 874: 'cp874', 875: 'cp875', 912: 'iso8859_2', 914: 'iso8859_4', 915: 'iso8859_5', 916: 'iso8859_8', 920: 'iso8859_9', 923: 'iso8859_15', 932: 'sjis', 936: 'ms936', 943: 'ms932', 944: 'cp949', 949: 'ksc5601', 950: 'big5', 970: 'euc_kr', 1006: 'cp1006', 1026: 'cp1026', 1089: 'iso8859_6', 1140: 'cp1140', 1208: 'utf8', 1250: 'cp1250', 1251: 'cp1251', 1252: 'cp1252', 1253: 'cp1253', 1254: 'cp1254', 1255: 'cp1255', 1256: 'cp1256', 1257: 'cp1257', 1381: 'gb2312', 1383: 'euc_cn', 1386: 'gbk', 1392: 'gb18030', 5050: 'euc_jp', 5054: 'iso2022jp', 25546: 'iso2022kr', }
1,823
Python
.py
70
18.114286
109
0.48627
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,532
xml_.py
zatosource_zato/code/zato-common/src/zato/common/xml_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,533
component_info.py
zatosource_zato/code/zato-common/src/zato/common/component_info.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from datetime import datetime from itertools import groupby from io import StringIO from operator import attrgetter from time import time # psutil from psutil import NoSuchProcess, Process # PyYAML import yaml # pytz from pytz import UTC # Texttable from texttable import Texttable # Zato from zato.common.api import INFO_FORMAT, MISC, ZATO_INFO_FILE from zato.common.json_internal import dumps as json_dumps, loads as json_loads from zato.common.util.api import current_host from zato.common.util.open_ import open_r # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import stranydict # ################################################################################################################################ # ################################################################################################################################ def format_connections(conns, format): """ Formats a list of connections according to the output format. """ groups = (groupby(conns, key=attrgetter('status'))) out = {} for status, items in groups: items = list(items) items.sort(key=attrgetter('raddr')) out_items = out.setdefault(status, []) for item in items: laddr_str = ':'.join(str(elem) for elem in item.laddr).ljust(21) raddr_str = ':'.join(str(elem) for elem in item.raddr).rjust(21) out_item = { 'from': '{}:{}'.format(*item.laddr), 'to': None, 'formatted': None, } if item.raddr: out_item['to'] = '{}:{}'.format(*item.raddr) out_item['formatted'] = '{} -> {}'.format(laddr_str, raddr_str) else: out_item['formatted'] = '{}:{}'.format(*item.laddr) out_items.append(out_item) return out def get_worker_pids(component_path): """ Returns PIDs of all workers of a given server, which must be already started. """ master_proc_pid = int(open_r(os.path.join(component_path, MISC.PIDFILE)).read()) try: out = sorted(elem.pid for elem in Process(master_proc_pid).children()) except NoSuchProcess: out = [] finally: return out def get_info(component_path, format, _now=datetime.utcnow) -> 'stranydict': master_proc_pid_file = None component_details_file = open_r(os.path.join(component_path, ZATO_INFO_FILE)) component_details = component_details_file.read() out = { 'component_details': component_details, 'component_full_path': component_path, 'component_host': current_host(), 'component_running': False, 'current_time': datetime.now().isoformat(), 'current_time_utc': datetime.utcnow().isoformat(), 'master_proc_connections': None, 'master_proc_pid': None, 'master_proc_name': None, 'master_proc_create_time': None, 'master_proc_create_time_utc': None, 'master_proc_username': None, 'master_proc_workers_no': None, 'master_proc_workers_pids': None, } master_proc_pid = None try: master_proc_pid_file = open_r(os.path.join(component_path, MISC.PIDFILE)) master_proc_pid = int(master_proc_pid_file.read()) except(IOError, ValueError): # Ok, no such file or it is empty pass finally: if master_proc_pid_file: master_proc_pid_file.close() if master_proc_pid: out['component_running'] = True master_proc = Process(master_proc_pid) workers_pids = sorted(elem.pid for elem in master_proc.children()) now = datetime.fromtimestamp(time(), UTC) mater_proc_create_time = master_proc.create_time() mater_proc_create_time_utc = datetime.fromtimestamp(mater_proc_create_time, UTC) out['mater_proc_uptime'] = now - mater_proc_create_time_utc out['mater_proc_uptime_seconds'] = int(out['mater_proc_uptime'].total_seconds()) out['master_proc_connections'] = format_connections(master_proc.connections(), format) out['master_proc_pid'] = master_proc.pid out['master_proc_create_time'] = datetime.fromtimestamp(mater_proc_create_time).isoformat() out['master_proc_create_time_utc'] = mater_proc_create_time_utc.isoformat() out['master_proc_username'] = master_proc.username() out['master_proc_name'] = master_proc.name() out['master_proc_workers_no'] = len(workers_pids) out['master_proc_workers_pids'] = workers_pids for pid in workers_pids: worker = Process(pid) worker_create_time = worker.create_time() worker_create_time_utc = datetime.fromtimestamp(worker_create_time, UTC) out['worker_{}_uptime'.format(pid)] = now - worker_create_time_utc out['worker_{}_uptime_seconds'.format(pid)] = int(out['worker_{}_uptime'.format(pid)].total_seconds()) out['worker_{}_create_time'.format(pid)] = datetime.fromtimestamp(worker_create_time).isoformat() out['worker_{}_create_time_utc'.format(pid)] = worker_create_time_utc.isoformat() out['worker_{}_connections'.format(pid)] = format_connections(worker.connections(), format) # Final cleanup component_details_file.close() return out def format_info(value, format, cols_width=None, dumper=None): if format in(INFO_FORMAT.DICT, INFO_FORMAT.JSON, INFO_FORMAT.YAML): value['component_details'] = json_loads(value['component_details']) if format == INFO_FORMAT.JSON: return json_dumps(value) elif format == INFO_FORMAT.YAML: buff = StringIO() yaml.dump_all([value], default_flow_style=False, indent=4, Dumper=dumper, stream=buff) value = buff.getvalue() buff.close() return value elif format == INFO_FORMAT.TEXT: cols_width = (elem.strip() for elem in cols_width.split(',')) cols_width = [int(elem) for elem in cols_width] table = Texttable() table.set_cols_width(cols_width) # Use text ('t') instead of auto so that boolean values don't get converted into ints table.set_cols_dtype(['t', 't']) rows = [['Key', 'Value']] rows.extend(sorted(value.items())) table.add_rows(rows) return table.draw() else: return value
6,801
Python
.py
148
38.560811
130
0.592251
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,534
oauth.py
zatosource_zato/code/zato-common/src/zato/common/oauth.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging from datetime import datetime, timedelta from http.client import OK from json import loads # gevent from gevent import sleep from gevent.lock import RLock # Requests from requests import post as requests_post # Zato from zato.common.typing_ import dataclass # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, callable_, dictnone, intanydict, stranydict, strnone # ################################################################################################################################ # ################################################################################################################################ logger = logging.getLogger('zato') # ################################################################################################################################ # ################################################################################################################################ class ModuleCtx: # After how many seconds we will consider a token to have expired TTL = 40 * 60 # This is used to join multiple scopes in an HTTP call that requests a new token to be generated Scopes_Separator = ' ' # How many seconds to wait for the auth server to reply when requesting a new token Auth_Reply_Timeout = 20 # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class StoreItem: parent_id: 'int' data: 'any_' creation_time: 'datetime' expiration_time: 'datetime' # ################################################################################################################################ # ################################################################################################################################ class OAuthTokenClient: def __init__( self, conn_name, # type: str username, # type: str secret, # type: str auth_server_url, # type: str scopes # type: str ) -> 'None': self.conn_name = conn_name self.username = username self.secret = secret self.auth = (self.username, self.secret) self.auth_server_url = auth_server_url self.scopes = (scopes or '').splitlines() # ################################################################################################################################ @staticmethod def from_config(config:'stranydict') -> 'OAuthTokenClient': # Extract only the information that the client object expects on input client_config = { 'conn_name': config['name'], 'username': config['username'], 'secret': config['password'], 'auth_server_url': config['auth_server_url'], 'scopes': config['scopes'], } out = OAuthTokenClient(**client_config) return out # ################################################################################################################################ @staticmethod def obtain_from_config(config:'stranydict') -> 'dictnone': client = OAuthTokenClient.from_config(config) token = client.obtain_token() return token # ################################################################################################################################ def obtain_token(self) -> 'dictnone': # All the metadata headers .. headers = { 'Accept': 'application/json', 'Cache-Control': 'no-cache', 'Content-Type': 'application/x-www-form-urlencoded', } # .. POST data to request a new token .. post_data = { 'grant_type': 'client_credentials', 'scope': ModuleCtx.Scopes_Separator.join(self.scopes) } # .. request the token now .. response = requests_post( url=self.auth_server_url, auth=self.auth, data=post_data, headers=headers, verify=None, timeout=ModuleCtx.Auth_Reply_Timeout, ) # .. make sure the response is as expected .. if response.status_code != OK: msg = 'OAuth token for `{}` ({}) could not be obtained -> code:{} -> {}'.format( self.conn_name, self.auth_server_url, response.status_code, response.text ) raise ValueError(msg) # .. if we are here, it means that we do have a token, # .. so we can load it from JSON .. data = loads(response.text) # .. and return it to our caller. return data # ################################################################################################################################ # ################################################################################################################################ class OAuthStore: def __init__( self, get_config_func, # type: callable_ obtain_item_func, # type: callable_ obtain_sleep_time = 5, # type: int max_obtain_iters = 1234567890, # type: int ) -> 'None': # This callable will return an OAuth definition's configuration based on its ID self.get_config_func = get_config_func # This callable is used to obtain an OAuth token from an auth server self.obtain_item_func = obtain_item_func # For how many seconds to sleep in each iteration when obtaining a token self.obtain_sleep_time = obtain_sleep_time # How many times at most we will try to obtain an individual token self.max_obtain_iters = max_obtain_iters # Keys are OAuth definition IDs and values are RLock objects self._lock_dict = {} # type: intanydict # This is where we actually keep tokens self._impl = {} # ################################################################################################################################ def create(self, item_id:'int') -> 'None': self._lock_dict[item_id] = RLock() # ################################################################################################################################ def _get(self, item_id:'int') -> 'StoreItem | None': item = self._impl.get(item_id) return item # ################################################################################################################################ def get(self, item_id:'int') -> 'StoreItem | None': # This will always exist .. lock = self._lock_dict[item_id] # .. make sure we are the only one trying to get the token .. with lock: # This may be potentially missing .. item = self._get(item_id) # .. if it does not, we need to obtain it .. if not item: item = self._set(item_id) # .. if we do have an item, we still need to check whether it is not time to renew it, # .. in which we case we need to obtain a new one anyway .. else: if self._needs_renew(item): item = self._set(item_id) # .. finally, we can return it to our caller. return item # ################################################################################################################################ def get_auth_header(self, item_id:'int') -> 'strnone': item = self.get(item_id) if item: header = '{} {}'.format(item.data['token_type'], item.data['access_token']) return header # ################################################################################################################################ def _needs_renew(self, item:'StoreItem') -> 'bool': now = datetime.utcnow() needs_renew = now >= item.expiration_time return needs_renew # ################################################################################################################################ def _obtain_item(self, item_id:'int') -> 'StoreItem | None': # We are going to keep iterating until we do obtain the item, # or until we can no longer find the configuration for this item, e.g. because it has been already deleted, # or until we run out of iteration attempts. # We are just starting out current_iter = 0 # By default, we are to run keep_running = True while keep_running: # Confirm whether we should still continue keep_running = current_iter < self.max_obtain_iters if not keep_running: break # First, let's increase it current_iter += 1 # Try to look the configuration by ID .. config = self.get_config_func(item_id) # .. if it is not found, it means that it no longer exists, # .. for instance, because it has been already deleted, # .. in which case, we have nothing to return .. if not config: return # .. if we are here, it means that configuration exists .. # .. so we can obtain its underlying data now .. data = self.obtain_item_func(config) # .. if there is no item, we sleep for a while and retry again .. if not data: sleep(self.obtain_sleep_time) continue # .. otherwise, return the obtained item, no matter what it was. else: item = StoreItem() item.data = data item.parent_id = item_id item.creation_time = datetime.utcnow() item.expiration_time = item.creation_time + timedelta(seconds=ModuleCtx.TTL) return item # ################################################################################################################################ def _set(self, item_id:'int') -> 'StoreItem | None': # First, try to obtain the item .. item = self._obtain_item(item_id) # .. if we do not have it, we can explicitly return None .. if not item: return None # .. otherwise .. else: # .. we populate the expected data structures .. self._impl[item_id] = item # .. and return the item obtained. return item # ################################################################################################################################ def delete(self, item_id:'int') -> 'None': # We still have the per-item lock here .. with self._lock_dict[item_id]: # .. remove the definition from the underlying implementation .. _ = self._impl.pop(item_id, None) # .. finally, remove our own lock now. _ = self._lock_dict.pop(item_id, None) # ################################################################################################################################ # ################################################################################################################################
11,874
Python
.py
232
42.431034
130
0.419609
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,535
bearer_token.py
zatosource_zato/code/zato-common/src/zato/common/bearer_token.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime, timedelta, timezone from json import dumps, loads from logging import getLogger from time import time # dateutil from dateutil.parser import parse as dt_parse # Requests from requests import post as requests_post # Zato from zato.cache import KeyExpiredError from zato.common.api import CACHE, Data_Format, ZATO_NOT_GIVEN from zato.common.model.security import BearerTokenConfig, BearerTokenInfo, BearerTokenInfoResult from zato.common.util.api import parse_extra_into_dict # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.cache import Entry from zato.common.typing_ import any_, dtnone, intnone, stranydict from zato.server.base.parallel import ParallelServer from zato.server.connection.cache import Cache # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class BearerTokenManager: # Type hints cache: 'Cache' # This is where we store the tokens cache_name = CACHE.Default_Name.Bearer_Token def __init__(self, server:'ParallelServer') -> None: self.server = server self.security_facade = server.security_facade self.set_cache() def set_cache(self): cache_api = self.server.worker_store.cache_api try: self.cache = cache_api.get_builtin_cache(self.cache_name) except KeyError: self.cache = None # type: ignore # ################################################################################################################################ def _get_bearer_token_config(self, sec_def:'stranydict') -> 'BearerTokenConfig': # Scopes require preprocessing .. scopes = (sec_def['scopes'] or '').splitlines() scopes = [elem.strip() for elem in scopes] scopes = ' '.join(scopes) # .. same goes for extra fields .. extra_fields = sec_def['extra_fields'] or '' extra_fields = parse_extra_into_dict(extra_fields) # .. build a business object from security definition .. out = BearerTokenConfig() out.sec_def_name = sec_def['name'] out.username = sec_def['username'] out.password = sec_def['password'] out.scopes = scopes out.grant_type = sec_def['grant_type'] out.extra_fields = extra_fields out.auth_server_url = sec_def['auth_server_url'] out.client_id_field = sec_def['client_id_field'] out.client_secret_field = sec_def['client_secret_field'] # .. and return it to our caller. return out # ################################################################################################################################ def _build_bearer_token_info(self, sec_def_name:'str', data:'stranydict') -> 'BearerTokenInfo': # Local variables out = BearerTokenInfo() now = datetime.now(tz=timezone.utc) expires_in:'timedelta | None' = None expires_in_sec:'intnone' = None expiration_time:'dtnone' = None # These can be built upfront .. out.creation_time = now out.sec_def_name = sec_def_name out.token = data['access_token'] out.token_type = data['token_type'] # .. these are optional .. out.scopes = data.get('scope') or '' out.username = data.get('username') or data.get('userName') or '' # .. expiration time may be provided as: .. # .. 1) the number of seconds, e.g. "expires_in=86400" # .. 2) a datetime string, e.g. ".expires=Fri, 27 Oct 2023 11:22:33 GMT" # .. and we need to populate the missing field ourselves .. # Case 1) if expires_in_sec := data.get('expires_in'): expires_in = timedelta(seconds=expires_in_sec) expiration_time = now + expires_in # Case 2) if expires := data.get('.expires'): expiration_time = dt_parse(expires) expires_in = expiration_time - now expires_in_sec = int(expires_in.total_seconds()) # .. populate the expiration metadata .. out.expires_in = expires_in out.expires_in_sec = expires_in_sec out.expiration_time = expiration_time # .. and return it to our caller. return out # ################################################################################################################################ def _get_bearer_token_from_auth_server( self, config, # type: BearerTokenConfig scopes, # type: str data_format, # type: str ) -> 'BearerTokenInfo': # Local variables _needs_json = data_format == Data_Format.JSON # The content type will depend on whether it is JSON or not if _needs_json: content_type = 'application/json' else: content_type = 'application/x-www-form-urlencoded' # If we have any scopes given explicitly, they will take priority, # otherwise, the ones from the configuration (if any), will be used. _scopes = scopes or config.scopes # Build our outgoing request .. request = { config.client_id_field: config.username, config.client_secret_field: config.password, 'grant_type': config.grant_type, 'scopes': config.scopes } # .. scopes are optional .. if _scopes: request['scopes'] = _scopes # .. extra fields are optional .. if config.extra_fields: request.update(config.extra_fields) # .. the headers that will be sent along with the request .. headers = { 'Cache-Control': 'no-cache', 'Content-Type': content_type } # .. potentially, we send JSON requests .. if _needs_json: request = dumps(request) # .. now, send the request to the remote end .. response = requests_post(config.auth_server_url, request, headers=headers, verify=None) # .. raise an exception if the invocation was not successful .. if not response.ok: msg = f'Bearer token for `{config.sec_def_name}` could not be obtained from {config.auth_server_url} -> ' msg += f'{response.status_code} -> {response.text}' raise Exception(msg) # .. if we are here, it means that we can load the JSON response .. data:'stranydict' = loads(response.text) # .. turn into a business object that represents the token .. info = self._build_bearer_token_info(config.sec_def_name, data) msg = f'Bearer token received for `{config.sec_def_name}`' msg += f'; expires_in={info.expires_in_sec} ({info.expires_in} -> {info.expiration_time} UTC)' msg += f'; scopes={info.scopes}' logger.info(msg) # .. which can be now returned to our caller. return info # ################################################################################################################################ def _get_cache_key(self, sec_def_name:'str', scopes:'str', audience:'str'='') -> 'str': # Make sure all values are populated scopes = scopes or 'NoScopes' audience = audience or 'NoAudience' # Build the cache key .. key = f'zato.sec.bearer-token.{sec_def_name}.{scopes}.{audience}' # .. and return it to our caller. return key # ################################################################################################################################ def _has_bearer_token_in_cache(self, sec_def_name:'str', scopes:'str') -> 'bool': # Build a cache key .. key = self._get_cache_key(sec_def_name, scopes) # .. check if it exists .. has_key = key in self.cache return has_key # ################################################################################################################################ def _get_bearer_token_from_cache(self, sec_def_name:'str', scopes:'str') -> 'any_': # Build a cache cache key .. key = self._get_cache_key(sec_def_name, scopes) # .. try to get the token information from our cache .. try: cache_entry = self.cache.get(key, details=True) # type: Entry except KeyExpiredError: # ..this key has already expired and we cannot get it .. logger.info('Ignoring expired Bearer token key -> %s', key) # .. return None explicitly to indicate that there is no such key .. return None else: # .. if we are here, we return the key to our caller but only if it actually exists. if cache_entry and cache_entry != ZATO_NOT_GIVEN: return cache_entry # ################################################################################################################################ def _store_bearer_token_in_cache(self, info:'BearerTokenInfo', scopes:'str') -> 'int': # Build a cache cache key .. key = self._get_cache_key(info.sec_def_name, scopes) # .. make it expire in half the time the token will be valid for .. # .. or in one minute in case the expiration time is not available .. if info.expires_in_sec: expiry = info.expires_in_sec / 2 else: expiry = 60 # .. store the token .. self.cache.set(key, info, expiry=expiry) # .. make it known when exactly the key will expire .. expiry_in = timedelta(seconds=expiry) expiry_time = datetime.now(tz=timezone.utc) + expiry_in # .. log what we have done .. msg = f'Bearer token for `{info.sec_def_name}` cached under key `{key}`' msg += f'; expiry={expiry} ({expiry_in} -> {expiry_time} UTC)' logger.info(msg) # .. and return the details to the caller. return expiry # type: ignore # ################################################################################################################################ def _get_bearer_token_info_impl( self, config, # type: BearerTokenConfig scopes, # type: str data_format, # type:str ) -> 'BearerTokenInfoResult': # Local variables result = BearerTokenInfoResult() # If we have the token in our cache, we can return it immediately .. if cache_entry := self._get_bearer_token_from_cache(config.sec_def_name, scopes): # .. assign the actual value .. result.info = cache_entry.value # .. indicate that it came from the cache .. result.is_cache_hit = True result.cache_hits = cache_entry.hits # .. build the remaining expiration time, in seconds .. # .. rounded down to make sure it does not take too much log space .. cache_expiry = cache_entry.expires_at - time() cache_expiry = round(cache_expiry, 2) # .. now, can assign the expiration time .. result.cache_expiry = cache_expiry # .. and return the result to the caller. return result # .. we are here if the token was not in the cache .. else: # .. since the token was not cache, we need to obtain it from the auth server .. info = self._get_bearer_token_from_auth_server(config, scopes, data_format) # .. then we can cache it .. expiry = self._store_bearer_token_in_cache(info, scopes) # .. build the result .. result.info = info result.is_cache_hit = False result.cache_expiry = expiry # .. and now, we can return it to our caller. return result # ################################################################################################################################ def _get_bearer_token_info(self, sec_def:'stranydict', scopes:'str', data_format:'str') -> 'BearerTokenInfoResult': # Turn the input security definition into a bearer token configuration .. config = self._get_bearer_token_config(sec_def) # .. this gets a token either from the server's cache .. # .. or from the remote authentication endpoint .. result = self._get_bearer_token_info_impl(config, scopes, data_format) # .. now, we can return the token to our caller. return result # ################################################################################################################################ def get_bearer_token_info_by_sec_def_id( self, sec_def_id, # type: int scopes, # type: str data_format, # type: str ) -> 'BearerTokenInfoResult': # Get our security definition by its ID .. sec_def:'stranydict' = self.security_facade.get_bearer_token_by_id(sec_def_id) # .. get a token .. result = self._get_bearer_token_info(sec_def, scopes, data_format) # .. and return it to our caller now. return result # ################################################################################################################################ def get_bearer_token_info_by_sec_def_name( self, sec_def_name, # type: str scopes, # type: str data_format, # type: str ) -> 'BearerTokenInfoResult': # Get our security definition by its ID .. sec_def:'stranydict' = self.security_facade.get_bearer_token_by_name(sec_def_name) # .. get a token .. result = self._get_bearer_token_info(sec_def, scopes, data_format) # .. and return it to our caller now. return result # ################################################################################################################################ # ################################################################################################################################
14,875
Python
.py
284
43.742958
130
0.507559
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,536
json_internal.py
zatosource_zato/code/zato-common/src/zato/common/json_internal.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # This is an internal version of zato.common.json_ which only loads the core libraries, # without any other additions. This is important in the CLI where every millisecond counts. # stdlib from json import load, loads # uJSON try: from ujson import dump, dumps except ImportError: from json import dump, dumps load = load dump = dump json_dumps = dumps json_loads = loads
623
Python
.py
19
30.947368
91
0.763423
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,537
const.py
zatosource_zato/code/zato-common/src/zato/common/const.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ class ServiceConst: ServiceInvokerName = 'pub.zato.service.service-invoker' API_Admin_Invoke_Username = 'admin.invoke' API_Admin_Invoke_Url_Path = '/zato/admin/invoke' # ################################################################################################################################ # ################################################################################################################################ class SECRETS: # These parameters will be automatically encrypted in SimpleIO input PARAMS = ('auth_data', 'auth_token', 'password', 'password1', 'password2', 'secret_key', 'token', 'secret') # Zato secret (Fernet) PREFIX = 'zato.secf.' PREFIX_BYTES = b'zato.secf.' # Encrypted data has this prefix Encrypted_Indicator = 'gAAA' # Zato secret (configuration) URL_PREFIX = 'zato+secret://' # ################################################################################################################################ # ################################################################################################################################
1,553
Python
.py
25
58.76
130
0.337508
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,538
json_schema.py
zatosource_zato/code/zato-common/src/zato/common/json_schema.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from logging import getLogger # JSON Schema from jsonschema import validate as js_validate from jsonschema.exceptions import ValidationError as JSValidationError from jsonschema.validators import validator_for # Zato from zato.common.api import CHANNEL, NotGiven from zato.common.json_internal import dumps, loads from zato.common.json_rpc import ErrorCtx, JSONRPCBadRequest, ItemResponse from zato.common.util.open_ import open_r # ################################################################################################################################ # ################################################################################################################################ if 0: from typing import Callable from bunch import Bunch from zato.common.typing_ import anydict from zato.server.base.parallel import ParallelServer Bunch = Bunch Callable = Callable ParallelServer = ParallelServer # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ def get_service_config(item:'anydict', server:'ParallelServer') -> 'anydict': # By default services are allowed to validate input using JSON Schema is_json_schema_enabled = item.get('is_json_schema_enabled', True) # Unless configured per each service separately, we use server defaults here needs_json_schema_err_details = item.get('needs_json_schema_err_details', NotGiven) if needs_json_schema_err_details is NotGiven: needs_json_schema_err_details = server.fs_server_config.misc.return_json_schema_errors return { 'is_json_schema_enabled': is_json_schema_enabled, 'needs_json_schema_err_details': needs_json_schema_err_details } # ################################################################################################################################ # ################################################################################################################################ class ValidationException(Exception): def __init__( self, cid, # type: str object_type, # type: str object_name, # type: str needs_err_details, # type: bool error_msg, # type: str error_msg_details # type: str ) -> 'None': self.cid = cid self.object_type = object_type self.object_name = object_name self.needs_err_details = needs_err_details self.error_msg = error_msg self.error_msg_details = error_msg_details super(ValidationException, self).__init__('JSON Schema validation error in `{}` ({}), e:`{}`'.format( self.object_name, cid, self.error_msg)) # ################################################################################################################################ # ################################################################################################################################ class ValidationError: """ Base class for validation error-related classes. """ __slots__ = 'cid', 'needs_err_details', 'error_msg', 'error_extra', 'needs_prefix' def __init__(self, cid, needs_err_details, error_msg, error_extra=None, needs_prefix=True): # type: (str, bool, str, dict, bool) self.cid = cid self.needs_err_details = needs_err_details self.error_msg = error_msg self.error_extra = error_extra self.needs_prefix = needs_prefix def get_error_message(self, needs_error_msg=False): # type: (bool) -> str out = 'Invalid request' if self.needs_prefix else '' if needs_error_msg or self.needs_err_details: if out: out += '; ' out += self.error_msg return out def serialize(self): raise NotImplementedError('Must be overridden in subclasses') # ################################################################################################################################ # ################################################################################################################################ class DictError(ValidationError): """ An error reporter that serializes JSON Schema validation errors into Python dict responses. """ def serialize(self, to_string=False): # type: (bool) -> object out = { 'is_ok': False, 'cid': self.cid, 'message': self.get_error_message() } return dumps(out) if to_string else out # ################################################################################################################################ # ################################################################################################################################ class JSONRPCError(ValidationError): """ An error reporter that serializes JSON Schema validation errors into JSON-RPC responses. """ def serialize(self): # type: () -> dict error_ctx = ErrorCtx() error_ctx.cid = self.cid error_ctx.code = JSONRPCBadRequest.code error_ctx.message = 'Invalid request' # This may be optionally turned off error_ctx.message = self.get_error_message() out = ItemResponse() out.id = self.error_extra['json_rpc_id'] out.error = error_ctx return out.to_dict() # ################################################################################################################################ channel_type_to_error_class = { CHANNEL.HTTP_SOAP: DictError, CHANNEL.JSON_RPC: JSONRPCError, CHANNEL.SERVICE: DictError, } # ################################################################################################################################ # ################################################################################################################################ class ValidationConfig: """ An individual set of configuration options - each object requiring validation (e.g. each channel) will have its own instance of this class assigned to its validator. """ __slots__ = 'is_enabled', 'object_type', 'object_name', 'schema_path', 'schema', 'validator', 'needs_err_details' def __init__(self): self.is_enabled = None # type: bool # Object type is channel type or, in the future, one of outgoing connections # whose requests to external resources we may also want to validate. self.object_type = None # type: str self.object_name = None # type: str self.schema_path = None # type: str self.schema = None # type: dict self.validator = None # type: object self.needs_err_details = None # type: bool # ################################################################################################################################ # ################################################################################################################################ class Result: __slots__ = 'is_ok', 'cid', 'needs_err_details', 'error_msg', 'error_extra', 'object_type' def __init__(self): self.is_ok = None # type: bool self.cid = None # type: str self.needs_err_details = None # type: bool self.error_msg = None # type: str self.error_extra = None # type: dict self.object_type = None # type: str def __bool__(self): return bool(self.is_ok) __nonzero__ = __bool__ def get_error(self): # type: () -> ValidationError ErrorClass = channel_type_to_error_class[self.object_type] error = ErrorClass(self.cid, self.needs_err_details, self.error_msg, self.error_extra) # type: ValidationError return error # ################################################################################################################################ # ################################################################################################################################ class Validator: """ Validates JSON requests against a previously assigned schema and serializes errors according to the caller's type, e.g. using REST or JSON-RPC. """ __slots__ = 'is_initialized', 'config' def __init__(self): self.is_initialized = False # type: bool self.config = None # type: ValidationConfig def init(self): if not self.config.is_enabled: logger.info('Skipped initialization of JSON Schema validation for `%s` (%s)', self.config.object_name, self.config.object_type) return if not os.path.exists(self.config.schema_path): raise ValueError('JSON schema not found `{}` ({})'.format( self.config.schema_path, self.config.object_name )) # The file is sure to exist with open_r(self.config.schema_path) as f: schema = f.read() # Parse the contents as JSON schema = loads(schema) # Assign the schema and validator for the schema for later use self.config.schema = schema self.config.validator = validator_for(schema) # Everything is set up = we are initialized self.is_initialized = True def validate(self, cid, data, object_type=None, object_name=None, needs_err_details=False, _validate=js_validate): # type: (str, object, str, str, Callable) -> Result # Result we will return result = Result() result.cid = cid object_type = object_type or self.config.object_type object_name = object_name or self.config.object_name needs_err_details = needs_err_details or self.config.needs_err_details try: js_validate(data, self.config.schema, self.config.validator) except JSValidationError as e: # These will be always used, no matter the object/channel type result.is_ok = False result.object_type = object_type result.needs_err_details = needs_err_details result.error_msg = str(e) # This is applicable only to JSON-RPC if object_type == CHANNEL.JSON_RPC: result.error_extra = {'json_rpc_id': data.get('id')} else: result.is_ok = True return result # ################################################################################################################################ # ################################################################################################################################
11,271
Python
.py
212
46.160377
130
0.469256
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,539
json_rpc.py
zatosource_zato/code/zato-common/src/zato/common/json_rpc.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from logging import getLogger from traceback import format_exc # Zato from zato.common.api import NotGiven from zato.common.exception import BadRequest, InternalServerError from zato.common.rate_limiting.common import RateLimitReached as RateLimitReachedError # ################################################################################################################################ # Type checking import typing if typing.TYPE_CHECKING: # stdlib from typing import Callable # Zato from zato.common.json_schema import ValidationException as JSONSchemaValidationException from zato.server.service import ChannelInfo from zato.server.service.store import ServiceStore # For pyflakes Callable = Callable ChannelInfo = ChannelInfo JSONSchemaValidationException = JSONSchemaValidationException ServiceStore = ServiceStore # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ json_rpc_version_supported = '2.0' # ################################################################################################################################ # ################################################################################################################################ class RequestContext: __slots__ = ('cid', 'orig_message', 'message') def __init__(self): self.cid = None # type: str self.orig_message = None # type: object self.message = None # type: str # ################################################################################################################################ # ################################################################################################################################ class ErrorCtx: __slots__ = ('cid', 'code', 'message') def __init__(self): self.cid = None # type: str self.code = None # type: int self.message = None # type: str def to_dict(self): # type: () -> dict return { 'code': self.code, 'message': self.message, 'data': { 'ctx': { 'cid': self.cid } } } # ################################################################################################################################ # ################################################################################################################################ class ItemResponse: __slots__ = ('id', 'cid', 'error', 'result') def __init__(self): self.id = None # type: int self.cid = None # type: str self.error = None # type: ErrorCtx self.result = NotGiven # type: object def to_dict(self, _json_rpc_version=json_rpc_version_supported): # type: (str) -> dict out = { 'jsonrpc': _json_rpc_version, 'id': self.id, } if self.result is not NotGiven: out['result'] = self.result else: out['error'] = self.error.to_dict() return out # ################################################################################################################################ # ################################################################################################################################ class JSONRPCException: code = -32000 # ################################################################################################################################ # ################################################################################################################################ class JSONRPCBadRequest(JSONRPCException, BadRequest): def __init__(self, cid, message): # type: (str, str) BadRequest.__init__(self, cid, msg=message) # ################################################################################################################################ # ################################################################################################################################ class InvalidRequest(JSONRPCBadRequest): code = -32600 # ################################################################################################################################ # ################################################################################################################################ class MethodNotFound(JSONRPCBadRequest): code = -32601 # ################################################################################################################################ # ################################################################################################################################ class InternalError(JSONRPCException, InternalServerError): code = -32603 # ################################################################################################################################ # ################################################################################################################################ class ParseError(JSONRPCBadRequest): code = -32700 # ################################################################################################################################ # ################################################################################################################################ class Forbidden(JSONRPCBadRequest): code = -32403 # ################################################################################################################################ # ################################################################################################################################ class RateLimitReached(JSONRPCBadRequest): code = -32429 # ################################################################################################################################ # ################################################################################################################################ class JSONRPCItem: """ An object describing an individual JSON-RPC request. """ __slots__ = 'jsonrpc', 'method', 'params', 'id', 'needs_response' # ################################################################################################################################ def __init__(self): self.jsonrpc = None # type: str self.method = None # type: str self.params = None # type: object self.id = None # type: str self.needs_response = None # type: bool # ################################################################################################################################ def to_dict(self): # type: () -> dict return { 'jsonrpc': self.jsonrpc, 'method': self.method, 'params': self.params, 'id': self.id } # ################################################################################################################################ @staticmethod def from_dict(item): # type: (dict) -> JSONRPCItem # Our object to return out = JSONRPCItem() # At this stage we only create a Python-level object and input # validation is performed by our caller. out.jsonrpc = item.get('jsonrpc') out.id = item.get('id', -123456789) out.method = item.get('method') out.params = item.get('params') out.needs_response = out.id is not NotGiven return out # ################################################################################################################################ # ################################################################################################################################ class JSONRPCHandler: def __init__(self, service_store, wsgi_environ, config, invoke_func, channel_info, JSONSchemaValidationException): # type: (ServiceStore, dict, dict, Callable, ChannelInfo, JSONSchemaValidationException) self.service_store = service_store self.wsgi_environ = wsgi_environ self.config = config self.invoke_func = invoke_func self.channel_info = channel_info # Kept here and provided by the caller to remove circular imports between common/json_rpc.py and common/json_schema.py self.JSONSchemaValidationException = JSONSchemaValidationException # ################################################################################################################################ def handle(self, ctx): # type: (RequestContext) -> object if isinstance(ctx.message, list): return self.handle_list(ctx) else: return self.handle_one_item(ctx) # ################################################################################################################################ def can_handle(self, method): # type: (str) -> bool return method in self.config['service_whitelist'] # ################################################################################################################################ def _handle_one_item(self, cid, message, orig_message, _json_rpc_version=json_rpc_version_supported): # type: (RequestContext, str) -> dict try: # Response to return out = ItemResponse() # Construct a Python object out of incoming data item = JSONRPCItem.from_dict(message) # We should have the ID at this point out.id = item.id # Confirm that we can handle the JSON-RPC version requested if item.jsonrpc != json_rpc_version_supported: raise InvalidRequest(cid, 'Unsupported JSON-RPC version `{}` in `{}`'.format( item.jsonrpc, orig_message.decode('utf8'))) # Confirm that method requested is one that we can handle if not self.can_handle(item.method): raise MethodNotFound(cid, 'Method not supported `{}` in `{}`'.format(item.method, orig_message.decode('utf8'))) # Try to invoke the service .. skip_response_elem = self.service_store.has_sio(item.method) service_response = self.invoke_func(item.method, item.params, channel_info=self.channel_info, skip_response_elem=skip_response_elem, wsgi_environ=self.wsgi_environ) # .. no exception here = invocation was successful out.result = service_response return out.to_dict() if item.needs_response else None except Exception as e: is_schema_error = isinstance(e, self.JSONSchemaValidationException) is_rate_limit_error = isinstance(e, RateLimitReachedError) error_ctx = ErrorCtx() error_ctx.cid = cid # JSON Schema validator error if is_schema_error: err_code = InvalidRequest.code err_message = e.error_msg_details if e.needs_err_details else e.error_msg elif is_rate_limit_error: err_code = RateLimitReached.code err_message = 'Too Many Requests' else: # Any JSON-RPC error if isinstance(e, JSONRPCException): err_code = e.code err_message = e.args[0] # Any other error else: err_code = -32000 err_message = 'Message could not be handled' if is_schema_error: logger.warning('JSON Schema validation error in JSON-RPC channel `%s` (%s); msg:`%s`, e:`%s`, details:`%s`', self.config.name, cid, orig_message, format_exc(), e.error_msg_details) else: logger.warning('JSON-RPC exception in `%s` (%s); msg:`%s`, e:`%s`', self.config.name, cid, orig_message, format_exc()) error_ctx.code = err_code error_ctx.message = err_message out.error = error_ctx return out.to_dict() # ################################################################################################################################ def handle_one_item(self, ctx, _json_rpc_version=json_rpc_version_supported): # type: (RequestContext) -> dict return self._handle_one_item(ctx.cid, ctx.message, ctx.orig_message) # ################################################################################################################################ def handle_list(self, ctx): # type: (RequestContext) -> list out = [] for item in ctx.message: # type: dict out.append(self._handle_one_item(ctx.cid, item, ctx.orig_message)) return out # ################################################################################################################################ # ################################################################################################################################
13,592
Python
.py
240
48.6125
130
0.377969
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,540
api.py
zatosource_zato/code/zato-common/src/zato/common/api.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from collections import OrderedDict from dataclasses import dataclass from io import StringIO from numbers import Number from sys import maxsize # Bunch from bunch import Bunch # Zato from zato.common.defaults import http_plain_server_port # ################################################################################################################################ if 0: from zato.common.ext.imbox import Imbox from zato.common.typing_ import any_ # ################################################################################################################################ # SQL ODB engine_def = '{engine}://{username}:{password}@{host}:{port}/{db_name}' engine_def_sqlite = 'sqlite:///{sqlite_path}' # Convenience access functions and constants. class OS_Env: Zato_Enable_Memory_Profiler = 'Zato_Enable_Memory_Profiler' megabyte = 10 ** 6 # Hook methods whose func.im_func.func_defaults contains this argument will be assumed to have not been overridden by users # and ServiceStore will be allowed to override them with None so that they will not be called in Service.update_handle # which significantly improves performance (~30%). zato_no_op_marker = 'zato_no_op_marker' SECRET_SHADOW = '******' Secret_Shadow = SECRET_SHADOW # TRACE1 logging level, even more details than DEBUG TRACE1 = 6 SECONDS_IN_DAY = 86400 # 60 seconds * 60 minutes * 24 hours (and we ignore leap seconds) scheduler_date_time_format = '%Y-%m-%d %H:%M:%S' # TODO: Classes that have this attribute defined (no matter the value) will not be deployed # onto servers. DONT_DEPLOY_ATTR_NAME = 'zato_dont_import' # A convenient constant used in several places, simplifies passing around # arguments which are, well, not given (as opposed to being None, an empty string etc.) ZATO_NOT_GIVEN = b'ZATO_NOT_GIVEN' ZatoNotGiven = b'ZatoNotGiven' # Separates command line arguments in shell commands. CLI_ARG_SEP = 'Zato_Zato_Zato' # Also used in a couple of places. ZATO_OK = 'ZATO_OK' ZATO_ERROR = 'ZATO_ERROR' ZATO_WARNING = 'ZATO_WARNING' ZATO_NONE = 'ZATO_NONE' ZATO_DEFAULT = 'ZATO_DEFAULT' ZATO_SEC_USE_RBAC = 'ZATO_SEC_USE_RBAC' Zato_None = ZATO_NONE Zato_No_Security = 'zato-no-security' DELEGATED_TO_RBAC = 'Delegated to RBAC' # Default HTTP method outgoing connections use to ping resources # TODO: Move it to MISC DEFAULT_HTTP_PING_METHOD = 'HEAD' # Default size of an outgoing HTTP connection's pool (plain, SOAP, any). # This is a per-outconn setting # TODO: Move it to MISC DEFAULT_HTTP_POOL_SIZE = 20 # Used when there's a need for encrypting/decrypting a well-known data. # TODO: Move it to MISC ZATO_CRYPTO_WELL_KNOWN_DATA = 'ZATO' # Used if it could not be established what remote address a request came from NO_REMOTE_ADDRESS = '(None)' # Pattern matching order TRUE_FALSE = 'true_false' FALSE_TRUE = 'false_true' simple_types = (bytes, str, dict, list, tuple, bool, Number) # ################################################################################################################################ # ################################################################################################################################ generic_attrs = ( 'is_rate_limit_active', 'rate_limit_type', 'rate_limit_def', 'rate_limit_check_parent_def', 'is_audit_log_sent_active', 'is_audit_log_received_active', 'max_len_messages_sent', 'max_len_messages_received', 'max_bytes_per_message_sent', 'max_bytes_per_message_received', 'hl7_version', 'json_path', 'data_encoding', 'max_msg_size', 'read_buffer_size', 'recv_timeout', 'logging_level', 'should_log_messages', 'start_seq', 'end_seq', 'max_wait_time', 'oauth_def', 'ping_interval', 'pings_missed_threshold', 'socket_read_timeout', 'socket_write_timeout', 'security_group_count', 'security_group_member_count', ) # ################################################################################################################################ # ################################################################################################################################ # These are used by web-admin only because servers and scheduler use sql.conf ping_queries = { 'db2': 'SELECT current_date FROM sysibm.sysdummy1', 'mssql': 'SELECT 1', 'mysql+pymysql': 'SELECT 1+1', 'oracle': 'SELECT 1 FROM dual', 'postgresql': 'SELECT 1', 'postgresql+pg8000': 'SELECT 1', 'sqlite': 'SELECT 1', } engine_display_name = { 'db2': 'DB2', 'mssql': 'MS SQL', 'zato+mssql1': 'MS SQL (Direct)', 'mysql+pymysql': 'MySQL', 'oracle': 'Oracle', 'postgresql': 'PostgreSQL', 'postgresql+pg8000': 'PostgreSQL', 'sqlite': 'SQLite', } # ################################################################################################################################ # ################################################################################################################################ class EnvVariable: Key_Prefix = 'Zato_Config' Key_Missing_Suffix = '_Missing' Log_Env_Details = 'Zato_Log_Env_Details' # ################################################################################################################################ # ################################################################################################################################ class EnvFile: Default = 'env.ini' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class EnvConfigCtx: component:'str' file_name:'str' missing_suffix:'str' = EnvVariable.Key_Missing_Suffix # ################################################################################################################################ # ################################################################################################################################ class API_Key: Env_Key = 'Zato_API_Key_Name' Default_Header = 'X-API-Key' # ################################################################################################################################ # ################################################################################################################################ # All URL types Zato understands. class URL_TYPE: SOAP = 'soap' # Used only by outgoing connections PLAIN_HTTP = 'plain_http' def __iter__(self): return iter([self.PLAIN_HTTP]) # ################################################################################################################################ # ################################################################################################################################ ZATO_FIELD_OPERATORS = { 'is-equal-to': '==', 'is-not-equal-to': '!=', } # ################################################################################################################################ # ################################################################################################################################ ZMQ_OUTGOING_TYPES = ('PUSH', 'PUB') # ################################################################################################################################ # ################################################################################################################################ class ZMQ: PULL = 'PULL' PUSH = 'PUSH' PUB = 'PUB' SUB = 'SUB' MDP = 'MDP' MDP01 = MDP + '01' MDP01_HUMAN = 'Majordomo 0.1 (MDP)' class POOL_STRATEGY_NAME: SINGLE = 'single' UNLIMITED = 'unlimited' class SERVICE_SOURCE_NAME: ZATO = 'zato' MDP01 = 'mdp01' CHANNEL = OrderedDict({ PULL: 'Pull', SUB: 'Sub', MDP01: MDP01_HUMAN, }) OUTGOING = OrderedDict({ PUSH: 'Push', PUB: 'Pub', }) class METHOD_NAME: BIND = 'bind' CONNECT = 'connect' METHOD = { METHOD_NAME.BIND: 'Bind', METHOD_NAME.CONNECT: 'Connect', } POOL_STRATEGY = OrderedDict({ POOL_STRATEGY_NAME.SINGLE: 'Single', POOL_STRATEGY_NAME.UNLIMITED: 'Unlimited', }) SERVICE_SOURCE = OrderedDict({ SERVICE_SOURCE_NAME.ZATO: 'Zato', SERVICE_SOURCE_NAME.MDP01: MDP01_HUMAN, }) # ################################################################################################################################ # ################################################################################################################################ ZATO_ODB_POOL_NAME = 'ZATO_ODB' # ################################################################################################################################ # ################################################################################################################################ SOAP_VERSIONS = ('1.1', '1.2') SOAP_CHANNEL_VERSIONS = ('1.1',) # ################################################################################################################################ # ################################################################################################################################ class SEARCH: class ES: class DEFAULTS: BODY_AS = 'POST' HOSTS = '127.0.0.1:9200\n' class SOLR: class DEFAULTS: ADDRESS = 'https://127.0.0.1:8983/solr' PING_PATH = '/solr/admin/ping' TIMEOUT = '10' POOL_SIZE = '5' class ZATO: class DEFAULTS: PAGE_SIZE = 50 PAGINATE_THRESHOLD = PAGE_SIZE + 1 # ################################################################################################################################ # ################################################################################################################################ class SEC_DEF_TYPE: APIKEY = 'apikey' AWS = 'aws' BASIC_AUTH = 'basic_auth' JWT = 'jwt' NTLM = 'ntlm' OAUTH = 'oauth' TLS_CHANNEL_SEC = 'tls_channel_sec' TLS_KEY_CERT = 'tls_key_cert' VAULT = 'vault_conn_sec' WSS = 'wss' Sec_Def_Type = SEC_DEF_TYPE # ################################################################################################################################ # ################################################################################################################################ SEC_DEF_TYPE_NAME = { SEC_DEF_TYPE.APIKEY: 'API key', SEC_DEF_TYPE.AWS: 'AWS', SEC_DEF_TYPE.BASIC_AUTH: 'Basic Auth', SEC_DEF_TYPE.JWT: 'JWT', SEC_DEF_TYPE.NTLM: 'NTLM', SEC_DEF_TYPE.OAUTH: 'Bearer token', SEC_DEF_TYPE.TLS_CHANNEL_SEC: 'TLS channel', SEC_DEF_TYPE.TLS_KEY_CERT: 'TLS key/cert', SEC_DEF_TYPE.VAULT: 'Vault', SEC_DEF_TYPE.WSS: 'WS-Security', } All_Sec_Def_Types = sorted(SEC_DEF_TYPE_NAME) # ################################################################################################################################ # ################################################################################################################################ class AUTH_RESULT: class BASIC_AUTH: INVALID_PREFIX = 'invalid-prefix' NO_AUTH = 'no-auth' # ################################################################################################################################ # ################################################################################################################################ DEFAULT_STATS_SETTINGS = { 'scheduler_per_minute_aggr_interval':60, 'scheduler_raw_times_interval':90, 'scheduler_raw_times_batch':99999, 'atttention_slow_threshold':2000, 'atttention_top_threshold':10, } # ################################################################################################################################ # ################################################################################################################################ class BATCH_DEFAULTS: PAGE_NO = 1 SIZE = 25 MAX_SIZE = 1000 # ################################################################################################################################ # ################################################################################################################################ class MSG_SOURCE: DUPLEX = 'duplex' # ################################################################################################################################ # ################################################################################################################################ class NameId: """ Wraps both an attribute's name and its ID. """ def __init__(self, name:'str', id:'str'=''): self.name = name self.id = id or name def __repr__(self): return '<{} at {}; name={}; id={}>'.format(self.__class__.__name__, hex(id(self)), self.name, self.id) # ################################################################################################################################ # ################################################################################################################################ class NotGiven: pass # ################################################################################################################################ # ################################################################################################################################ class Attrs(type): """ A container for class attributes that can be queried for an existence of an attribute using the .has class-method. """ attrs = NotGiven @classmethod def has(cls, attr): if cls.attrs is NotGiven: cls.attrs = [] for cls_attr in dir(cls): if cls_attr == cls_attr.upper(): cls.attrs.append(getattr(cls, cls_attr)) return attr in cls.attrs # ################################################################################################################################ # ################################################################################################################################ class DATA_FORMAT(Attrs): CSV = 'csv' DICT = 'dict' FORM_DATA = 'form' HL7 = 'hl7' JSON = 'json' POST = 'post' def __iter__(self): # Note that DICT and other attributes aren't included because they're never exposed to the external world as-is, # they may at most only used so that services can invoke each other directly return iter((self.JSON, self.CSV, self.POST, self.HL7)) Data_Format = DATA_FORMAT # ################################################################################################################################ # ################################################################################################################################ class DEPLOYMENT_STATUS(Attrs): DEPLOYED = 'deployed' AWAITING_DEPLOYMENT = 'awaiting-deployment' IGNORED = 'ignored' # ################################################################################################################################ # ################################################################################################################################ class SERVER_JOIN_STATUS(Attrs): ACCEPTED = 'accepted' # ################################################################################################################################ # ################################################################################################################################ class SERVER_UP_STATUS(Attrs): RUNNING = 'running' CLEAN_DOWN = 'clean-down' # ################################################################################################################################ # ################################################################################################################################ class CACHE: class Default_Name: Main = 'default' Bearer_Token = 'zato.bearer.token' API_USERNAME = 'pub.zato.cache' class TYPE: BUILTIN = 'builtin' MEMCACHED = 'memcached' class BUILTIN_KV_DATA_TYPE: STR = NameId('String', 'str') INT = NameId('Integer', 'int') def __iter__(self): return iter((self.STR, self.INT)) class STATE_CHANGED: CLEAR = 'CLEAR' DELETE = 'DELETE' DELETE_BY_PREFIX = 'DELETE_BY_PREFIX' DELETE_BY_SUFFIX= 'DELETE_BY_SUFFIX' DELETE_BY_REGEX = 'DELETE_BY_REGEX' DELETE_CONTAINS = 'DELETE_CONTAINS' DELETE_NOT_CONTAINS = 'DELETE_NOT_CONTAINS' DELETE_CONTAINS_ALL = 'DELETE_CONTAINS_ALL' DELETE_CONTAINS_ANY = 'DELETE_CONTAINS_ANY' EXPIRE = 'EXPIRE' EXPIRE_BY_PREFIX = 'EXPIRE_BY_PREFIX' EXPIRE_BY_SUFFIX = 'EXPIRE_BY_SUFFIX' EXPIRE_BY_REGEX = 'EXPIRE_BY_REGEX' EXPIRE_CONTAINS = 'EXPIRE_CONTAINS' EXPIRE_NOT_CONTAINS = 'EXPIRE_NOT_CONTAINS' EXPIRE_CONTAINS_ALL = 'EXPIRE_CONTAINS_ALL' EXPIRE_CONTAINS_ANY = 'EXPIRE_CONTAINS_ANY' GET = 'GET' SET = 'SET' SET_BY_PREFIX = 'SET_BY_PREFIX' SET_BY_SUFFIX = 'SET_BY_SUFFIX' SET_BY_REGEX = 'SET_BY_REGEX' SET_CONTAINS = 'SET_CONTAINS' SET_NOT_CONTAINS = 'SET_NOT_CONTAINS' SET_CONTAINS_ALL = 'SET_CONTAINS_ALL' SET_CONTAINS_ANY = 'SET_CONTAINS_ANY' class DEFAULT: MAX_SIZE = 10000 MAX_ITEM_SIZE = 10000 # In characters for string/unicode, bytes otherwise class PERSISTENT_STORAGE: NO_PERSISTENT_STORAGE = NameId('No persistent storage', 'no-persistent-storage') SQL = NameId('SQL', 'sql') def __iter__(self): return iter((self.NO_PERSISTENT_STORAGE, self.SQL)) class SYNC_METHOD: NO_SYNC = NameId('No synchronization', 'no-sync') IN_BACKGROUND = NameId('In background', 'in-background') def __iter__(self): return iter((self.NO_SYNC, self.IN_BACKGROUND)) # ################################################################################################################################ # ################################################################################################################################ class KVDB(Attrs): SEPARATOR = ':::' DICTIONARY_ITEM = 'zato:kvdb:data-dict:item' DICTIONARY_ITEM_ID = DICTIONARY_ITEM + ':id' # ID of the last created dictionary ID, always increasing. LOCK_PREFIX = 'zato:lock:' LOCK_SERVER_PREFIX = '{}server:'.format(LOCK_PREFIX) LOCK_SERVER_ALREADY_DEPLOYED = '{}already-deployed:'.format(LOCK_SERVER_PREFIX) LOCK_SERVER_STARTING = '{}starting:'.format(LOCK_SERVER_PREFIX) LOCK_PACKAGE_PREFIX = '{}package:'.format(LOCK_PREFIX) LOCK_PACKAGE_UPLOADING = '{}uploading:'.format(LOCK_PACKAGE_PREFIX) LOCK_PACKAGE_ALREADY_UPLOADED = '{}already-uploaded:'.format(LOCK_PACKAGE_PREFIX) LOCK_DELIVERY = '{}delivery:'.format(LOCK_PREFIX) LOCK_DELIVERY_AUTO_RESUBMIT = '{}auto-resubmit:'.format(LOCK_DELIVERY) LOCK_SERVICE_PREFIX = '{}service:'.format(LOCK_PREFIX) LOCK_CONFIG_PREFIX = '{}config:'.format(LOCK_PREFIX) LOCK_FANOUT_PATTERN = '{}fanout:{{}}'.format(LOCK_PREFIX) LOCK_PARALLEL_EXEC_PATTERN = '{}parallel-exec:{{}}'.format(LOCK_PREFIX) LOCK_ASYNC_INVOKE_WITH_TARGET_PATTERN = '{}async-invoke-with-pattern:{{}}:{{}}'.format(LOCK_PREFIX) TRANSLATION = 'zato:kvdb:data-dict:translation' TRANSLATION_ID = TRANSLATION + ':id' SERVICE_USAGE = 'zato:stats:service:usage:' SERVICE_TIME_BASIC = 'zato:stats:service:time:basic:' SERVICE_TIME_RAW = 'zato:stats:service:time:raw:' SERVICE_TIME_RAW_BY_MINUTE = 'zato:stats:service:time:raw-by-minute:' SERVICE_TIME_AGGREGATED_BY_MINUTE = 'zato:stats:service:time:aggr-by-minute:' SERVICE_TIME_AGGREGATED_BY_HOUR = 'zato:stats:service:time:aggr-by-hour:' SERVICE_TIME_AGGREGATED_BY_DAY = 'zato:stats:service:time:aggr-by-day:' SERVICE_TIME_AGGREGATED_BY_MONTH = 'zato:stats:service:time:aggr-by-month:' SERVICE_TIME_SLOW = 'zato:stats:service:time:slow:' SERVICE_SUMMARY_PREFIX_PATTERN = 'zato:stats:service:summary:{}:' SERVICE_SUMMARY_BY_DAY = 'zato:stats:service:summary:by-day:' SERVICE_SUMMARY_BY_WEEK = 'zato:stats:service:summary:by-week:' SERVICE_SUMMARY_BY_MONTH = 'zato:stats:service:summary:by-month:' SERVICE_SUMMARY_BY_YEAR = 'zato:stats:service:summary:by-year:' ZMQ_CONFIG_READY_PREFIX = 'zato:zmq.config.ready.{}' REQ_RESP_SAMPLE = 'zato:req-resp:sample:' RESP_SLOW = 'zato:resp:slow:' DELIVERY_PREFIX = 'zato:delivery:' DELIVERY_BY_TARGET_PREFIX = '{}by-target:'.format(DELIVERY_PREFIX) FANOUT_COUNTER_PATTERN = 'zato:fanout:counter:{}' FANOUT_DATA_PATTERN = 'zato:fanout:data:{}' PARALLEL_EXEC_COUNTER_PATTERN = 'zato:parallel-exec:counter:{}' PARALLEL_EXEC_DATA_PATTERN = 'zato:parallel-exec:data:{}' ASYNC_INVOKE_PROCESSED_FLAG_PATTERN = 'zato:async-invoke-with-pattern:processed:{}:{}' ASYNC_INVOKE_PROCESSED_FLAG = '1' # ################################################################################################################################ # ################################################################################################################################ class SCHEDULER: InitialSleepTime = 0.1 EmbeddedIndicator = 'zato_embedded' EmbeddedIndicatorBytes = EmbeddedIndicator.encode('utf8') # This is what a server will invoke DefaultHost = '127.0.0.1' DefaultPort = 31530 # This is what a scheduler will invoke Default_Server_Host = '127.0.0.1' Default_Server_Port = http_plain_server_port # This is what a scheduler will bind to DefaultBindHost = '0.0.0.0' DefaultBindPort = DefaultPort # This is the username of an API client that servers # will use when they invoke their scheduler. Default_API_Client_For_Server_Auth_Required = True Default_API_Client_For_Server_Username = 'server_api_client1' TLS_Enabled = False TLS_Verify = True TLS_Client_Certs = 'optional' TLS_Private_Key_Location = 'zato-scheduler-priv-key.pem' TLS_Public_Key_Location = 'zato-scheduler-pub-key.pem' TLS_Cert_Location = 'zato-scheduler-cert.pem' TLS_CA_Certs_Key_Location = 'zato-scheduler-ca-certs.pem' TLS_Version_Default_Linux = 'TLSv1_3' TLS_Version_Default_Windows = 'TLSv1_2' TLS_Ciphers_13 = 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256' TLS_Ciphers_12 = 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:' + \ 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:' + \ 'DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305' class Status: Active = 'Active' Paused = 'Paused' class Env: # Basic information about where the scheduler can be found Host = 'Zato_Scheduler_Host' Port = 'Zato_Scheduler_Port' # Whether the scheduler is active or paused Status = 'Zato_Scheduler_Status' Bind_Host = 'Zato_Scheduler_scheduler_conf_bind_host' Bind_Port = 'Zato_Scheduler_Bind_Port' Use_TLS = 'Zato_Scheduler_Use_TLS' TLS_Verify = 'Zato_Scheduler_TLS_Verify' TLS_Client_Certs = 'Zato_Scheduler_TLS_Client_Certs' TLS_Private_Key_Location = 'Zato_Scheduler_TLS_Private_Key_Location' TLS_Public_Key_Location = 'Zato_Scheduler_TLS_Public_Key_Location' TLS_Cert_Location = 'Zato_Scheduler_TLS_Cert_Location' TLS_CA_Certs_Key_Location = 'Zato_Scheduler_TLS_CA_Certs_Key_Location' TLS_Version = 'Zato_Scheduler_TLS_Version' TLS_Ciphers = 'Zato_Scheduler_TLS_Ciphers' Path_Action_Prefix = 'Zato_Scheduler_Path_Action_' # These are used by servers to invoke the scheduler Server_Username = 'Zato_Scheduler_API_Client_For_Server_Username' Server_Password = 'Zato_Scheduler_API_Client_For_Server_Password' Server_Auth_Required = 'Zato_Scheduler_API_Client_For_Server_Auth_Required' class ConfigCommand: Pause = 'pause' Resume = 'resume' SetServer = 'set_server' # These jobs were removed in 3.2 and should be ignored JobsToIgnore = {'zato.wsx.cleanup.pub-sub', 'zato.wsx.cleanup'} # This is the job that cleans up pub/sub data PubSubCleanupJob = 'zato.pubsub.cleanup' class JOB_TYPE(Attrs): ONE_TIME = 'one_time' INTERVAL_BASED = 'interval_based' CRON_STYLE = 'cron_style' class ON_MAX_RUNS_REACHED: DELETE = 'delete' INACTIVATE = 'inactivate' # ################################################################################################################################ # ################################################################################################################################ class CHANNEL(Attrs): AMQP = 'amqp' DELIVERY = 'delivery' FANOUT_CALL = 'fanout-call' FANOUT_ON_FINAL = 'fanout-on-final' FANOUT_ON_TARGET = 'fanout-on-target' HTTP_SOAP = 'http-soap' INTERNAL_CHECK = 'internal-check' INVOKE = 'invoke' INVOKE_ASYNC = 'invoke-async' INVOKE_ASYNC_CALLBACK = 'invoke-async-callback' IPC = 'ipc' JSON_RPC = 'json-rpc' NEW_INSTANCE = 'new-instance' NOTIFIER_RUN = 'notifier-run' NOTIFIER_TARGET = 'notifier-target' PARALLEL_EXEC_CALL = 'parallel-exec-call' PARALLEL_EXEC_ON_TARGET = 'parallel-exec-on-target' PUBLISH = 'publish' SCHEDULER = 'scheduler' SCHEDULER_AFTER_ONE_TIME = 'scheduler-after-one-time' SERVICE = 'service' SSO_USER = 'sso-user' STARTUP_SERVICE = 'startup-service' URL_DATA = 'url-data' WEB_SOCKET = 'web-socket' IBM_MQ = 'websphere-mq' WORKER = 'worker' ZMQ = 'zmq' # ################################################################################################################################ # ################################################################################################################################ class CONNECTION: CHANNEL = 'channel' OUTGOING = 'outgoing' # ################################################################################################################################ # ################################################################################################################################ class INVOCATION_TARGET(Attrs): CHANNEL_AMQP = 'channel-amqp' CHANNEL_WMQ = 'channel-wmq' CHANNEL_ZMQ = 'channel-zmq' OUTCONN_AMQP = 'outconn-amqp' OUTCONN_WMQ = 'outconn-wmq' OUTCONN_ZMQ = 'outconn-zmq' SERVICE = 'service' # ################################################################################################################################ # ################################################################################################################################ class DELIVERY_STATE(Attrs): IN_DOUBT = 'in-doubt' IN_PROGRESS_ANY = 'in-progress-any' # A wrapper for all in-progress-* states IN_PROGRESS_RESUBMITTED = 'in-progress-resubmitted' IN_PROGRESS_RESUBMITTED_AUTO = 'in-progress-resubmitted-auto' IN_PROGRESS_STARTED = 'in-progress' IN_PROGRESS_TARGET_OK = 'in-progress-target-ok' IN_PROGRESS_TARGET_FAILURE = 'in-progress-target-failure' CONFIRMED = 'confirmed' FAILED = 'failed' UNKNOWN = 'unknown' # ################################################################################################################################ # ################################################################################################################################ class DELIVERY_CALLBACK_INVOKER(Attrs): SOURCE = 'source' TARGET = 'target' # ################################################################################################################################ # ################################################################################################################################ class BROKER: DEFAULT_EXPIRATION = 15 # In seconds # ################################################################################################################################ # ################################################################################################################################ class MISC: DEFAULT_HTTP_TIMEOUT=10 OAUTH_SIG_METHODS = ['HMAC-SHA1', 'PLAINTEXT'] PIDFILE = 'pidfile' SEPARATOR = ':::' DefaultAdminInvokeChannel = 'admin.invoke.json' Default_Cluster_ID = 1 # ################################################################################################################################ # ################################################################################################################################ class HTTP_SOAP: UNUSED_MARKER = 'unused' class ACCEPT: ANY = '*/*' ANY_INTERNAL = 'haany' class METHOD: ANY_INTERNAL = 'hmany' # ################################################################################################################################ # ################################################################################################################################ class ADAPTER_PARAMS: APPLY_AFTER_REQUEST = 'apply-after-request' APPLY_BEFORE_REQUEST = 'apply-before-request' # ################################################################################################################################ # ################################################################################################################################ class INFO_FORMAT: DICT = 'dict' TEXT = 'text' JSON = 'json' YAML = 'yaml' # ################################################################################################################################ # ################################################################################################################################ class MSG_MAPPER: DICT_TO_DICT = 'dict-to-dict' DICT_TO_XML = 'dict-to-xml' XML_TO_DICT = 'xml-to-dict' XML_TO_XML = 'xml-to-xml' # ################################################################################################################################ # ################################################################################################################################ class CLOUD: class AWS: class S3: class STORAGE_CLASS: STANDARD = 'STANDARD' REDUCED_REDUNDANCY = 'REDUCED_REDUNDANCY' GLACIER = 'GLACIER' DEFAULT = STANDARD def __iter__(self): return iter((self.STANDARD, self.REDUCED_REDUNDANCY, self.GLACIER)) class DEFAULTS: ADDRESS = 'https://s3.amazonaws.com/' CONTENT_TYPE = 'application/octet-stream' # Taken from boto.s3.key.Key.DefaultContentType DEBUG_LEVEL = 0 POOL_SIZE = 5 PROVIDER = 'aws' # ################################################################################################################################ # ################################################################################################################################ class URL_PARAMS_PRIORITY: PATH_OVER_QS = 'path-over-qs' QS_OVER_PATH = 'qs-over-path' DEFAULT = QS_OVER_PATH class __metaclass__(type): def __iter__(self): return iter((self.PATH_OVER_QS, self.QS_OVER_PATH, self.DEFAULT)) # ################################################################################################################################ # ################################################################################################################################ class PARAMS_PRIORITY: CHANNEL_PARAMS_OVER_MSG = 'channel-params-over-msg' MSG_OVER_CHANNEL_PARAMS = 'msg-over-channel-params' DEFAULT = CHANNEL_PARAMS_OVER_MSG def __iter__(self): return iter((self.CHANNEL_PARAMS_OVER_MSG, self.MSG_OVER_CHANNEL_PARAMS, self.DEFAULT)) # ################################################################################################################################ # ################################################################################################################################ class HTTP_SOAP_SERIALIZATION_TYPE: STRING_VALUE = NameId('String', 'string') SUDS = NameId('Suds', 'suds') DEFAULT = STRING_VALUE def __iter__(self): return iter((self.STRING_VALUE, self.SUDS)) # ################################################################################################################################ # ################################################################################################################################ class PUBSUB: SUBSCRIBE_CLASS: '_PUBSUB_SUBSCRIBE_CLASS' SKIPPED_PATTERN_MATCHING = '<skipped>' # All float values are converted to strings of that precision # to make sure pg8000 does not round up the floats with loss of precision. FLOAT_STRING_CONVERT = '{:.7f}' class DATA_FORMAT: CSV = NameId('CSV', DATA_FORMAT.CSV) DICT = NameId('Dict', DATA_FORMAT.DICT) JSON = NameId('JSON', DATA_FORMAT.JSON) POST = NameId('POST', DATA_FORMAT.POST) def __iter__(self): return iter((self.CSV, self.DICT, self.JSON, self.POST)) class HOOK_TYPE: BEFORE_PUBLISH = 'pubsub_before_publish' BEFORE_DELIVERY = 'pubsub_before_delivery' ON_OUTGOING_SOAP_INVOKE = 'pubsub_on_topic_outgoing_soap_invoke' ON_SUBSCRIBED = 'pubsub_on_subscribed' ON_UNSUBSCRIBED = 'pubsub_on_unsubscribed' class HOOK_ACTION: SKIP = 'skip' DELETE = 'delete' DELIVER = 'deliver' def __iter__(self): return iter((self.SKIP, self.DELETE, self.DELIVER)) class DELIVER_BY: PRIORITY = 'priority' EXT_PUB_TIME = 'ext_pub_time' PUB_TIME = 'pub_time' def __iter__(self): return iter((self.PRIORITY, self.EXT_PUB_TIME, self.PUB_TIME)) class ON_NO_SUBS_PUB: ACCEPT = NameId('Accept', 'accept') DROP = NameId('Drop', 'drop') class DEFAULT: DATA_FORMAT = 'text' MIME_TYPE = 'application/json' TOPIC_MAX_DEPTH_GD = 10000 TOPIC_MAX_DEPTH_NON_GD = 1000 DEPTH_CHECK_FREQ = 100 EXPIRATION = 2147483647 # (2 ** 31 - 1) = around 70 years GET_BATCH_SIZE = 50 DELIVERY_BATCH_SIZE = 500 DELIVERY_MAX_RETRY = 123456789 DELIVERY_MAX_SIZE = 500000 # 500 kB PUB_BUFFER_SIZE_GD = 0 TASK_SYNC_INTERVAL = 500 TASK_DELIVERY_INTERVAL = 2000 WAIT_TIME_SOCKET_ERROR = 10 WAIT_TIME_NON_SOCKET_ERROR = 3 ON_NO_SUBS_PUB = 'accept' SK_OPAQUE = ('deliver_to_sk', 'reply_to_sk') Dashboard_Message_Body = 'This is a sample message' Delivery_Err_Should_Block = True Has_GD = False PositionInGroup = 1 UnsubOnWSXClose = True Wrap_One_Msg_In_List = True LimitMessageExpiry = 86_400 # In seconds = 1 day # 0.1 LimitTopicRetention = 86_400 # In seconds = 1 day # 0.1 LimitSubInactivity = 86_400 # In seconds = 1 day # 0.1 DEFAULT_USERNAME = 'zato.pubsub' DEFAULT_SECDEF_NAME = 'pub.zato.pubsub.default' TEST_USERNAME = 'zato.pubsub.test' TEST_SECDEF_NAME = 'zato.pubsub.test.secdef' PUBAPI_USERNAME = 'pubapi' PUBAPI_SECDEF_NAME = 'pubapi' INTERNAL_USERNAME = 'zato.pubsub.internal' INTERNAL_SECDEF_NAME = 'zato.pubsub.internal.secdef' INTERNAL_ENDPOINT_NAME = 'zato.pubsub.internal.default' Topic_Patterns_All = 'pub=/*\nsub=/*' class SERVICE_SUBSCRIBER: NAME = 'zato.pubsub.service.subscriber' TOPICS_ALLOWED = 'sub=/zato/s/to/*' class TOPIC_PATTERN: TO_SERVICE = '/zato/s/to/{}' class QUEUE_TYPE: STAGING = 'staging' CURRENT = 'current' def __iter__(self): return iter((self.STAGING, self.CURRENT)) class GD_CHOICE: DEFAULT_PER_TOPIC = NameId('----------', 'default-per-topic') YES = NameId('Yes', 'true') NO = NameId('No', 'false') def __iter__(self): return iter((self.DEFAULT_PER_TOPIC, self.YES, self.NO)) class QUEUE_ACTIVE_STATUS: FULLY_ENABLED = NameId('Pub and sub', 'pub-sub') PUB_ONLY = NameId('Pub only', 'pub-only') SUB_ONLY = NameId('Sub only', 'sub-only') DISABLED = NameId('Disabled', 'disabled') def __iter__(self): return iter((self.FULLY_ENABLED, self.PUB_ONLY, self.SUB_ONLY, self.DISABLED)) class DELIVERY_METHOD: NOTIFY = NameId('Notify', 'notify') PULL = NameId('Pull', 'pull') WEB_SOCKET = NameId('WebSocket', 'web-socket') def __iter__(self): # Note that WEB_SOCKET is not included because it's not shown in GUI for subscriptions return iter((self.NOTIFY, self.PULL)) class DELIVERY_STATUS: DELIVERED = 1 INITIALIZED = 2 TO_DELETE = 3 WAITING_FOR_CONFIRMATION = 4 class PRIORITY: DEFAULT = 5 MIN = 1 MAX = 9 class ROLE: PUBLISHER = NameId('Publisher', 'pub-only') SUBSCRIBER = NameId('Subscriber', 'sub-only') PUBLISHER_SUBSCRIBER = NameId('Publisher/subscriber', 'pub-sub') def __iter__(self): return iter((self.PUBLISHER, self.SUBSCRIBER, self.PUBLISHER_SUBSCRIBER)) class RunDeliveryStatus: class StatusCode: OK = 1 Warning = 2 Error = 3 class ReasonCode: Error_IO = 1 Error_Other = 2 No_Msg = 3 Error_Runtime_Invoke = 4 class ENDPOINT_TYPE: INTERNAL = NameId('Internal', 'internal') REST = NameId('REST', 'rest') SERVICE = NameId('Service', 'srv') WEB_SOCKETS = NameId('WebSockets', 'wsx') def __iter__(self): return iter(( self.INTERNAL.id, self.REST.id, self.WEB_SOCKETS.id, self.SERVICE.id )) def get_pub_types(self): return iter(( self.REST, self.WEB_SOCKETS, self.SERVICE )) @staticmethod def get_name_by_type(endpoint_type:'str') -> 'str': data = { 'srv': 'Service', 'rest': 'REST', 'internal': 'Internal', 'wsx': 'WebSockets', } return data[endpoint_type] class REDIS: META_TOPIC_LAST_KEY = 'zato.ps.meta.topic.last.%s.%s' META_ENDPOINT_PUB_KEY = 'zato.ps.meta.endpoint.pub.%s.%s' META_ENDPOINT_SUB_KEY = 'zato.ps.meta.endpoint.sub.%s.%s' class MIMEType: Zato = 'application/vnd.zato.ps.msg' class Env: Log_Table = 'Zato_Pub_Sub_Log_Table' # ################################################################################################################################ # ################################################################################################################################ class _PUBSUB_SUBSCRIBE_CLASS: classes = { PUBSUB.ENDPOINT_TYPE.REST.id: 'zato.pubsub.subscription.subscribe-rest', PUBSUB.ENDPOINT_TYPE.SERVICE.id: 'zato.pubsub.subscription.subscribe-service', PUBSUB.ENDPOINT_TYPE.WEB_SOCKETS.id: 'zato.pubsub.subscription.create-wsx-subscription', } @staticmethod def get(name:'str'): return _PUBSUB_SUBSCRIBE_CLASS.classes[name] # ################################################################################################################################ # ################################################################################################################################ PUBSUB.SUBSCRIBE_CLASS = _PUBSUB_SUBSCRIBE_CLASS # ################################################################################################################################ # ################################################################################################################################ skip_endpoint_types = ( PUBSUB.ENDPOINT_TYPE.INTERNAL.id, ) # ################################################################################################################################ # ################################################################################################################################ class EMAIL: class DEFAULT: TIMEOUT = 10 PING_ADDRESS = 'invalid@invalid' GET_CRITERIA = 'UNSEEN' FILTER_CRITERIA = 'isRead ne true' IMAP_DEBUG_LEVEL = 0 class IMAP: class MODE: PLAIN = 'plain' SSL = 'ssl' def __iter__(self): return iter((self.SSL, self.PLAIN)) class ServerType: Generic = 'generic-imap' Microsoft365 = 'microsoft-365' ServerTypeHuman = { ServerType.Generic: 'Generic IMAP', ServerType.Microsoft365: 'Microsoft 365', } class SMTP: class MODE: PLAIN = 'plain' SSL = 'ssl' STARTTLS = 'starttls' def __iter__(self): return iter((self.PLAIN, self.SSL, self.STARTTLS)) # ################################################################################################################################ # ################################################################################################################################ class NOTIF: class DEFAULT: CHECK_INTERVAL = 5 # In seconds CHECK_INTERVAL_SQL = 600 # In seconds NAME_PATTERN = '**' GET_DATA_PATTERN = '**' class TYPE: SQL = 'sql' # ################################################################################################################################ # ################################################################################################################################ class CASSANDRA: class DEFAULT: CONTACT_POINTS = '127.0.0.1\n' EXEC_SIZE = 2 PORT = 9042 PROTOCOL_VERSION = 4 KEYSPACE = 'not-set' class COMPRESSION: DISABLED = 'disabled' ENABLED_NEGOTIATED = 'enabled-negotiated' ENABLED_LZ4 = 'enabled-lz4' ENABLED_SNAPPY = 'enabled-snappy' # ################################################################################################################################ # ################################################################################################################################ class TLS: # All the BEGIN/END blocks we don't want to store in logs. # Taken from https://github.com/openssl/openssl/blob/master/crypto/pem/pem.h # Note that the last one really is empty to denote 'BEGIN PRIVATE KEY' alone. BEGIN_END = ('ANY ', 'RSA ', 'DSA ', 'EC ', 'ENCRYPTED ', '') # Directories in a server's config/tls directory keeping the material DIR_CA_CERTS = 'ca-certs' DIR_KEYS_CERTS = 'keys-certs' class DEFAULT: VERSION = 'SSLv23' CIPHERS = 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:' \ 'ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:' \ 'ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256' class VERSION: SSLv23 = NameId('SSLv23') TLSv1 = NameId('TLSv1') TLSv1_1 = NameId('TLSv1_1') TLSv1_2 = NameId('TLSv1_2') def __iter__(self): return iter((self.SSLv23, self.TLSv1, self.TLSv1_1, self.TLSv1_2)) class CERT_VALIDATE: CERT_NONE = NameId('Disabled', 'CERT_NONE') CERT_OPTIONAL = NameId('Optional', 'CERT_OPTIONAL') CERT_REQUIRED = NameId('Required', 'CERT_REQUIRED') def __iter__(self): return iter((self.CERT_NONE, self.CERT_OPTIONAL, self.CERT_REQUIRED)) class RATE_LIMIT: class TYPE: APPROXIMATE = NameId('Approximate', 'APPROXIMATE') EXACT = NameId('Exact', 'EXACT') def __iter__(self): return iter((self.APPROXIMATE, self.EXACT)) class OBJECT_TYPE: HTTP_SOAP = 'http_soap' SERVICE = 'service' SEC_DEF = 'sec_def' SSO_USER = 'sso_user' # ################################################################################################################################ # ################################################################################################################################ class CommonObject: Prefix_Invalid = 'prefix-invalid' Invalid = 'invalid-invalid' PubSub_Endpoint = 'pubsub-endpoint' PubSub_Publish = 'pubsub-publish' PubSub_Subscription = 'pubsub-subscription' PubSub_Topic = 'pubsub-topic' Security_Basic_Auth = 'security-basic-auth' # ################################################################################################################################ # ################################################################################################################################ class ODOO: class CLIENT_TYPE: OPENERP_CLIENT_LIB = 'openerp-client-lib' class DEFAULT: PORT = 8069 POOL_SIZE = 3 class PROTOCOL: XML_RPC = NameId('XML-RPC', 'xmlrpc') XML_RPCS = NameId('XML-RPCS', 'xmlrpcs') JSON_RPC = NameId('JSON-RPC', 'jsonrpc') JSON_RPCS = NameId('JSON-RPCS', 'jsonrpcs') def __iter__(self): return iter((self.XML_RPC, self.XML_RPCS, self.JSON_RPC, self.JSON_RPCS)) # ################################################################################################################################ # ################################################################################################################################ class SAP: class DEFAULT: INSTANCE = '00' POOL_SIZE = 1 # ################################################################################################################################ # ################################################################################################################################ class STOMP: class DEFAULT: ADDRESS = '127.0.0.1:61613' PROTOCOL = '1.0' TIMEOUT = 10 # In seconds USERNAME = 'guest' ACK_MODE = 'client-individual' # ################################################################################################################################ # ################################################################################################################################ CONTENT_TYPE = Bunch( JSON = 'application/json', PLAIN_XML = 'application/xml', SOAP11 = 'text/xml; charset=UTF-8', SOAP12 = 'application/soap+xml; charset=utf-8', ) # type: Bunch class ContentType: FormURLEncoded = 'application/x-www-form-urlencoded' # ################################################################################################################################ # ################################################################################################################################ class IPC: Status_OK = 'ok' class Default: Timeout = 90 TCP_Port_Start = 17050 class Credentials: Username = 'zato.server.ipc' Password_Key = 'Zato_Server_IPC_Password' class ACTION: INVOKE_SERVICE = 'invoke-service' INVOKE_WORKER_STORE = 'invoke-worker-store' class STATUS: SUCCESS = 'zs' FAILURE = 'zf' LENGTH = 2 # Length of either success or failure messages class CONNECTOR: class USERNAME: FTP = 'zato.connector.ftp' IBM_MQ = 'zato.connector.wmq' SFTP = 'zato.connector.sftp' # ################################################################################################################################ # ################################################################################################################################ class WEB_SOCKET: AUDIT_KEY = 'wsx-connection' GatewayResponseElem = 'zato_gateway_response' class DEFAULT: NEW_TOKEN_TIMEOUT = 5 TOKEN_TTL = 3600 FQDN_UNKNOWN = '(Unknown)' INTERACT_UPDATE_INTERVAL = 60 # 60 minutes = 1 hour PINGS_MISSED_THRESHOLD = 2 PINGS_MISSED_THRESHOLD_OUTGOING = 1 PING_INTERVAL = 45 Socket_Read_Timeout = 60 Socket_Write_Timeout = 60 class PATTERN: BY_EXT_ID = 'zato.by-ext-id.{}' BY_CHANNEL = 'zato.by-channel.{}' MSG_BROWSER_PREFIX = 'zato.msg-browser.' # This is used as a prefix in SQL queries MSG_BROWSER = MSG_BROWSER_PREFIX + '{}' class ACTION: CLIENT_RESPONSE = 'client-response' CREATE_SESSION = 'create-session' INVOKE_SERVICE = 'invoke-service' class OUT_MSG_TYPE: CONNECT = 'connect' MESSAGE = 'message' CLOSE = 'close' class HOOK_TYPE: ON_CONNECTED = 'wsx_on_connected' ON_DISCONNECTED = 'wsx_on_disconnected' ON_PUBSUB_RESPONSE = 'wsx_on_pubsub_response' ON_VAULT_MOUNT_POINT_NEEDED = 'wsx_on_vault_mount_point_needed' class ExtraProperties: StoreCtx = 'StoreCtx' # ################################################################################################################################ # ################################################################################################################################ class APISPEC: OPEN_API_V3 = 'openapi_v3' NAMESPACE_NULL = '' DEFAULT_TAG = 'public' GENERIC_INVOKE_PATH = '/zato/api/invoke/{service_name}' # OpenAPI # ################################################################################################################################ # ################################################################################################################################ class PADDING: LEFT = 'left' RIGHT = 'right' # ################################################################################################################################ # ################################################################################################################################ class AMQP: class DEFAULT: POOL_SIZE = 10 PRIORITY = 5 PREFETCH_COUNT = 0 class ACK_MODE: ACK = NameId('Ack', 'ack') REJECT = NameId('Reject', 'reject') def __iter__(self): return iter((self.ACK, self.REJECT)) # ################################################################################################################################ # ################################################################################################################################ class REDIS: class DEFAULT: PORT = 6379 DB = 0 # ################################################################################################################################ # ################################################################################################################################ class SERVER_STARTUP: class PHASE: FS_CONFIG_ONLY = 'fs-config-only' IMPL_BEFORE_RUN = 'impl-before-run' ON_STARTING = 'on-starting' BEFORE_POST_FORK = 'before-post-fork' AFTER_POST_FORK = 'after-post-fork' IN_PROCESS_FIRST = 'in-process-first' IN_PROCESS_OTHER = 'in-process-other' AFTER_STARTED = 'after-started' # ################################################################################################################################ # ################################################################################################################################ class GENERIC: ATTR_NAME = 'opaque1' DeleteReason = 'DeleteGenericConnection' DeleteReasonBytes = DeleteReason.encode('utf8') InitialReason = 'ReasonInitial' class ConnName: OutconnWSX = 'outgoing WebSocket' class CONNECTION: class TYPE: CHANNEL_FILE_TRANSFER = 'channel-file-transfer' CHANNEL_HL7_MLLP = 'channel-hl7-mllp' CLOUD_CONFLUENCE = 'cloud-confluence' CLOUD_DROPBOX = 'cloud-dropbox' CLOUD_JIRA = 'cloud-jira' CLOUD_MICROSOFT_365 = 'cloud-microsoft-365' CLOUD_SALESFORCE = 'cloud-salesforce' DEF_KAFKA = 'def-kafka' OUTCONN_HL7_FHIR = 'outconn-hl7-fhir' OUTCONN_HL7_MLLP = 'outconn-hl7-mllp' OUTCONN_IM_SLACK = 'outconn-im-slack' OUTCONN_IM_TELEGRAM = 'outconn-im-telegram' OUTCONN_LDAP = 'outconn-ldap' OUTCONN_MONGODB = 'outconn-mongodb' OUTCONN_SFTP = 'outconn-sftp' OUTCONN_WSX = 'outconn-wsx' # ################################################################################################################################ # ################################################################################################################################ class Groups: class Type: Group_Parent = 'zato-group' Group_Member = 'zato-group-member' API_Clients = 'zato-api-creds' Organizations = 'zato-org' class Membership_Action: Add = 'add' Remove = 'remove' # ################################################################################################################################ # ################################################################################################################################ class AuditLog: class Direction: received = 'received' sent = 'sent' class Default: max_len_messages = 50 max_data_stored_per_message = 500 # In kilobytes # ################################################################################################################################ # ################################################################################################################################ class TOTP: default_label = '<default-label>' # ################################################################################################################################ # ################################################################################################################################ class LDAP: class DEFAULT: CONNECT_TIMEOUT = 10 POOL_EXHAUST_TIMEOUT = 5 POOL_KEEP_ALIVE = 30 POOL_LIFETIME = 3600 POOL_MAX_CYCLES = 1 POOL_SIZE = 1 Server_List = 'localhost:1389' Username = 'cn=admin,dc=example,dc=org' class AUTH_TYPE: NTLM = NameId('NTLM', 'NTLM') SIMPLE = NameId('Simple', 'SIMPLE') def __iter__(self): return iter((self.SIMPLE, self.NTLM)) class AUTO_BIND: DEFAULT = NameId('Default', 'DEFAULT') NO_TLS = NameId('No TLS', 'NO_TLS') NONE = NameId('None', 'NONE') TLS_AFTER_BIND = NameId('Bind -> TLS', 'TLS_AFTER_BIND') TLS_BEFORE_BIND = NameId('TLS -> Bind', 'TLS_BEFORE_BIND') def __iter__(self): return iter((self.DEFAULT, self.NONE, self.NO_TLS, self.TLS_AFTER_BIND, self.TLS_BEFORE_BIND)) class GET_INFO: ALL = NameId('All', 'ALL') DSA = NameId('DSA', 'DSA') NONE = NameId('None', 'NONE') SCHEMA = NameId('Schema', 'SCHEMA') OFFLINE_EDIR_8_8_8 = NameId('EDIR 8.8.8', 'OFFLINE_EDIR_8_8_8') OFFLINE_AD_2012_R2 = NameId('AD 2012.R2', 'OFFLINE_AD_2012_R2') OFFLINE_SLAPD_2_4 = NameId('SLAPD 2.4', 'OFFLINE_SLAPD_2_4') OFFLINE_DS389_1_3_3 = NameId('DS 389.1.3.3', 'OFFLINE_DS389_1_3_3') def __iter__(self): return iter((self.NONE, self.ALL, self.SCHEMA, self.DSA, self.OFFLINE_EDIR_8_8_8, self.OFFLINE_AD_2012_R2, self.OFFLINE_SLAPD_2_4, self.OFFLINE_DS389_1_3_3)) class IP_MODE: IP_V4_ONLY = NameId('Only IPv4', 'IP_V4_ONLY') IP_V6_ONLY = NameId('Only IPv6', 'IP_V6_ONLY') IP_V4_PREFERRED = NameId('Prefer IPv4', 'IP_V4_PREFERRED') IP_V6_PREFERRED = NameId('Prefer IPv6', 'IP_V6_PREFERRED') IP_SYSTEM_DEFAULT = NameId('System default', 'IP_SYSTEM_DEFAULT') def __iter__(self): return iter((self.IP_V4_ONLY, self.IP_V6_ONLY, self.IP_V4_PREFERRED, self.IP_V6_PREFERRED, self.IP_SYSTEM_DEFAULT)) class POOL_HA_STRATEGY: FIRST = NameId('First', 'FIRST') RANDOM = NameId('Random', 'RANDOM') ROUND_ROBIN = NameId('Round robin', 'ROUND_ROBIN') def __iter__(self): return iter((self.FIRST, self.RANDOM, self.ROUND_ROBIN)) class SASL_MECHANISM: GSSAPI = NameId('GSS-API', 'GSSAPI') EXTERNAL = NameId('External', 'EXTERNAL') def __iter__(self): return iter((self.EXTERNAL, self.GSSAPI)) # ################################################################################################################################ # ################################################################################################################################ class MONGODB: class DEFAULT: AUTH_SOURCE = 'admin' HB_FREQUENCY = 10 MAX_IDLE_TIME = 600 MAX_STALENESS = -1 POOL_SIZE_MIN = 0 POOL_SIZE_MAX = 5 SERVER_LIST = '127.0.0.1:27017' WRITE_TO_REPLICA = '' WRITE_TIMEOUT = 5 ZLIB_LEVEL = -1 class TIMEOUT: CONNECT = 10 SERVER_SELECT = 5 SOCKET = 30 WAIT_QUEUE = 10 class READ_PREF: PRIMARY = NameId('Primary', 'primary') PRIMARY_PREFERRED = NameId('Primary pref.', 'primaryPreferred') SECONDARY = NameId('Secondary', 'secondary') SECONDARY_PREFERRED = NameId('Secondary pref.', 'secondaryPreferred') NEAREST = NameId('Nearest', 'nearest') def __iter__(self): return iter((self.PRIMARY, self.PRIMARY_PREFERRED, self.SECONDARY, self.SECONDARY_PREFERRED, self.NEAREST)) class AUTH_MECHANISM: SCRAM_SHA_1 = NameId('SCRAM-SHA-1') SCRAM_SHA_256 = NameId('SCRAM-SHA-256') def __iter__(self): return iter((self.SCRAM_SHA_1, self.SCRAM_SHA_256)) # ################################################################################################################################ # ################################################################################################################################ class Kafka: class Default: Broker_Version = '3.3' Server_List = '127.0.0.1:2181' Username = 'admin' class Timeout: Socket = 1 Offsets = 10 # ################################################################################################################################ # ################################################################################################################################ class TELEGRAM: class DEFAULT: ADDRESS = 'https://api.telegram.org/bot{token}/{method}' class TIMEOUT: CONNECT = 5 INVOKE = 10 # ################################################################################################################################ # ################################################################################################################################ class SFTP: class DEFAULT: BANDWIDTH_LIMIT = 10 BUFFER_SIZE = 32768 COMMAND_SFTP = 'sftp' COMMAND_PING = 'ls .' PORT = 22 class LOG_LEVEL: LEVEL0 = NameId('0', '0') LEVEL1 = NameId('1', '1') LEVEL2 = NameId('2', '2') LEVEL3 = NameId('3', '3') LEVEL4 = NameId('4', '4') def __iter__(self): return iter((self.LEVEL0, self.LEVEL1, self.LEVEL2, self.LEVEL3, self.LEVEL4)) def is_valid(self, value): return value in (elem.id for elem in self) class IP_TYPE: IPV4 = NameId('IPv4', 'ipv4') IPV6 = NameId('IPv6', 'ipv6') def __iter__(self): return iter((self.IPV4, self.IPV6)) def is_valid(self, value): return value in (elem.id for elem in self) # ################################################################################################################################ # ################################################################################################################################ class DROPBOX: class DEFAULT: MAX_RETRIES_ON_ERROR = 5 MAX_RETRIES_ON_RATE_LIMIT = None OAUTH2_ACCESS_TOKEN_EXPIRATION = None POOL_SIZE = 10 TIMEOUT = 60 USER_AGENT = None # ################################################################################################################################ # ################################################################################################################################ class JSON_RPC: class PREFIX: CHANNEL = 'json.rpc.channel' OUTGOING = 'json.rpc.outconn' # ################################################################################################################################ # ################################################################################################################################ class CONFIG_FILE: USER_DEFINED = 'user-defined' # We need to use such a constant because we can sometimes be interested in setting # default values which evaluate to boolean False. NO_DEFAULT_VALUE = 'NO_DEFAULT_VALUE' PLACEHOLDER = 'zato_placeholder' # ################################################################################################################################ # ################################################################################################################################ class MS_SQL: ZATO_DIRECT = 'zato+mssql1' EXTRA_KWARGS = 'login_timeout', 'appname', 'blocksize', 'use_mars', 'readonly', 'use_tz', 'bytes_to_unicode', \ 'cafile', 'validate_host' # ################################################################################################################################ # ################################################################################################################################ class FILE_TRANSFER: SCHEDULER_SERVICE = 'pub.zato.channel.file-transfer.handler' class DEFAULT: FILE_PATTERNS = '*' ENCODING = 'utf-8' RelativeDir = '<no-relative-dir>' class SOURCE_TYPE: LOCAL = NameId('Local', 'local') FTP = NameId('FTP', 'ftp') SFTP = NameId('SFTP', 'sftp') def __iter__(self): return iter((self.LOCAL, self.FTP, self.SFTP)) class SOURCE_TYPE_IMPL: LOCAL_INOTIFY = 'local-inotify' LOCAL_SNAPSHOT = 'local-snapshot' # ################################################################################################################################ # ################################################################################################################################ class SALESFORCE: class Default: Address = 'https://example.my.salesforce.com' API_Version = '54.0' # ################################################################################################################################ # ################################################################################################################################ class Atlassian: class Default: Address = 'https://example.atlassian.net' API_Version = '3' # ################################################################################################################################ # ################################################################################################################################ class Microsoft365: class Default: Auth_Redirect_URL = 'https://zato.io/ext/redirect/oauth2' Scopes = [ 'https://graph.microsoft.com/.default' ] # ################################################################################################################################ # ################################################################################################################################ class OAuth: class Default: Auth_Server_URL = 'https://example.com/oauth2/token' Scopes = [] # There are no default scopes Client_ID_Field = 'client_id' Client_Secret_Field = 'client_secret' Grant_Type = 'client_credentials' # ################################################################################################################################ # ################################################################################################################################ class HL7: class Default: """ Default values for HL7 objects. """ # Default address for FHIR connections address_fhir = 'https://fhir.simplifier.net/zato' # Default address and port for MLLP connections channel_host = '0.0.0.0' channel_port = 30901 # Assume that UTF-8 is sent in by default data_encoding = 'utf-8' # Each message may be of at most that many bytes max_msg_size = '1_000_000' # How many seconds to wait for HL7 MLLP responses when invoking a remote end max_wait_time = 60 # At most that many bytes will be read from a socket at a time read_buffer_size = 2048 # We wait at most that many milliseconds for data from a socket in each iteration of the main loop recv_timeout = 250 # At what level to log messages (Python logging) logging_level = 'INFO' # Should we store the contents of messages in logs (Python logging) should_log_messages = False # How many concurrent outgoing connections we allow pool_size = 10 # An MLLP message may begin with these bytes .. start_seq = '0b' # .. and end with these below. end_seq = '1c 0d' class Const: """ Various HL7-related constants. """ class Version: # A generic v2 message, without an indication of a specific release. v2 = NameId('HL7 v2', 'hl7-v2') def __iter__(self): return iter((self.v2,)) class LoggingLevel: Info = NameId('INFO', 'INFO') Debug = NameId('DEBUG', 'DEBUG') def __iter__(self): return iter((self.Info, self.Debug)) class ImplClass: hl7apy = 'hl7apy' zato = 'Zato' class FHIR_Auth_Type: Basic_Auth = NameId('Basic Auth', 'basic-auth') OAuth = NameId('OAuth', 'oauth') def __iter__(self): return iter((self.Basic_Auth, self.OAuth)) # ################################################################################################################################ # ################################################################################################################################ # TODO: SIMPLE_IO.FORMAT should be removed in favour of plain DATA_FORMAT class SIMPLE_IO: class FORMAT(Attrs): FORM_DATA = DATA_FORMAT.FORM_DATA JSON = DATA_FORMAT.JSON COMMON_FORMAT = OrderedDict() COMMON_FORMAT[DATA_FORMAT.JSON] = 'JSON' HTTP_SOAP_FORMAT = OrderedDict() HTTP_SOAP_FORMAT[DATA_FORMAT.JSON] = 'JSON' HTTP_SOAP_FORMAT[HL7.Const.Version.v2.id] = HL7.Const.Version.v2.name HTTP_SOAP_FORMAT[DATA_FORMAT.FORM_DATA] = 'Form data' Bearer_Token_Format = [ NameId('JSON', DATA_FORMAT.JSON), NameId('Form data', DATA_FORMAT.FORM_DATA) ] # ################################################################################################################################ # ################################################################################################################################ class UNITTEST: SQL_ENGINE = 'zato+unittest' HTTP = 'zato+unittest' VAULT_URL = 'https://zato+unittest' class HotDeploy: UserPrefix = 'hot-deploy.user' UserConfPrefix = 'user_conf' Source_Directory = 'src' User_Conf_Directory = 'user-conf' Enmasse_File_Pattern = 'enmasse' Default_Patterns = [User_Conf_Directory, Enmasse_File_Pattern] class Env: Pickup_Patterns = 'Zato_Hot_Deploy_Pickup_Patterns' # ################################################################################################################################ # ################################################################################################################################ class ZatoKVDB: SlowResponsesName = 'zato.service.slow_responses' UsageSamplesName = 'zato.service.usage_samples' CurrentUsageName = 'zato.service.current_usage' PubSubMetadataName = 'zato.pubsub.metadata' SlowResponsesPath = SlowResponsesName + '.json' UsageSamplesPath = UsageSamplesName + '.json' CurrentUsagePath = CurrentUsageName + '.json' PubSubMetadataPath = PubSubMetadataName + '.json' DefaultSyncThreshold = 3_000 DefaultSyncInterval = 3 # ################################################################################################################################ # ################################################################################################################################ class Stats: # This is in milliseconds, for how long do we keep old statistics in persistent storage. Defaults to two years. # 1k ms * 60 s * 60 min * 24 hours * 365 days * 2 years = 94_608_000_000 milliseconds (or two years). # We use milliseconds because that makes it easier to construct tests. MaxRetention = 1000 * 60 * 60 * 24 * 365 * 2 # By default, statistics will be aggregated into time buckets of that duration DefaultAggrTimeFreq = '5min' # Five minutes # We always tabulate by object_id (e.g. service name) TabulateAggr = 'object_id' # ################################################################################################################################ # ################################################################################################################################ class StatsKey: CurrentValue = 'current_value' PerKeyMin = 'min' PerKeyMax = 'max' PerKeyMean = 'mean' PerKeyValue = 'value' PerKeyLastTimestamp = 'last_timestamp' PerKeyLastDuration = 'last_duration' # ################################################################################################################################ # ################################################################################################################################ class SSO: class Default: RESTPrefix = '/zato/sso' class EmailTemplate: SignupConfirm = 'signup-confirm.txt' SignupWelcome = 'signup-welcome.txt' PasswordResetLink = 'password-reset-link.txt' # ################################################################################################################################ # ################################################################################################################################ ZATO_INFO_FILE = '.zato-info' # ################################################################################################################################ # ################################################################################################################################ class SourceCodeInfo: """ Attributes describing the service's source code file. """ __slots__ = 'source', 'source_html', 'len_source', 'path', 'hash', 'hash_method', 'server_name', 'line_number' def __init__(self): self.source = b'' # type: bytes self.source_html = '' # type: str self.len_source = 0 # type: int self.path = None # type: str self.hash = None # type: str self.hash_method = None # type: str self.server_name = None # type: str self.line_number = 0 # type: int # ################################################################################################################################ # ################################################################################################################################ class StatsElem: """ A single element of a statistics query result concerning a particular service. All values make sense only within the time interval of the original query, e.g. a 'min_resp_time' may be 18 ms in this element because it represents statistics regarding, say, the last hour yet in a different period the 'min_resp_time' may be a completely different value. Likewise, 'all' in the description of parameters below means 'all that matched given query criteria' rather than 'all that ever existed'. service_name - name of the service this element describes usage - how many times the service has been invoked mean - an arithmetical average of all the mean response times (in ms) rate - usage rate in requests/s (up to 1 decimal point) time - time spent by this service on processing the messages (in ms) usage_trend - a CSV list of values representing the service usage usage_trend_int - a list of integers representing the service usage mean_trend - a CSV list of values representing mean response times (in ms) mean_trend_int - a list of integers representing mean response times (in ms) min_resp_time - minimum service response time (in ms) max_resp_time - maximum service response time (in ms) all_services_usage - how many times all the services have been invoked all_services_time - how much time all the services spent on processing the messages (in ms) mean_all_services - an arithmetical average of all the mean response times of all services (in ms) usage_perc_all_services - this service's usage as a percentage of all_services_usage (up to 2 decimal points) time_perc_all_services - this service's share as a percentage of all_services_time (up to 2 decimal points) expected_time_elems - an OrderedDict of all the time slots mapped to a mean time and rate temp_rate - a temporary place for keeping request rates, needed to get a weighted mean of uneven execution periods temp_mean - just like temp_rate but for mean response times temp_mean_count - how many periods containing a mean rate there were """ def __init__(self, service_name=None, mean=None): self.service_name = service_name self.usage = 0 self.mean = mean self.rate = 0.0 self.time = 0 self.usage_trend_int = [] self.mean_trend_int = [] self.min_resp_time = maxsize # Assuming that there sure will be at least one response time lower than that self.max_resp_time = 0 self.all_services_usage = 0 self.all_services_time = 0 self.mean_all_services = 0 self.usage_perc_all_services = 0 self.time_perc_all_services = 0 self.expected_time_elems = OrderedDict() self.temp_rate = 0 self.temp_mean = 0 self.temp_mean_count = 0 def get_attrs(self, ignore=None): ignore = ignore or [] for attr in dir(self): if attr.startswith('__') or attr.startswith('temp_') or callable(getattr(self, attr)) or attr in ignore: continue yield attr def to_dict(self, ignore=None): if not ignore: ignore = ['expected_time_elems', 'mean_trend_int', 'usage_trend_int'] return {attr: getattr(self, attr) for attr in self.get_attrs(ignore)} @staticmethod def from_json(item): stats_elem = StatsElem() for k, v in item.items(): setattr(stats_elem, k, v) return stats_elem @staticmethod def from_xml(item): stats_elem = StatsElem() for child in item.getchildren(): setattr(stats_elem, child.xpath('local-name()'), child.pyval) return stats_elem def __repr__(self): buff = StringIO() buff.write('<{} at {} '.format(self.__class__.__name__, hex(id(self)))) attrs = ('{}=[{}]'.format(attr, getattr(self, attr)) for attr in self.get_attrs()) buff.write(', '.join(attrs)) buff.write('>') value = buff.getvalue() buff.close() return value def __iadd__(self, other): self.max_resp_time = max(self.max_resp_time, other.max_resp_time) self.min_resp_time = min(self.min_resp_time, other.min_resp_time) self.usage += other.usage return self def __bool__(self): return bool(self.service_name) # Empty stats_elems won't have a service name set # ################################################################################################################################ # ################################################################################################################################ class SMTPMessage: from_: 'any_' to: 'any_' subject: 'any_' body: 'any_' attachments: 'any_' cc: 'any_' bcc: 'any_' is_html: 'any_' headers: 'any_' charset: 'any_' is_rfc2231: 'any_' def __init__(self, from_=None, to=None, subject='', body='', attachments=None, cc=None, bcc=None, is_html=False, headers=None, charset='utf8', is_rfc2231=True): self.from_ = from_ self.to = to self.subject = subject self.body = body self.attachments = attachments or [] self.cc = cc self.bcc = bcc self.is_html = is_html self.headers = headers or {} self.charset = charset self.is_rfc2231 = is_rfc2231 def attach(self, name, contents): self.attachments.append({'name':name, 'contents':contents}) # ################################################################################################################################ # ################################################################################################################################ class IDEDeploy: Username = 'ide_publisher' # ################################################################################################################################ # ################################################################################################################################ class IMAPMessage: def __init__(self, uid, conn, data): self.uid = uid # type: str self.conn = conn # type: Imbox self.data = data def __repr__(self): class_name = self.__class__.__name__ self_id = hex(id(self)) return '<{} at {}, uid:`{}`, conn.config:`{}`>'.format(class_name, self_id, self.uid, self.conn.config_no_sensitive) def delete(self): raise NotImplementedError('Must be implemented by subclasses') def mark_seen(self): raise NotImplementedError('Must be implemented by subclasses') # ################################################################################################################################ # ################################################################################################################################ class IBMMQCallData: """ Metadata for information returned by IBM MQ in response to underlying MQPUT calls. """ __slots__ = ('msg_id', 'correlation_id') def __init__(self, msg_id, correlation_id): self.msg_id = msg_id self.correlation_id = correlation_id # For compatibility with Zato < 3.2 WebSphereMQCallData = IBMMQCallData # ################################################################################################################################ # ################################################################################################################################ class Name_Prefix: Keysight_Hawkeye = 'KeysightHawkeye.' Keysight_Vision = 'KeysightVision.' Wrapper_Name_Prefix_List = { Name_Prefix.Keysight_Hawkeye, Name_Prefix.Keysight_Vision, } # ################################################################################################################################ # ################################################################################################################################ class Wrapper_Type: Keysight_Hawkeye = 'KeysightHawkeye' Keysight_Vision = 'KeysightVision' # ################################################################################################################################ # ################################################################################################################################ class HAProxy: Default_Memory_Limit = '1024' # In megabytes = 1 GB # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class URLInfo: address: 'str' host: 'str' port: 'int' use_tls: 'bool' # ################################################################################################################################ # ################################################################################################################################ Default_Service_File_Data = """ # -*- coding: utf-8 -*- # File path: {full_path} # Zato from zato.server.service import Service class MyService(Service): # I/O definition input = '-name' output = 'salutation' def handle(self): # Local variables name = self.request.input.name or 'partner' # Our response to produce message = f'Howdy {{name}}!' # Reply to our caller self.response.payload.salutation = message """.lstrip() # ################################################################################################################################ # ################################################################################################################################ default_internal_modules = { 'zato.server.service.internal': True, 'zato.server.service.internal.apispec': True, 'zato.server.service.internal.audit_log': True, 'zato.server.service.internal.cache.builtin': True, 'zato.server.service.internal.cache.builtin.entry': True, 'zato.server.service.internal.cache.builtin.pubapi': True, 'zato.server.service.internal.cache.memcached': True, 'zato.server.service.internal.channel.amqp_': True, 'zato.server.service.internal.channel.file_transfer': True, 'zato.server.service.internal.channel.jms_wmq': True, 'zato.server.service.internal.channel.json_rpc': True, 'zato.server.service.internal.channel.web_socket': True, 'zato.server.service.internal.channel.web_socket.cleanup': True, 'zato.server.service.internal.channel.web_socket.client': True, 'zato.server.service.internal.channel.web_socket.subscription': True, 'zato.server.service.internal.channel.zmq': True, 'zato.server.service.internal.cloud.aws.s3': True, 'zato.server.service.internal.common': True, 'zato.server.service.internal.common.create': True, 'zato.server.service.internal.common.delete': True, 'zato.server.service.internal.common.import_': True, 'zato.server.service.internal.common.sync': True, 'zato.server.service.internal.connector.amqp_': True, 'zato.server.service.internal.crypto': True, 'zato.server.service.internal.definition.amqp_': True, 'zato.server.service.internal.definition.cassandra': True, 'zato.server.service.internal.definition.jms_wmq': True, 'zato.server.service.internal.email.imap': True, 'zato.server.service.internal.email.smtp': True, 'zato.server.service.internal.generic.connection': True, 'zato.server.service.internal.generic.rest_wrapper': True, 'zato.server.service.internal.groups': True, 'zato.server.service.internal.helpers': True, 'zato.server.service.internal.hot_deploy': True, 'zato.server.service.internal.ide_deploy': True, 'zato.server.service.internal.info': True, 'zato.server.service.internal.http_soap': True, 'zato.server.service.internal.kv_data': True, 'zato.server.service.internal.kvdb': True, 'zato.server.service.internal.kvdb.data_dict.dictionary': True, 'zato.server.service.internal.kvdb.data_dict.impexp': True, 'zato.server.service.internal.kvdb.data_dict.translation': True, 'zato.server.service.internal.message.namespace': True, 'zato.server.service.internal.message.xpath': True, 'zato.server.service.internal.message.json_pointer': True, 'zato.server.service.internal.notif': True, 'zato.server.service.internal.notif.sql': True, 'zato.server.service.internal.outgoing.amqp_': True, 'zato.server.service.internal.outgoing.ftp': True, 'zato.server.service.internal.outgoing.jms_wmq': True, 'zato.server.service.internal.outgoing.odoo': True, 'zato.server.service.internal.outgoing.redis': True, 'zato.server.service.internal.outgoing.sql': True, 'zato.server.service.internal.outgoing.sap': True, 'zato.server.service.internal.outgoing.sftp': True, 'zato.server.service.internal.outgoing.zmq': True, 'zato.server.service.internal.pattern': True, 'zato.server.service.internal.pickup': True, 'zato.server.service.internal.pattern.invoke_retry': True, 'zato.server.service.internal.pubsub': True, 'zato.server.service.internal.pubsub.delivery': True, 'zato.server.service.internal.pubsub.endpoint': True, 'zato.server.service.internal.pubsub.hook': True, 'zato.server.service.internal.pubsub.message': True, 'zato.server.service.internal.pubsub.migrate': True, 'zato.server.service.internal.pubsub.pubapi': True, 'zato.server.service.internal.pubsub.publish': True, 'zato.server.service.internal.pubsub.subscription': True, 'zato.server.service.internal.pubsub.queue': True, 'zato.server.service.internal.pubsub.task': True, 'zato.server.service.internal.pubsub.task.delivery': True, 'zato.server.service.internal.pubsub.task.delivery.message': True, 'zato.server.service.internal.pubsub.task.delivery.server': True, 'zato.server.service.internal.pubsub.task.sync': True, 'zato.server.service.internal.pubsub.topic': True, 'zato.server.service.internal.query.cassandra': True, 'zato.server.service.internal.scheduler': True, 'zato.server.service.internal.search.es': True, 'zato.server.service.internal.search.solr': True, 'zato.server.service.internal.security': True, 'zato.server.service.internal.security.apikey': True, 'zato.server.service.internal.security.aws': True, 'zato.server.service.internal.security.basic_auth': True, 'zato.server.service.internal.security.jwt': True, 'zato.server.service.internal.security.ntlm': True, 'zato.server.service.internal.security.oauth': True, 'zato.server.service.internal.security.rbac': True, 'zato.server.service.internal.security.rbac.client_role': True, 'zato.server.service.internal.security.rbac.permission': True, 'zato.server.service.internal.security.rbac.role': True, 'zato.server.service.internal.security.rbac.role_permission': True, 'zato.server.service.internal.security.tls.ca_cert': True, 'zato.server.service.internal.security.tls.channel': True, 'zato.server.service.internal.security.tls.key_cert': True, 'zato.server.service.internal.security.wss': True, 'zato.server.service.internal.security.vault.connection': True, 'zato.server.service.internal.security.vault.policy': True, 'zato.server.service.internal.security.xpath': True, 'zato.server.service.internal.server': True, 'zato.server.service.internal.service': True, 'zato.server.service.internal.service.ide': True, 'zato.server.service.internal.sms': True, 'zato.server.service.internal.sms.twilio': True, 'zato.server.service.internal.sso': True, 'zato.server.service.internal.sso.cleanup': True, 'zato.server.service.internal.sso.password_reset': True, 'zato.server.service.internal.sso.session': True, 'zato.server.service.internal.sso.session_attr': True, 'zato.server.service.internal.sso.signup': True, 'zato.server.service.internal.sso.user': True, 'zato.server.service.internal.sso.user_attr': True, 'zato.server.service.internal.stats': True, 'zato.server.service.internal.stats.summary': True, 'zato.server.service.internal.stats.trends': True, 'zato.server.service.internal.updates': True, } # ################################################################################################################################ # ################################################################################################################################
90,789
Python
.py
1,780
44.626404
130
0.44564
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,541
typing_.py
zatosource_zato/code/zato-common/src/zato/common/typing_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ # stdlib from datetime import date, datetime from decimal import Decimal as decimal_ from pathlib import Path from types import ModuleType from typing import \ Any as any_, \ BinaryIO as binaryio_, \ Callable as callable_, \ cast as cast_, \ Dict as dict_, \ Generator as generator_, \ Iterator as iterator_, \ IO as io_, \ NoReturn as noreturn, \ List as list_, \ Optional as optional, \ Text as str_, \ TextIO as textio_, \ Tuple as tuple_, \ Type as type_, \ TypeVar as typevar_, \ Set as set_, \ Union as union_ # typing-extensions from typing_extensions import \ TypeAlias as typealias_ # type: ignore # dacite from dacite.core import from_dict # stdlib from dataclasses import * # type: ignore # Zato from zato.common.marshal_.model import BaseModel # ################################################################################################################################ # ################################################################################################################################ # # TypedDict # try: from typing import TypedDict from typing import Protocol except ImportError: from zato.common.ext.typing_extensions import TypedDict from zato.common.ext.typing_extensions import Protocol # ################################################################################################################################ # ################################################################################################################################ # For flake8 from_dict = from_dict optional = optional Protocol = Protocol TypedDict = TypedDict # ################################################################################################################################ # ################################################################################################################################ class _ISOTimestamp: pass class DateTimeWithZone(datetime): pass # ################################################################################################################################ # ################################################################################################################################ # Some basic types are defined upfront to make sure that none of the later definitions results in the type "Unknown". intnone = optional[int] strnone = optional[str] anydict = dict_[any_, any_] anydictnone = optional[anydict] anylist = list_[any_] anylistnone = optional[anylist] anynone = optional[any_] anyset = set_[any_] anytuple = tuple_[any_, ...] binaryio_ = binaryio_ boolnone = optional[bool] byteslist = list_[bytes] bytesnone = optional[bytes] callable_ = callable_[..., any_] callnone = optional[callable_] cast_ = cast_ commondict = dict_[str, union_[int, str_, bool, float, anydict, anylist, datetime, None]] commoniter = union_[anylist, anytuple] date_ = date datetime_ = datetime datetimez = DateTimeWithZone isotimestamp = _ISOTimestamp decimal_ = decimal_ decnone = optional[decimal_] dictlist = list_[anydict] dictnone = optional[anydict] dictorlist = union_[anydict, anylist] dtnone = optional[datetime] floatnone = optional[float] generator_ = generator_ intanydict = dict_[int, any_] intdict = dict_[int, int] intdictdict = dict_[int, anydict] intlist = list_[int] intlistempty = list_[intnone] intlistnone = optional[list_[int]] intset = set_[int] intsetdict = dict_[int, anyset] intstrdict = dict_[int, str] iterator_ = iterator_ iobytes_ = io_[bytes] listnone = anylistnone listorstr = union_[anylist, str] model = type_[BaseModel] modelnone = optional[type_[BaseModel]] module_ = ModuleType noreturn = noreturn path_ = Path pathlist = list_[path_] set_ = set_ stranydict = dict_[str, any_] strcalldict = dict_[str, callable_] strdict = stranydict strbytes = union_[str_, bytes] strbooldict = dict_[str, bool] strcalldict = dict_[str, callable_] strdictdict = dict_[str, anydict] strdictlist = list_[stranydict] strdictnone = union_[stranydict, None] strint = union_[str_, int] strintbool = union_[str_, int, bool] strintdict = dict_[str, int] strintnone = union_[strnone, intnone] strlist = list_[str] strlistdict = dict_[str, anylist] strlistempty = list_[strnone] strlistnone = optional[list_[str_]] strordict = union_[str, anydict] strordictnone = union_[strnone, anydictnone] strorfloat = union_[str, float] stroriter = union_[str, anylist, anytuple] strorlist = listorstr strorlistnone = optional[listorstr] strset = set_[str] strsetdict = dict_[str, anyset] strstrdict = dict_[str, str] strtuple = tuple_[str, ...] textio_ = textio_ textionone = textio_ tuple_ = tuple_ tuplist = union_[anylist, anytuple] tupnone = optional[anytuple] type_ = type_ typealias_ = typealias_ typevar_ = typevar_ union_ = union_ # ################################################################################################################################ # ################################################################################################################################ def instance_from_dict(class_:'any_', data:'anydict') -> 'any_': instance = class_() for key, value in data.items(): setattr(instance, key, value) return instance # ################################################################################################################################ def is_union(elem:'any_') -> 'bool': origin = getattr(elem, '__origin__', None) # type: any_ return origin and getattr(origin, '_name', '') == 'Union' # ################################################################################################################################ def extract_from_union(elem:'any_') -> 'anytuple': field_type_args = elem.__args__ # type: anylist field_type = field_type_args[0] union_with = field_type_args[1] return field_type_args, field_type, union_with # ################################################################################################################################ def list_field() -> 'callable_[anylist]': # type: ignore return field(default_factory=list) # noqa: F405 # ################################################################################################################################ def dict_field() -> 'callable_[anydict]': # type: ignore return field(default_factory=dict) # noqa: F405 # ################################################################################################################################ # ################################################################################################################################
7,599
Python
.py
178
40.668539
130
0.447165
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,542
match.py
zatosource_zato/code/zato-common/src/zato/common/match.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import logging # globre from globre import match as globre_match # Paste from paste.util.converters import asbool # Zato from zato.common.api import FALSE_TRUE, TRUE_FALSE logger = logging.getLogger(__name__) class Matcher: def __init__(self): self.config = None self.items = {True:[], False:[]} self.order1 = None self.order2 = None self.is_allowed_cache = {} self.special_case = None def read_config(self, config): self.config = config order = config.get('order', FALSE_TRUE) self.order1, self.order2 = (True, False) if order == TRUE_FALSE else (False, True) for key, value in config.items(): # Ignore meta key(s) if key == 'order': continue value = asbool(value) # Add new items self.items[value].append(key) # Now sort everything lexicographically, the way it will be used in run-time for key in self.items: self.items[key] = sorted(self.items[key], reverse=True) for empty, non_empty in ((True, False), (False, True)): if not self.items[empty] and '*' in self.items[non_empty]: self.special_case = non_empty break def is_allowed(self, value): logger.debug('Cache:`%s`, value:`%s`', self.is_allowed_cache, value) if self.special_case is not None: return self.special_case try: return self.is_allowed_cache[value] except KeyError: _match = globre_match is_allowed = None for order in self.order1, self.order2: for pattern in self.items[order]: if _match(pattern, value): is_allowed = order # No match at all - we don't allow it in that case is_allowed = is_allowed if (is_allowed is not None) else False self.is_allowed_cache[value] = is_allowed return is_allowed
2,281
Python
.py
58
30.224138
90
0.599273
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,543
ibm_mq.py
zatosource_zato/code/zato-common/src/zato/common/ibm_mq.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ class ConnectorClosedException(Exception): def __init__(self, exc, message): self.inner_exc = exc super().__init__(message)
293
Python
.py
9
29
64
0.66548
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,544
sso.py
zatosource_zato/code/zato-common/src/zato/common/sso.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,545
defaults.py
zatosource_zato/code/zato-common/src/zato/common/defaults.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # A place for storing all the defaults values. web_admin_host = '0.0.0.0' web_admin_port = 8183 http_plain_server_port = 17010
284
Python
.py
9
30
64
0.714815
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,546
repo.py
zatosource_zato/code/zato-common/src/zato/common/repo.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging import os import socket # Zato from zato.common.util.api import get_current_user # ################################################################################################################################ logger = logging.getLogger(__name__) logger_bzr = logging.getLogger('bzr') logger_bzr.setLevel(logging.WARN) logger_sh = logging.getLogger('sh.command') logger_sh.setLevel(logging.WARN) # ################################################################################################################################ # We use Bazaar under Zato 3.0 with Python 2.7. Any newer version of Zato, or Zato 3.0 with Python 3.x, uses git. # ################################################################################################################################ # ################################################################################################################################ class _BaseRepoManager: def __init__(self, repo_location='.'): self.repo_location = os.path.abspath(os.path.expanduser(repo_location)) # ################################################################################################################################ # ################################################################################################################################ class PassThroughRepoManager(_BaseRepoManager): def ensure_repo_consistency(self): pass # ################################################################################################################################ # ################################################################################################################################ class GitRepoManager(_BaseRepoManager): def ensure_repo_consistency(self): # Use sh for git commands import sh # Always work in the same directory as the repository is in sh.cd(self.repo_location) # (Re-)init the repository sh.git.init(self.repo_location) # Set user info current_user = get_current_user() sh.git.config('user.name', current_user) sh.git.config('user.email', '{}@{}'.format(current_user, socket.getfqdn())) # Default branch is called 'main' sh.git.checkout('-B', 'main') # Add all files sh.git.add('-A', self.repo_location) output = sh.git.status('--porcelain') # type: str output = output.strip() # And commit changes if there are any if output: sh.git.commit('-m', 'Committing latest changes') # ################################################################################################################################ # ################################################################################################################################ RepoManager = PassThroughRepoManager # ################################################################################################################################ # ################################################################################################################################
3,312
Python
.py
57
53.403509
130
0.350991
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,547
__init__.py
zatosource_zato/code/zato-common/src/zato/common/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from zato.common.api import * # noqa: F401 from zato.common.vault_ import * # noqa: F401
247
Python
.py
7
33.857143
64
0.696203
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,548
dispatch.py
zatosource_zato/code/zato-common/src/zato/common/dispatch.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from logging import getLogger # gevent from gevent.lock import RLock logger = getLogger(__name__) # ################################################################################################################################ UPDATES = 'CREATE', 'EDIT', 'DELETE', 'CHANGE_PASSWORD' class Dispatcher: def __init__(self): self.lock = RLock() self.listeners = {} def _listen(self, event, callback, **opaque): self.listeners.setdefault(event, []).append((callback, opaque)) def listen(self, *args, **kwargs): with self.lock: self._listen(*args, **kwargs) def listen_for_updates(self, msg, callback, **opaque): with self.lock: for name, value in msg.items(): for update in UPDATES: if update in name: self._listen(value.value, callback, **opaque) def notify(self, event, ctx): with self.lock: for ev, values in self.listeners.items(): if ev == event: for callback, opaque in values: callback(event, ctx, **opaque) # A singleton used throughout the whole application. dispatcher = Dispatcher()
1,474
Python
.py
36
33.305556
130
0.559382
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,549
scheduler.py
zatosource_zato/code/zato-common/src/zato/common/scheduler.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from dataclasses import dataclass # Zato from zato.common.api import SCHEDULER # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import list_, strdict, strlist # ################################################################################################################################ # ################################################################################################################################ pubsub_cleanup_job = SCHEDULER.PubSubCleanupJob # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class SchedulerCredentials: username:'str' password:'str' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class PathAction: path:'str' action:'str' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class _BaseConfig: host:'str' port:'int' use_tls:'bool' verify_tls:'bool' @dataclass(init=False) class ServerSchedulerConfig(_BaseConfig): username:'str' password:'str' @dataclass(init=False) class SchedulerConfig(_BaseConfig): bind_host:'str' bind_port:'int' tls_version:'str' tls_version:'str' tls_ciphers:'str' priv_key_location:'str' pub_key_location:'str' cert_location:'str' ca_certs_location:'str' api_user_list:'list_[SchedulerCredentials]' config_action_user_list:'list_[SchedulerCredentials]' # ################################################################################################################################ # ################################################################################################################################ startup_jobs=f""" [zato.outgoing.sql.auto-ping] minutes=3 service=zato.outgoing.sql.auto-ping [zato.wsx.cleanup] minutes=30 service=pub.zato.channel.web-socket.cleanup-wsx [{pubsub_cleanup_job}] minutes=60 service=zato.pubsub.cleanup-service extra= """.lstrip() # ################################################################################################################################ # ################################################################################################################################ def get_startup_job_services() -> 'strlist': # Zato from zato.common.util.api import get_config_from_string config = get_config_from_string(startup_jobs) return sorted(value.service for value in config.values()) # ################################################################################################################################ # ################################################################################################################################ def get_server_scheduler_config(fs_config:'strdict') -> 'ServerSchedulerConfig': # Our response to produce out = ServerSchedulerConfig() return out # ################################################################################################################################ # ################################################################################################################################
4,146
Python
.py
82
47.804878
130
0.311943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,550
audit_log.py
zatosource_zato/code/zato-common/src/zato/common/audit_log.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from collections import deque from datetime import datetime from logging import getLogger # gevent from gevent.lock import RLock # Zato from zato.common.api import AuditLog as CommonAuditLog, CHANNEL, GENERIC, WEB_SOCKET from zato.common.util.api import new_cid # ################################################################################################################################ # ################################################################################################################################ _sent = CommonAuditLog.Direction.sent _received = CommonAuditLog.Direction.received event_attrs = 'direction', 'data', 'event_id', 'timestamp', 'msg_id', 'in_reply_to', 'type_', 'object_id', 'conn_id' transfer_attrs = 'total_bytes_received', 'total_messages_received', 'avg_msg_size_received', 'first_received', 'last_received', \ 'total_bytes_sent', 'total_messages_sent', 'avg_msg_size_sent', 'first_sent', 'last_sent', \ 'data', 'messages' config_attrs = 'type_', 'object_id', 'max_len_messages_received', 'max_len_messages_sent', \ 'max_bytes_per_message_received', 'max_bytes_per_message_sent', \ 'max_bytes_per_message' # ################################################################################################################################ # ################################################################################################################################ def new_event_id(prefix='zae', _new_cid=new_cid): return '{}{}'.format(prefix, _new_cid()) # ################################################################################################################################ # ################################################################################################################################ class DataEvent: def __init__(self, direction, _utcnow=datetime.utcnow, _new_event_id=new_event_id): self.direction = direction self.event_id = _new_event_id() self.data = b'' self.timestamp = _utcnow() self.msg_id = '' self.in_reply_to = '' self.type_ = '' self.object_id = '' self.conn_id = '' # This will be the other half of a request or response, # e.g. it will link DataSent to DataReceived or ther other way around. self.counterpart = None # type: DataEvent # ################################################################################################################################ def to_dict(self): out = {} for name in event_attrs: out[name] = getattr(self, name) return out # ################################################################################################################################ # ################################################################################################################################ class DataSent(DataEvent): """ An individual piece of data sent by Zato to a remote end. This can be a request or a reply to a previous one sent by an API client. """ __slots__ = event_attrs def __init__(self, _direction=_sent): super().__init__(_direction) # ################################################################################################################################ # ################################################################################################################################ class DataReceived(DataEvent): """ An individual piece of data received by Zato from a remote end. This can be a request or a reply to a previous one sent by an API client. """ __slots__ = event_attrs def __init__(self, _direction=_received): super().__init__(_direction) # ################################################################################################################################ # ################################################################################################################################ class LogContainerConfig: """ Data retention configuration for a specific object. """ __slots__ = config_attrs def __init__(self): self.type_ = '<log-container-config-type_-not-set>' self.object_id = '<log-container-config-object_id-not-set>' self.max_len_messages_received = 0 self.max_len_messages_sent = 0 self.max_bytes_per_message_received = 0 self.max_bytes_per_message_sent = 0 # ################################################################################################################################ # ################################################################################################################################ class LogContainer: """ Stores messages for a specific object, e.g. an individual REST or HL7 channel. """ __slots__ = config_attrs + transfer_attrs + ('lock',) def __init__(self, config, _sent=_sent, _received=_received): # type: (LogContainerConfig) # To serialise access to the underlying storage self.lock = { _sent: RLock(), _received: RLock(), } self.type_ = config.type_ self.object_id = config.object_id self.max_len_messages_sent = config.max_len_messages_sent self.max_len_messages_received = config.max_len_messages_received self.max_bytes_per_message = { _sent: config.max_bytes_per_message_sent, _received: config.max_bytes_per_message_received, } self.total_bytes_sent = 0 self.total_messages_sent = 0 self.avg_msg_size_sent = 0 self.first_sent = None # type: datetime self.last_sent = None # type: datetime self.total_bytes_received = 0 self.total_messages_received = 0 self.avg_msg_size_received = 0 self.first_received = None # type: datetime self.last_received = None # type: datetime # These two deques are where the actual data is kept self.messages = {} self.messages[_sent] = deque(maxlen=self.max_len_messages_sent) self.messages[_received] = deque(maxlen=self.max_len_messages_received) # ################################################################################################################################ def store(self, data_event): with self.lock[data_event.direction]: # Make sure we do not exceed our limit of bytes stored max_len = self.max_bytes_per_message[data_event.direction] data_event.data = data_event.data[:max_len] storage = self.messages[data_event.direction] # type: deque storage.append(data_event) # ################################################################################################################################ def to_dict(self, _sent=_sent, _received=_received): out = { _sent: [], _received: [] } for name in (_sent, _received): messages = out[name] with self.lock[name]: for message in self.messages[name]: # type: DataEvent messages.append(message.to_dict()) return out # ################################################################################################################################ # ################################################################################################################################ class AuditLog: """ Stores a log of messages for channels, outgoing connections or other objects. """ def __init__(self): # Update lock self.lock = RLock() # The main log - keys are object types, values are dicts mapping object IDs to LogContainer objects self._log = { CHANNEL.HTTP_SOAP: {}, CHANNEL.WEB_SOCKET: {}, GENERIC.CONNECTION.TYPE.CHANNEL_HL7_MLLP: {}, WEB_SOCKET.AUDIT_KEY: {}, } # Python logging self.logger = getLogger('zato') # ################################################################################################################################ def get_container(self, type_, object_id): # type: (str, str) -> LogContainer # Note that below we ignore any key errors, effectively silently dropping invalid requests. return self._log.get(type_, {}).get(object_id) # ################################################################################################################################ def _create_container(self, config): # type: (LogContainerConfig) # Make sure the object ID is a string (it can be an int) config.object_id = str(config.object_id) # Get the mapping of object types to object IDs .. container_dict = self._log.setdefault(config.type_, {}) # .. make sure we do not have such an object already .. if config.object_id in container_dict: raise ValueError('Container already found `{}` ({})'.format(config.object_id, config.type_)) # .. if we are here, it means that we are really adding a new container .. container = LogContainer(config) # .. finally, we can attach it to the log by the object's ID. container_dict[config.object_id] = container # ################################################################################################################################ def create_container(self, config): # type: (LogContainerConfig) with self.lock: self._create_container(config) # ################################################################################################################################ def _delete_container(self, type_, object_id): # type: (str, str) # Make sure the object ID is a string (it can be an int) object_id = str(object_id) # Get the mapping of object types to object IDs .. try: container_dict = self._log[type_] # type: dict except KeyError: raise ValueError('Container type not found `{}` among `{}` ({})'.format(type_, sorted(self._log), object_id)) # No KeyError = we recognised that type .. # .. so we can now try to delete that container by its object's ID. # Note that we use .pop on purpose - e.g. when a server has just started, # it may not have any such an object yet but the user may already try to edit # the object this log is attached to. Using .pop ignores non-existing keys. container_dict.pop(object_id, None) # ################################################################################################################################ def delete_container(self, type_, object_id): # type: (str, str) with self.lock: self._delete_container(type_, object_id) # ################################################################################################################################ def edit_container(self, config): # type: (LogContainerConfig) with self.lock: self._delete_container(config.type_, config.object_id) self._create_container(config) # ################################################################################################################################ def store_data(self, data_event): # type: (DataEvent) -> None # We always store IDs as string objects data_event.object_id = str(data_event.object_id) # At this point we assume that all the dicts and containers already exist container_dict = self._log[data_event.type_] container = container_dict[data_event.object_id] # type: LogContainer container.store(data_event) # ################################################################################################################################ def store_data_received(self, data_event): # type: (DataReceived) -> None self.store_data(data_event) # ################################################################################################################################ def store_data_sent(self, data_event): # type: (DataSent) -> None self.store_data(data_event) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': pass
13,006
Python
.py
226
49.955752
130
0.426603
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,551
groups.py
zatosource_zato/code/zato-common/src/zato/common/groups.py
# -*- coding: utf-8 -*- """ Copyright (C) 2024, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from dataclasses import dataclass # Zato from zato.server.service import Model # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class Member(Model): id: 'int' name: 'str' type: 'str' group_id: 'int' security_id: 'int' sec_type: 'str' username: 'str' = '' password: 'str' = '' header_value: 'str' = '' # ################################################################################################################################ # ################################################################################################################################
1,006
Python
.py
24
39
130
0.303498
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,552
broker_message.py
zatosource_zato/code/zato-common/src/zato/common/broker_message.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from inspect import isclass # candv from candv import Constants as _Constants, ValueConstant as _ValueConstant # Python 2/3 compatibility from zato.common.ext.future.utils import iteritems from zato.common.py23_.past.builtins import cmp class Constants(_Constants): values = _Constants.constants class ValueConstant(_ValueConstant): def __cmp__(self, other): return cmp(self.value, (other.value if isinstance(other, ValueConstant) else other)) class MESSAGE: MESSAGE_TYPE_LENGTH = 4 TOKEN_LENGTH = 32 TOKEN_START = MESSAGE_TYPE_LENGTH TOKEN_END = MESSAGE_TYPE_LENGTH + TOKEN_LENGTH PAYLOAD_START = MESSAGE_TYPE_LENGTH + TOKEN_LENGTH NULL_TOKEN = '0' * TOKEN_LENGTH class MESSAGE_TYPE: TO_SCHEDULER = '0000' TO_PARALLEL_ANY = '0001' TO_PARALLEL_ALL = '0002' TO_AMQP_PUBLISHING_CONNECTOR_ALL = '0003' TO_AMQP_CONSUMING_CONNECTOR_ALL = '0004' TO_AMQP_CONNECTOR_ALL = '0005' TO_JMS_WMQ_PUBLISHING_CONNECTOR_ALL = '0006' TO_JMS_WMQ_CONSUMING_CONNECTOR_ALL = '0007' TO_JMS_WMQ_CONNECTOR_ALL = '0008' USER_DEFINED_START = '5000' TOPICS = { MESSAGE_TYPE.TO_SCHEDULER: '/zato/to-scheduler', MESSAGE_TYPE.TO_PARALLEL_ANY: '/zato/to-parallel/any', MESSAGE_TYPE.TO_PARALLEL_ALL: '/zato/to-parallel/all', MESSAGE_TYPE.TO_AMQP_PUBLISHING_CONNECTOR_ALL: '/zato/connector/amqp/publishing/all', MESSAGE_TYPE.TO_AMQP_CONSUMING_CONNECTOR_ALL: '/zato/connector/amqp/consuming/all', MESSAGE_TYPE.TO_AMQP_CONNECTOR_ALL: '/zato/connector/amqp/all', MESSAGE_TYPE.TO_JMS_WMQ_PUBLISHING_CONNECTOR_ALL: '/zato/connector/jms-wmq/publishing/all', MESSAGE_TYPE.TO_JMS_WMQ_CONSUMING_CONNECTOR_ALL: '/zato/connector/jms-wmq/consuming/all', MESSAGE_TYPE.TO_JMS_WMQ_CONNECTOR_ALL: '/zato/connector/jms-wmq/all', } KEYS = {k:v.replace('/zato','').replace('/',':') for k,v in TOPICS.items()} class SCHEDULER(Constants): code_start = 100000 PAUSE = ValueConstant('') RESUME = ValueConstant('') CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') EXECUTE = ValueConstant('') JOB_EXECUTED = ValueConstant('') SET_JOB_INACTIVE = ValueConstant('') DELETE_PUBSUB_SUBSCRIBER = ValueConstant('') SET_SERVER_ADDRESS = ValueConstant('') SET_SCHEDULER_ADDRESS = ValueConstant('') class ZMQ_SOCKET(Constants): code_start = 100200 CLOSE = ValueConstant('') class SECURITY(Constants): code_start = 100400 BASIC_AUTH_CREATE = ValueConstant('') BASIC_AUTH_EDIT = ValueConstant('') BASIC_AUTH_DELETE = ValueConstant('') BASIC_AUTH_CHANGE_PASSWORD = ValueConstant('') JWT_CREATE = ValueConstant('') JWT_EDIT = ValueConstant('') JWT_DELETE = ValueConstant('') JWT_CHANGE_PASSWORD = ValueConstant('') WSS_CREATE = ValueConstant('') WSS_EDIT = ValueConstant('') WSS_DELETE = ValueConstant('') WSS_CHANGE_PASSWORD = ValueConstant('') OAUTH_CREATE = ValueConstant('') OAUTH_EDIT = ValueConstant('') OAUTH_DELETE = ValueConstant('') OAUTH_CHANGE_PASSWORD = ValueConstant('') NTLM_CREATE = ValueConstant('') NTLM_EDIT = ValueConstant('') NTLM_DELETE = ValueConstant('') NTLM_CHANGE_PASSWORD = ValueConstant('') AWS_CREATE = ValueConstant('') AWS_EDIT = ValueConstant('') AWS_DELETE = ValueConstant('') AWS_CHANGE_PASSWORD = ValueConstant('') APIKEY_CREATE = ValueConstant('') APIKEY_EDIT = ValueConstant('') APIKEY_DELETE = ValueConstant('') APIKEY_CHANGE_PASSWORD = ValueConstant('') XPATH_SEC_CREATE = ValueConstant('') XPATH_SEC_EDIT = ValueConstant('') XPATH_SEC_DELETE = ValueConstant('') XPATH_SEC_CHANGE_PASSWORD = ValueConstant('') TLS_CA_CERT_CREATE = ValueConstant('') TLS_CA_CERT_EDIT = ValueConstant('') TLS_CA_CERT_DELETE = ValueConstant('') TLS_CHANNEL_SEC_CREATE = ValueConstant('') TLS_CHANNEL_SEC_EDIT = ValueConstant('') TLS_CHANNEL_SEC_DELETE = ValueConstant('') TLS_KEY_CERT_CREATE = ValueConstant('') TLS_KEY_CERT_EDIT = ValueConstant('') TLS_KEY_CERT_DELETE = ValueConstant('') class DEFINITION(Constants): code_start = 100600 AMQP_CREATE = ValueConstant('') AMQP_EDIT = ValueConstant('') AMQP_DELETE = ValueConstant('') AMQP_CHANGE_PASSWORD = ValueConstant('') WMQ_CREATE = ValueConstant('') WMQ_EDIT = ValueConstant('') WMQ_DELETE = ValueConstant('') WMQ_CHANGE_PASSWORD = ValueConstant('') WMQ_PING = ValueConstant('') ZMQ_CREATE = ValueConstant('') ZMQ_EDIT = ValueConstant('') ZMQ_DELETE = ValueConstant('') CASSANDRA_CREATE = ValueConstant('') CASSANDRA_EDIT = ValueConstant('') CASSANDRA_DELETE = ValueConstant('') CASSANDRA_CHANGE_PASSWORD = ValueConstant('') class OUTGOING(Constants): code_start = 100800 AMQP_CREATE = ValueConstant('') AMQP_EDIT = ValueConstant('') AMQP_DELETE = ValueConstant('') AMQP_PUBLISH = ValueConstant('') WMQ_CREATE = ValueConstant('') WMQ_EDIT = ValueConstant('') WMQ_DELETE = ValueConstant('') WMQ_SEND = ValueConstant('') ZMQ_CREATE = ValueConstant('') ZMQ_EDIT = ValueConstant('') ZMQ_DELETE = ValueConstant('') ZMQ_SEND = ValueConstant('') SQL_CREATE_EDIT = ValueConstant('') # Same for creating and updating the pools SQL_CHANGE_PASSWORD = ValueConstant('') SQL_DELETE = ValueConstant('') HTTP_SOAP_CREATE_EDIT = ValueConstant('') # Same for creating and updating HTTP_SOAP_DELETE = ValueConstant('') FTP_CREATE_EDIT = ValueConstant('') # Same for creating and updating FTP_DELETE = ValueConstant('') FTP_CHANGE_PASSWORD = ValueConstant('') ODOO_CREATE = ValueConstant('') ODOO_EDIT = ValueConstant('') ODOO_DELETE = ValueConstant('') ODOO_CHANGE_PASSWORD = ValueConstant('') SAP_CREATE = ValueConstant('') SAP_EDIT = ValueConstant('') SAP_DELETE = ValueConstant('') SAP_CHANGE_PASSWORD = ValueConstant('') SFTP_CREATE = ValueConstant('') SFTP_EDIT = ValueConstant('') SFTP_DELETE = ValueConstant('') SFTP_CHANGE_PASSWORD = ValueConstant('') SFTP_EXECUTE = ValueConstant('') SFTP_PING = ValueConstant('') REST_WRAPPER_CHANGE_PASSWORD = ValueConstant('') class CHANNEL(Constants): code_start = 101000 AMQP_CREATE = ValueConstant('') AMQP_EDIT = ValueConstant('') AMQP_DELETE = ValueConstant('') AMQP_MESSAGE_RECEIVED = ValueConstant('') WMQ_CREATE = ValueConstant('') WMQ_EDIT = ValueConstant('') WMQ_DELETE = ValueConstant('') WMQ_MESSAGE_RECEIVED = ValueConstant('') ZMQ_CREATE = ValueConstant('') ZMQ_EDIT = ValueConstant('') ZMQ_DELETE = ValueConstant('') ZMQ_MESSAGE_RECEIVED = ValueConstant('') HTTP_SOAP_CREATE_EDIT = ValueConstant('') # Same for creating and updating HTTP_SOAP_DELETE = ValueConstant('') WEB_SOCKET_CREATE = ValueConstant('') WEB_SOCKET_EDIT = ValueConstant('') WEB_SOCKET_DELETE = ValueConstant('') WEB_SOCKET_BROADCAST = ValueConstant('') FTP_CREATE = ValueConstant('') FTP_EDIT = ValueConstant('') FTP_DELETE = ValueConstant('') FTP_PING = ValueConstant('') FTP_USER_CREATE = ValueConstant('') FTP_USER_EDIT = ValueConstant('') FTP_USER_DELETE = ValueConstant('') FTP_USER_CHANGE_PASSWORD = ValueConstant('') class AMQP_CONNECTOR(Constants): """ Since 3.0, this is not used anymore. """ code_start = 101200 CLOSE = ValueConstant('') class JMS_WMQ_CONNECTOR(Constants): """ Since 3.0, this is not used anymore. """ code_start = 101400 CLOSE = ValueConstant('') class ZMQ_CONNECTOR(Constants): """ Since 3.0, this is not used anymore. """ code_start = 101600 CLOSE = ValueConstant('') class SERVICE(Constants): code_start = 101800 EDIT = ValueConstant('') DELETE = ValueConstant('') PUBLISH = ValueConstant('') class STATS(Constants): code_start = 102000 DELETE = ValueConstant('') DELETE_DAY = ValueConstant('') class HOT_DEPLOY(Constants): code_start = 102200 CREATE_SERVICE = ValueConstant('') CREATE_STATIC = ValueConstant('') CREATE_USER_CONF = ValueConstant('') AFTER_DEPLOY = ValueConstant('') class SINGLETON(Constants): code_start = 102400 CLOSE = ValueConstant('') class MSG_NS(Constants): code_start = 102600 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') class MSG_XPATH(Constants): code_start = 102800 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') class MSG_JSON_POINTER(Constants): code_start = 103000 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') class PUB_SUB_TOPIC(Constants): code_start = 103200 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') ADD_DEFAULT_PRODUCER = ValueConstant('') DELETE_DEFAULT_PRODUCER = ValueConstant('') class PUB_SUB_PRODUCER(Constants): code_start = 103400 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') class PUB_SUB_CONSUMER(Constants): code_start = 103600 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') class CLOUD(Constants): code_start = 103800 AWS_S3_CREATE_EDIT = ValueConstant('') AWS_S3_DELETE = ValueConstant('') class NOTIF(Constants): code_start = 104000 RUN_NOTIFIER = ValueConstant('') SQL_CREATE = ValueConstant('') SQL_EDIT = ValueConstant('') SQL_DELETE = ValueConstant('') class SEARCH(Constants): code_start = 104200 CREATE = ValueConstant('') EDIT = ValueConstant('') DELETE = ValueConstant('') ES_CREATE = ValueConstant('') ES_EDIT = ValueConstant('') ES_DELETE = ValueConstant('') ES_CHANGE_PASSWORD = ValueConstant('') SOLR_CREATE = ValueConstant('') SOLR_EDIT = ValueConstant('') SOLR_DELETE = ValueConstant('') SOLR_CHANGE_PASSWORD = ValueConstant('') class QUERY(Constants): code_start = 104400 CASSANDRA_CREATE = ValueConstant('') CASSANDRA_EDIT = ValueConstant('') CASSANDRA_DELETE = ValueConstant('') CASSANDRA_CHANGE_PASSWORD = ValueConstant('') class EMAIL(Constants): code_start = 104800 SMTP_CREATE = ValueConstant('') SMTP_EDIT = ValueConstant('') SMTP_DELETE = ValueConstant('') SMTP_CHANGE_PASSWORD = ValueConstant('') IMAP_CREATE = ValueConstant('') IMAP_EDIT = ValueConstant('') IMAP_DELETE = ValueConstant('') IMAP_CHANGE_PASSWORD = ValueConstant('') class RBAC(Constants): code_start = 105200 ROLE_CREATE = ValueConstant('') ROLE_EDIT = ValueConstant('') ROLE_DELETE = ValueConstant('') CLIENT_ROLE_CREATE = ValueConstant('') CLIENT_ROLE_DELETE = ValueConstant('') PERMISSION_CREATE = ValueConstant('') PERMISSION_EDIT = ValueConstant('') PERMISSION_DELETE = ValueConstant('') ROLE_PERMISSION_CREATE = ValueConstant('') ROLE_PERMISSION_EDIT = ValueConstant('') ROLE_PERMISSION_DELETE = ValueConstant('') class VAULT(Constants): code_start = 105400 CONNECTION_CREATE = ValueConstant('') CONNECTION_EDIT = ValueConstant('') CONNECTION_DELETE = ValueConstant('') POLICY_CREATE = ValueConstant('') POLICY_EDIT = ValueConstant('') POLICY_DELETE = ValueConstant('') class PUBSUB(Constants): code_start = 105600 ENDPOINT_CREATE = ValueConstant('') ENDPOINT_EDIT = ValueConstant('') ENDPOINT_DELETE = ValueConstant('') SUBSCRIPTION_CREATE = ValueConstant('') SUBSCRIPTION_EDIT = ValueConstant('') SUBSCRIPTION_DELETE = ValueConstant('') TOPIC_CREATE = ValueConstant('') TOPIC_EDIT = ValueConstant('') TOPIC_DELETE = ValueConstant('') SUB_KEY_SERVER_SET = ValueConstant('') # This is shared by WSX and other endpoint types WSX_CLIENT_SUB_KEY_SERVER_REMOVE = ValueConstant('') DELIVERY_SERVER_CHANGE = ValueConstant('') QUEUE_CLEAR = ValueConstant('') class SMS(Constants): code_start = 106000 TWILIO_CREATE = ValueConstant('') TWILIO_EDIT = ValueConstant('') TWILIO_DELETE = ValueConstant('') class CACHE(Constants): code_start = 106400 BUILTIN_CREATE = ValueConstant('') BUILTIN_EDIT = ValueConstant('') BUILTIN_DELETE = ValueConstant('') BUILTIN_STATE_CHANGED_CLEAR = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_BY_PREFIX = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_BY_SUFFIX = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_BY_REGEX = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_NOT_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_CONTAINS_ALL = ValueConstant('') BUILTIN_STATE_CHANGED_DELETE_CONTAINS_ANY = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_BY_PREFIX = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_BY_SUFFIX = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_BY_REGEX = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_NOT_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_CONTAINS_ALL = ValueConstant('') BUILTIN_STATE_CHANGED_EXPIRE_CONTAINS_ANY = ValueConstant('') BUILTIN_STATE_CHANGED_SET = ValueConstant('') BUILTIN_STATE_CHANGED_SET_BY_PREFIX = ValueConstant('') BUILTIN_STATE_CHANGED_SET_BY_SUFFIX = ValueConstant('') BUILTIN_STATE_CHANGED_SET_BY_REGEX = ValueConstant('') BUILTIN_STATE_CHANGED_SET_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_SET_NOT_CONTAINS = ValueConstant('') BUILTIN_STATE_CHANGED_SET_CONTAINS_ALL = ValueConstant('') BUILTIN_STATE_CHANGED_SET_CONTAINS_ANY = ValueConstant('') MEMCACHED_CREATE = ValueConstant('') MEMCACHED_EDIT = ValueConstant('') MEMCACHED_DELETE = ValueConstant('') class GENERIC(Constants): code_start = 107000 CONNECTION_CREATE = ValueConstant('') CONNECTION_EDIT = ValueConstant('') CONNECTION_DELETE = ValueConstant('') CONNECTION_CHANGE_PASSWORD = ValueConstant('') class SSO(Constants): code_start = 107200 USER_CREATE = ValueConstant('') USER_EDIT = ValueConstant('') LINK_AUTH_CREATE = ValueConstant('') LINK_AUTH_DELETE = ValueConstant('') class EVENT(Constants): code_start = 107400 PUSH = ValueConstant('') class SERVER_IPC(Constants): code_start = 107600 INVOKE = ValueConstant('') class Common(Constants): code_start = 107800 Sync_Objects = ValueConstant('') class Groups(Constants): code_start = 108000 Edit = ValueConstant('') Edit_Member_List = ValueConstant('') Delete = ValueConstant('') code_to_name = {} # To prevent 'RuntimeError: dictionary changed size during iteration' item_name, item = None, None _globals = list(iteritems(globals())) for item_name, item in _globals: if isclass(item) and issubclass(item, Constants) and item is not Constants: for idx, (attr, const) in enumerate(item.items()): const.value = str(item.code_start + idx) code_to_name[const.value] = '{}_{}'.format(item_name, attr)
15,547
Python
.py
402
33.885572
95
0.69197
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,553
facade.py
zatosource_zato/code/zato-common/src/zato/common/facade.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import anydict, anydictnone from zato.server.base.parallel import ParallelServer # ################################################################################################################################ # ################################################################################################################################ class SecurityFacade: def __init__(self, server:'ParallelServer') -> 'None': self.server = server def get_bearer_token_by_name(self, key:'str') -> 'anydict': item:'anydictnone' = self.server.worker_store.request_dispatcher.url_data.oauth_config.get(key) if item: return item['config'] else: raise KeyError(f'Security definition not found by key (1) -> {key}') def get_bearer_token_by_id(self, id:'int') -> 'anydict': for value in self.server.worker_store.request_dispatcher.url_data.oauth_config.values(): if value['config']['id'] == id: return value['config'] else: raise KeyError(f'Security definition not found ID -> {id}') # ################################################################################################################################ # ################################################################################################################################
1,820
Python
.py
29
56.827586
130
0.363483
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,554
wsx_client.py
zatosource_zato/code/zato-common/src/zato/common/wsx_client.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # First thing in the process from gevent import monkey _ = monkey.patch_all() # stdlib import os import random from dataclasses import dataclass from datetime import datetime, timedelta from http.client import OK from json import dumps as json_dumps from logging import getLogger from traceback import format_exc # gevent from gevent import sleep, spawn # ws4py from zato.server.ext.ws4py.client.geventclient import WebSocketClient # Zato from zato.common.api import WEB_SOCKET from zato.common.marshal_.api import MarshalAPI, Model from zato.common.typing_ import cast_ from zato.common.util.json_ import JSONParser try: from OpenSSL.SSL import Error as PyOpenSSLError _ = PyOpenSSLError except ImportError: class PyOpenSSLError(Exception): pass # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, callable_, callnone, strnone from zato.server.base.parallel import ParallelServer from zato.server.ext.ws4py.messaging import TextMessage # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ def new_cid(bytes:'int'=12, _random:'callable_'=random.getrandbits) -> 'str': # Copied over from zato.common.util.api return hex(_random(bytes * 8))[2:] # ################################################################################################################################ # ################################################################################################################################ class MsgPrefix: _Common = 'zwsxc.{}' InvokeService = _Common.format('inv.{}') SendAuth = _Common.format('auth.{}') SendResponse = _Common.format('rsp.{}') # ################################################################################################################################ # ################################################################################################################################ zato_keep_alive_ping = 'zato-keep-alive-ping' _invalid = '_invalid.' + new_cid() utcnow = datetime.utcnow _ping_interval = WEB_SOCKET.DEFAULT.PING_INTERVAL _ping_missed_threshold = WEB_SOCKET.DEFAULT.PING_INTERVAL # This is how long we wait for responses - longer than the ping interval is wsx_socket_timeout = _ping_interval + (_ping_interval * 0.1) # ################################################################################################################################ # ################################################################################################################################ class Default: ResponseWaitTime = cast_('int', os.environ.get('Zato_WSX_Response_Wait_Time')) or 5 # How many seconds to wait for responses MaxConnectAttempts = 1234567890 MaxWaitTime = 999_999_999 # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class Config: address: 'str' client_id: 'str' client_name: 'str' on_request_callback: 'callable_' username:'strnone' = None secret:'strnone' = None on_closed_callback: 'callnone' = None wait_time:'int' = Default.ResponseWaitTime max_connect_attempts:'int' = Default.MaxConnectAttempts socket_read_timeout:'int' = WEB_SOCKET.DEFAULT.Socket_Read_Timeout socket_write_timeout:'int' = WEB_SOCKET.DEFAULT.Socket_Write_Timeout # This is a method that will tell the client whether its parent connection definition is still active. check_is_active_func: 'callable_' # This is a callback that the WSX client invokes to notify the server that the WSX connection stopped running. on_outconn_stopped_running_func: 'callable_' # This is a callback that the WSX client invokes to notify the server that the WSX connection connected to a remote end. on_outconn_connected_func: 'callable_' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class ClientMeta(Model): id: 'str' action: 'str' attrs: 'strnone' = None timestamp: 'str' client_id: 'str' client_name: 'str' token: 'strnone' username: 'strnone' = None secret: 'strnone' = None in_reply_to: 'strnone' = None # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class ClientToServerModel(Model): meta: 'ClientMeta' data: 'anydict' # ################################################################################################################################ # ################################################################################################################################ class ClientToServerMessage: """ An individual message from a WebSocket client to Zato, either request or response to a previous request from Zato. """ action = _invalid def __init__(self, msg_id:'str', config:'Config', token:'strnone'=None) -> 'None': self.config = config self.msg_id = msg_id self.token = token def serialize(self) -> 'str': # Base metadata that we can always produce # and subclasses can always write to, if needed. meta = ClientMeta() meta.action = self.action meta.id = self.msg_id meta.timestamp = utcnow().isoformat() meta.token = self.token meta.client_id = self.config.client_id meta.client_name = self.config.client_name # We can build an empty request that subclasses will fill out with actual data request = ClientToServerModel() request.meta = meta request.data = {} # Each subclass can enrich the message with is own specific information enriched = self.enrich(request) # Now, we are ready to serialize the message .. serialized = json_dumps(enriched.to_dict()) # .. and to finally return it return serialized def enrich(self, msg:'ClientToServerModel') -> 'ClientToServerModel': """ Implemented by subclasses that need to add extra information. """ return msg # ################################################################################################################################ # ################################################################################################################################ class AuthRequest(ClientToServerMessage): """ Logs a client into a WebSocket connection. """ action = 'create-session' def enrich(self, msg:'ClientToServerModel') -> 'ClientToServerModel': msg.meta.username = self.config.username msg.meta.secret = self.config.secret # Client attributes can be optionally provided via environment variables if client_attrs := os.environ.get('Zato_WSX_Client_Attrs'): msg.meta.attrs = client_attrs return msg # ################################################################################################################################ # ################################################################################################################################ class ServiceInvocationRequest(ClientToServerMessage): """ Encapsulates information about an invocation of a Zato service. """ action = 'invoke-service' def __init__(self, request_id:'str', data:'any_', *args:'any_', **kwargs:'any_') -> 'None': self.data = data super(ServiceInvocationRequest, self).__init__(request_id, *args, **kwargs) def enrich(self, msg:'ClientToServerModel') -> 'ClientToServerModel': msg.data.update(self.data) return msg # ################################################################################################################################ # ################################################################################################################################ class ResponseToServer(ClientToServerMessage): """ A response from this client to a previous request from Zato. """ action = 'client-response' def __init__(self, in_reply_to:'str', data:'any_', *args:'any_', **kwargs:'any_') -> 'None': self.in_reply_to = in_reply_to self.data = data super(ResponseToServer, self).__init__(*args, **kwargs) def enrich(self, msg:'ClientToServerModel') -> 'ClientToServerModel': msg.meta.in_reply_to = self.in_reply_to msg.data['response'] = self.data return msg # ################################################################################################################################ # ################################################################################################################################ class MessageFromServer: """ A message from server, either a server-initiated request or a response to our own previous request. """ id: 'str' timestamp: 'str' data: 'any_' msg_impl: 'any_' def __getitem__(self, key:'str') -> 'None': raise NotImplementedError() @staticmethod def from_json(msg:'anydict') -> 'MessageFromServer': raise NotImplementedError('Must be implemented in subclasses') # ################################################################################################################################ def to_dict(self): return {'id':self.id, 'timestamp':self.timestamp, 'data':self.data} # ################################################################################################################################ # ################################################################################################################################ class ResponseFromServer(MessageFromServer): """ A response from Zato to a previous request by this client. """ in_reply_to: 'strnone' status: 'str' is_ok: 'bool' @staticmethod def from_json(msg:'anydict') -> 'ResponseFromServer': response = ResponseFromServer() response.msg_impl = msg meta = msg['meta'] response.id = meta['id'] response.timestamp = meta['timestamp'] response.in_reply_to = meta['in_reply_to'] response.status = meta['status'] response.is_ok = response.status == OK response.data = msg.get('data') return response # ################################################################################################################################ # ################################################################################################################################ class RequestFromServer(MessageFromServer): """ A request from Zato to this client. """ @staticmethod def from_json(msg:'anydict') -> 'RequestFromServer': request = RequestFromServer() request.msg_impl = msg request.id = msg['meta']['id'] request.timestamp = msg['meta']['timestamp'] request.data = msg.get('data') return request # ################################################################################################################################ # ################################################################################################################################ class _WebSocketClientImpl(WebSocketClient): """ A low-level subclass of ws4py's WebSocket client functionality. """ def __init__( self, server:'ParallelServer', config:'Config', on_connected_callback:'callable_', on_message_callback:'callable_', on_error_callback:'callable_', on_closed_callback:'callable_' ) -> 'None': # Assign our own pieces of configuration .. self.config = config self.on_connected_callback = on_connected_callback self.on_message_callback = on_message_callback self.on_error_callback = on_error_callback self.on_closed_callback = on_closed_callback # .. call the parent .. super(_WebSocketClientImpl, self).__init__( server, url=self.config.address, socket_read_timeout=self.config.socket_read_timeout, socket_write_timeout=self.config.socket_write_timeout, ) # ################################################################################################################################ def opened(self) -> 'None': _ = spawn(self.on_connected_callback) # ################################################################################################################################ def received_message(self, msg:'anydict') -> 'None': self.on_message_callback(msg) # ################################################################################################################################ def unhandled_error(self, error:'any_') -> 'None': _ = spawn(self.on_error_callback, error) # ################################################################################################################################ def closed(self, code:'int', reason:'strnone'=None) -> 'None': super(_WebSocketClientImpl, self).closed(code, reason) self.on_closed_callback(code, reason) # ################################################################################################################################ # ################################################################################################################################ class Client: """ A WebSocket client that knows how to invoke Zato services. """ max_connect_attempts: 'int' conn: '_WebSocketClientImpl' def __init__(self, server:'ParallelServer', config:'Config') -> 'None': self.server = server self.config = config self.conn = self.create_conn(self.server, self.config) self.keep_running = True self.is_authenticated = False self.is_connected = False self.is_auth_needed = bool(self.config.username) self.auth_token = '' self.on_request_callback = self.config.on_request_callback self.on_closed_callback = self.config.on_closed_callback self.needs_auth = bool(self.config.username) self.max_connect_attempts = self.config.max_connect_attempts self._marshal_api = MarshalAPI() self.logger = getLogger('zato_web_socket') # Keyed by IDs of requests sent from this client to Zato self.requests_sent = {} # Same key as self.requests_sent but the dictionary contains responses to previously sent requests self.responses_received = {} # Requests initiated by Zato, keyed by their IDs self.requests_received = {} # Log information that we are about to become available self.logger.info('Starting WSX client: %s -> name:`%s`; id:`%s`; u:`%s`', self.config.address, self.config.client_name, self.config.client_id, self.config.username) def create_conn(self, server:'ParallelServer', config:'Config') -> '_WebSocketClientImpl': conn = _WebSocketClientImpl( server, config, self.on_connected, self.on_message, self.on_error, self.on_closed, ) return conn # ################################################################################################################################ def send(self, msg_id:'str', msg:'ClientToServerMessage', wait_time:'int'=2) -> 'None': """ Spawns a greenlet to send a message to Zato. """ _ = spawn(self._send, msg_id, msg, msg.serialize(), wait_time) # ################################################################################################################################ def _send(self, msg_id:'str', msg:'anydict', serialized:'str', wait_time:'int') -> 'None': """ Sends a request to Zato and waits up to wait_time or self.config.wait_time seconds for a reply. """ self.logger.info('Sending msg `%s`', serialized) # So that it can be correlated with a future response self.requests_sent[msg_id] = msg # Actually send the message as string now self.conn.send(serialized) # ################################################################################################################################ def _wait_for_response( self, request_id:'str', wait_time:'int'=Default.ResponseWaitTime, ) -> 'any_': """ Wait until a response arrives and return it or return None if there is no response up to wait_time or self.config.wait_time. """ now = utcnow() until = now + timedelta(seconds=wait_time or self.config.wait_time) while now < until: response = self.responses_received.get(request_id) # type: any_ if response: return response else: sleep(0.01) now = utcnow() # ################################################################################################################################ def authenticate(self, request_id:'str') -> 'None': """ Authenticates the client with Zato. """ self.logger.info('Authenticating as `%s` (%s %s)', self.config.username, self.config.client_name, self.config.client_id) _ = spawn(self.send, request_id, AuthRequest(request_id, self.config, self.auth_token)) # ################################################################################################################################ def on_connected(self) -> 'None': """ Invoked upon establishing an initial connection - logs the client in with self.config's credentials """ self.logger.info('Connected to `%s` %s (%s %s)', self.config.address, 'as `{}`'.format(self.config.username) if self.config.username else 'without credentials', self.config.client_name, self.config.client_id) request_id = MsgPrefix.SendAuth.format(new_cid()) self.authenticate(request_id) response = self._wait_for_response(request_id) if not response: self.logger.warning('No response to authentication request `%s`; (%s %s -> %s)', request_id, self.config.username, self.config.client_name, self.config.client_id) self.keep_running = False else: self.auth_token = response.data['token'] self.is_authenticated = True del self.responses_received[request_id] self.logger.info('Authenticated successfully as `%s` (%s %s)', self.config.username, self.config.client_name, self.config.client_id) # ################################################################################################################################ def _on_message(self, msg:'TextMessage') -> 'None': """ Invoked for each message received from Zato, both for responses to previous requests and for incoming requests. """ _msg = JSONParser().parse(msg.data) # type: anydict self.logger.info('Received message `%s`', _msg) meta = _msg.get('meta') if not meta: logger.warn('Element \'meta \'missing in message -> %r', msg.data) return in_reply_to = meta.get('in_reply_to') # Reply from Zato to one of our requests if in_reply_to: self.responses_received[in_reply_to] = ResponseFromServer.from_json(_msg) # Request from Zato else: request = RequestFromServer.from_json(_msg) data = self.on_request_callback(request) response_id = MsgPrefix.SendResponse.format(new_cid()) response = ResponseToServer(_msg['meta']['id'], data, response_id, self.config, self.auth_token) self.send(response_id, response) # ################################################################################################################################ def on_message(self, msg:'TextMessage') -> 'None': try: return self._on_message(msg) except Exception: self.logger.info('Exception in on_message -> %s', format_exc()) # ################################################################################################################################ def on_closed(self, code:'int', reason:'strnone'=None) -> 'None': self.logger.info('Closed WSX client connection to `%s` (remote code:%s reason:%s)', self.config.address, code, reason) if self.on_closed_callback: self.on_closed_callback(code, reason) # ################################################################################################################################ def on_error(self, error:'any_') -> 'None': """ Invoked for each unhandled error in the lower-level ws4py library. """ self.logger.info('Caught error `%s`', error) # ################################################################################################################################ def _run(self, max_wait:'int'=10, _sleep_time:'int'=2) -> 'None': """ Attempts to connects to a remote WSX server or raises an exception if max_wait time is exceeded. """ # We are just starting out num_connect_attempts = 0 needs_connect = True start = now = datetime.utcnow() # Initially, do not warn about socket errors in case # the other end is intrinsically slow to connect to. warn_from = start + timedelta(hours=24) use_warn = False # Wait for max_wait seconds until we have the connection until = now + timedelta(seconds=max_wait) while self.keep_running and needs_connect and now < until: # Check whether our connection definition is still active .. is_active = self.config.check_is_active_func() # .. if it is not, we can break out of the loop. if not is_active: # Log what we are doing .. self.logger.info('Skipped building an inactive WSX connection -> %s', self.config.client_name) # .. indicate that we are stopping .. self.keep_running = False # .. invoke a callback to notify any interested party in the fact that we are not running anymore .. self.config.on_outconn_stopped_running_func() # .. and break out of the loop. break # Check if we have already run out of attempts. if num_connect_attempts >= self.max_connect_attempts: self.logger.warning('Max. connect attempts reached, quitting; %s/%s -> %s (%s)', num_connect_attempts, self.max_connect_attempts, self.config.address, now - start) # .. and quit if we have reached the limit. break # If we are here, it means that we have not reached the limit yet # so we can increase the counter as the first thing .. num_connect_attempts += 1 try: # The underlying TCP socket may have been deleted .. if not self.conn.sock: # .. and we need to recreate it . self.conn = self.create_conn(self.server, self.config) # If we are here, it means that we likely have a TCP socket to use .. try: self.conn.connect() # .. however, we still need to catch the broken pipe error # .. and, in such a case, forcibly close the connection # .. to let it be opened in the next iteration of this loop. except BrokenPipeError: self.conn.close_connection() raise except Exception: if use_warn: log_func = self.logger.warning else: if now >= warn_from: log_func = self.logger.warning use_warn = True else: log_func = self.logger.info log_func('Exception caught in iter %s/%s `%s` while connecting to WSX `%s (%s)`', num_connect_attempts, self.max_connect_attempts, format_exc(), self.config.address, self.conn.sock, ) # .. this is needed to ensure that the next attempt will not reuse the current TCP socket .. # .. which, under Windows, would make it impossible to establish the connection .. # .. even if the remote endpoint existed. I.e. this would result in the error below: # .. [Errno 10061] [WinError 10061] No connection could be made because the target machine actively refused it. self.conn.close_connection() # .. now, we can sleep a bit .. sleep(_sleep_time) now = utcnow() else: needs_connect = False self.is_connected = True # .. invoke a callback to notify any interested party in the fact that we are not running anymore .. self.config.on_outconn_connected_func() # ################################################################################################################################ def _wait_until_flag_is_true(self, get_flag_func:'callable_', max_wait:'int'=Default.MaxWaitTime) -> 'bool': # .. wait for the connection for that much time .. now = utcnow() until = now + timedelta(seconds=max_wait) # .. wait and return if max. wait time is exceeded .. while not get_flag_func(): sleep(0.1) now = utcnow() if now >= until: return True # If we are here, it means that we did not exceed the max_wait time return False # ################################################################################################################################ def run(self, max_wait:'int'=Default.MaxWaitTime) -> 'None': # Actually try to connect .. self._run(max_wait) def get_flag_func(): return self.is_connected # .. wait and potentially return if max. wait time is exceeded .. has_exceeded = self._wait_until_flag_is_true(get_flag_func) if has_exceeded: return # .. otherwise, if we are here, it means that we are connected, # .. although we may be still not authenticated as the authentication step # .. is carried out by the on_connected_callback method. pass # ################################################################################################################################ def wait_until_authenticated(self, max_wait:'int'=Default.MaxWaitTime) -> 'bool': def get_flag_func(): return self.is_authenticated # Wait until we are authenticated or until the max. wait_time is exceeded _ = self._wait_until_flag_is_true(get_flag_func) # Return the flag to the caller for it to decide what to do next return self.is_authenticated # ################################################################################################################################ def stop(self, reason:'str'='') -> 'None': self.keep_running = False self.conn.close_connection() self.is_connected = False # ################################################################################################################################ def invoke(self, data:'any_', timeout:'int'=Default.ResponseWaitTime) -> 'any_': if self.needs_auth and (not self.is_authenticated): raise Exception('Client is not authenticated') request_id = MsgPrefix.InvokeService.format(new_cid()) _ = spawn(self.send, request_id, ServiceInvocationRequest(request_id, data, self.config, self.auth_token)) response = self._wait_for_response(request_id, wait_time=timeout) if not response: self.logger.warning('No response to invocation request `%s`', request_id) else: return response # ################################################################################################################################ def invoke_service(self, service_name:'str', request:'any_', timeout:'int'=Default.ResponseWaitTime) -> 'any_': return self.invoke({ 'service':service_name, 'request': request }, timeout=timeout) # ################################################################################################################################ def subscribe(self, topic_name:'str') -> 'None': service_name = 'zato.pubsub.subscription.create-wsx-subscription' request = { 'topic_name': topic_name } return self.invoke_service(service_name, request) # ################################################################################################################################ def publish( self, topic_name, # type: str data # type: any_ ) -> 'None': service_name = 'zato.pubsub.pubapi.publish-message' response = self.invoke_service(service_name, { 'topic_name': topic_name, 'data':data }) response # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': # First thing in the process from gevent import monkey _ = monkey.patch_all() # stdlib import logging import sys log_format = '%(asctime)s - %(levelname)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=logging.INFO, format=log_format) _cli_logger = logging.getLogger('zato') def on_request_from_zato(msg:'RequestFromServer') -> 'any_': try: _cli_logger.info('*' * 80) _cli_logger.debug('Message from Zato received -> %s', msg.to_dict()) return [elem['data'] for elem in msg.data] except Exception: return format_exc() def check_is_active_func(): return True address = 'ws://127.0.0.1:47043/zato.wsx.apitests' client_id = '123456' client_name = 'My Client' on_request_callback = on_request_from_zato # Test topic to use topic_name1 = '/zato/demo/sample' config = Config() config.address = address config.client_id = client_id config.client_name = client_name config.on_request_callback = on_request_callback config.check_is_active_func = check_is_active_func config.username = 'user1' config.secret = 'secret1' # Create a client .. client = Client(config) # .. start it .. client.run() # .. wait until it is authenticated .. _ = client.wait_until_authenticated() # .. and run sample code now .. is_subscriber = 'sub' in sys.argv if is_subscriber: client.subscribe(topic_name1) else: idx = 0 while idx < 100_000_000: idx += 1 client.invoke({'service':'zato.ping'}) client.publish(topic_name1, f'{idx}') # sleep(1) _cli_logger.info('Press Ctrl-C to quit') try: x = 0 while x < 100_000_000 and client.keep_running: sleep(0.2) except KeyboardInterrupt: client.stop() # ################################################################################################################################ # ################################################################################################################################
33,576
Python
.py
628
45.291401
130
0.468898
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,555
version.py
zatosource_zato/code/zato-common/src/zato/common/version.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ def get_sys_info(): import platform system = platform.system() is_linux = 'linux' in system.lower() is_windows = 'windows' in system.lower() is_mac = 'darwin' in system.lower() if is_linux: try: import distro info = distro.info() codename = info['codename'].lower() codename = codename.replace('/', '') out = '{}.{}'.format(info['id'], info['version']) if codename: out += '-{}'.format(codename) except ImportError: out = 'linux' elif is_windows: _platform = platform.platform().lower() _edition = platform.win32_edition() out = '{}-{}'.format(_platform, _edition) elif is_mac: out = platform.platform().lower() return out else: out = 'os.unrecognised' return out # ################################################################################################################################ # ################################################################################################################################ def get_version(): # stdlib import os import sys from sys import version_info as py_version_info # Python 2/3 compatibility from zato.common.py23_.past.builtins import execfile # Default version if not set below version = '3.2' try: # Make sure the underlying git command runs in our git repository .. code_dir = os.path.dirname(sys.executable) os.chdir(code_dir) curdir = os.path.dirname(os.path.abspath(__file__)) _version_py = os.path.normpath(os.path.join(curdir, '..', '..', '..', '..', '.version.py')) _locals = {} execfile(_version_py, _locals) version = 'Zato {}'.format(_locals['version']) finally: sys_info = get_sys_info() version = '{}-py{}.{}.{}-{}'.format( version, py_version_info.major, py_version_info.minor, py_version_info.micro, sys_info) return version # ################################################################################################################################ # ################################################################################################################################
2,790
Python
.py
65
35.553846
130
0.406447
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,556
audit.py
zatosource_zato/code/zato-common/src/zato/common/audit.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import logging # ipaddress from ipaddress import IPv4Address, IPv6Address # Zato from zato.common.json_internal import dumps # ################################################################################################################################ logger = logging.getLogger(__name__) # ################################################################################################################################ class AuditPII: """ Audit log for personally identifiable information (PII). """ def __init__(self): self._logger = logging.getLogger('zato_audit_pii') # ################################################################################################################################ def _log(self, func, cid, op, current_user='', target_user='', result='', extra='', _dumps=dumps): remote_addr = extra.get('remote_addr') if isinstance(extra, dict): if not remote_addr: extra['remote_addr'] = '' else: if isinstance(remote_addr, list) and remote_addr: if isinstance(remote_addr[0], (IPv4Address, IPv6Address)): extra['remote_addr'] = ';'.join(elem.exploded for elem in extra['remote_addr']) entry = { 'cid': cid, 'op': op, } if current_user: entry['current_user'] = current_user if target_user: entry['target_user'] = target_user if result: entry['result'] = result if extra: entry['extra'] = extra entry = dumps(entry) self._logger.info('%s' % entry) # ################################################################################################################################ def info(self, *args, **kwargs): self._log(self._logger.info, *args, **kwargs) # ################################################################################################################################ def warn(self, *args, **kwargs): self._log(self._logger.warning, *args, **kwargs) # ################################################################################################################################ def error(self, *args, **kwargs): self._log(self._logger.error, *args, **kwargs) # ################################################################################################################################ # A singleton available everywhere audit_pii = AuditPII() # ################################################################################################################################
2,916
Python
.py
57
44.157895
130
0.379993
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,557
ipaddress_.py
zatosource_zato/code/zato-common/src/zato/common/ipaddress_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import itertools # ipaddress from ipaddress import ip_address, ip_network # netifaces from netifaces import AF_INET, ifaddresses as net_ifaddresses, interfaces as net_ifaces # Python 2/3 compatibility from builtins import bytes from zato.common.ext.future.moves.urllib.parse import urlparse from six import PY2 # ################################################################################################################################ def to_ip_network(adddress): """ Converts address to a network object assuming it is feasible at all, otherwise returns None. """ try: return ip_network(adddress) except ValueError: pass else: return True # ################################################################################################################################ def ip_list_from_interface(interface, allow_loopback=False): """ Return the list of IP address for the given interface, possibly including loopback addresses """ addresses = [] af_inet = net_ifaddresses(interface).get(AF_INET) if af_inet: _addresses = [elem.get('addr') for elem in af_inet] if PY2: _addresses = [elem.decode('utf8') for elem in _addresses] for address in _addresses: address = ip_address(address) if address.is_loopback and not allow_loopback: continue addresses.append(address) return addresses # ################################################################################################################################ def get_preferred_ip(base_bind, user_prefs) -> 'str': """ Given user preferences, iterate over all address in all interfaces and check if any matches what users prefer. Note that preferences can include actual names of interfaces, not only IP or IP ranges. """ # First check out if the base address to bind does not already specify a concrete IP. # If it does, then this will be the preferred one. parsed = urlparse('https://{}'.format(base_bind)) if parsed.hostname != '0.0.0.0': return parsed.hostname # What is preferred preferred = user_prefs.ip # What actually exists in the system current_ifaces = net_ifaces() # Would be very weird not to have anything, even loopback, but oh well if not current_ifaces: return None current_ifaces.sort() current_addresses = [net_ifaddresses(elem).get(AF_INET) for elem in current_ifaces] current_addresses = [[elem.get('addr') for elem in x] for x in current_addresses if x] current_addresses = list(itertools.chain.from_iterable(current_addresses)) # Preferences broken out into interfacs and network ranges/IP addresses pref_interfaces = [elem for elem in preferred if elem in net_ifaces()] pref_networks = [to_ip_network(elem) for elem in preferred] pref_networks = [elem for elem in pref_networks if elem] # If users prefer a named interface and we have it then we need to return its IP for elem in pref_interfaces: # If any named interface is found, returns its first IP, if there is any ip_list = ip_list_from_interface(elem, user_prefs.allow_loopback) if ip_list: return str(ip_list[0]) # No address has been found by its interface but perhaps one has been specified explicitly # or through a network range. for current in current_addresses: for preferred in pref_networks: if ip_address(current.decode('utf8') if isinstance(current, bytes) else current) in preferred: return current # Ok, still nothing, so we need to find something ourselves loopback_ip = '' # First let's try the first non-loopback interface. for elem in current_ifaces: for ip in ip_list_from_interface(elem, True): if ip.is_loopback: loopback_ip = ip return str(ip) # If there is only loopback and we are allowed to use it then so be it if user_prefs.allow_loopback: return loopback_ip # ################################################################################################################################
4,379
Python
.py
90
42.555556
130
0.609676
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,558
pubsub.py
zatosource_zato/code/zato-common/src/zato/common/pubsub.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import getLogger # ujson from json import dumps # Zato from zato.common.api import GENERIC, PUBSUB from zato.common.odb.model import PubSubSubscription from zato.common.odb.query.pubsub.subscription import pubsub_sub_key_list from zato.common.typing_ import cast_ from zato.common.util.api import new_cid from zato.common.util.time_ import utcnow_as_ms # ################################################################################################################################ # ################################################################################################################################ if 0: from sqlalchemy import Column from sqlalchemy.orm.session import Session as SQLSession from zato.common.typing_ import any_, anylist, anytuple, callable_, commondict, optional, stranydict, \ strlist, strlistempty, strnone, strorfloat, strtuple, tupnone from zato.server.connection.http_soap.outgoing import SudsSOAPWrapper from zato.server.pubsub.model import Topic Column = Column # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato_pubsub.msg') logger_zato = getLogger('zato') # ################################################################################################################################ # ################################################################################################################################ class MSG_PREFIX: GROUP_ID = 'zpsg' MSG_ID = 'zpsm' SUB_KEY = 'zpsk' SERVICE_SK = 'zpsk.srv' prefix_group_id = MSG_PREFIX.GROUP_ID prefix_msg_id = MSG_PREFIX.MSG_ID prefix_sk = MSG_PREFIX.SUB_KEY # ################################################################################################################################ # ################################################################################################################################ sk_lists = ('reply_to_sk', 'deliver_to_sk') # ################################################################################################################################ skip_to_external = ( 'delivery_status', 'topic_id', 'cluster_id', 'pub_pattern_matched', 'sub_pattern_matched', 'published_by_id', 'data_prefix', 'data_prefix_short', 'pub_time', 'expiration_time', 'recv_time', 'pub_msg_id', 'pub_correl_id', 'zato_ctx', 'is_in_sub_queue', 'has_gd', 'server_name', 'server_pid' ) + sk_lists # ################################################################################################################################ _data_keys = ( 'data', 'data_prefix', 'data_prefix_short' ) # ################################################################################################################################ msg_pub_attrs = ( 'topic', 'sub_key', 'pub_msg_id', 'pub_correl_id', 'in_reply_to', 'ext_client_id', 'group_id', 'position_in_group', 'pub_time', 'ext_pub_time', 'data', 'data_prefix', 'data_prefix_short', 'mime_type', 'priority', 'expiration', 'expiration_time', 'has_gd', 'delivery_status', 'size', 'published_by_id', 'topic_id', 'is_in_sub_queue', 'topic_name', 'cluster_id', 'pub_time_iso', 'ext_pub_time_iso', 'expiration_time_iso', 'recv_time', 'recv_time_iso', 'data_prefix_short', 'server_name', 'server_pid', 'pub_pattern_matched', 'sub_pattern_matched', 'delivery_count', 'user_ctx', 'zato_ctx' ) # ################################################################################################################################ # These public attributes need to be ignored when the message is published msg_pub_ignore = ( 'delivery_count', 'deliver_to_sk', 'delivery_status', 'recv_time', 'recv_time_iso', 'reply_to_sk', 'expiration_time_iso', 'ext_pub_time_iso', 'pub_time_iso', 'server_name', 'sub_key', 'server_pid', ) # ################################################################################################################################ def new_msg_id(_new_cid:'callable_'=new_cid, _prefix:'str'=prefix_msg_id) -> 'str': return '%s%s' % (_prefix, _new_cid()) # ################################################################################################################################ def new_sub_key( endpoint_type, # type: str ext_client_id='', # type: str _new_cid=new_cid, # type: callable_ _prefix=prefix_sk # type: str ) -> 'str': _ext_client_id = '.%s' % (ext_client_id,) if ext_client_id else (ext_client_id or '') return '%s.%s%s.%s' % (_prefix, endpoint_type, _ext_client_id, _new_cid(3)) # ################################################################################################################################ def new_group_id(_new_cid:'callable_'=new_cid, _prefix:'str'=prefix_group_id) -> 'str': return '%s%s' % (_prefix, _new_cid()) # ################################################################################################################################ # ################################################################################################################################ class PubSubMessage: """ Base container class for pub/sub message wrappers. """ # We are not using __slots__ because they can't be inherited by subclasses # and this class, as well as its subclasses, will be rewritten in Cython anyway. pub_attrs = msg_pub_attrs + sk_lists recv_time: 'float' recv_time_iso: 'str' server_name: 'str' server_pid: 'int' topic: 'optional[Topic]' sub_key: 'str' pub_msg_id: 'str' pub_correl_id: 'strnone' in_reply_to: 'strnone' ext_client_id: 'str' group_id: 'strnone' position_in_group: 'int' pub_time: 'strorfloat' ext_pub_time: 'strorfloat | None' data: 'any_' data_prefix: 'str' data_prefix_short: 'str' mime_type: 'str' priority: 'int' expiration: 'int' expiration_time: 'float' has_gd: 'bool' delivery_status: 'str' pub_pattern_matched: 'str' sub_pattern_matched: 'stranydict' size: 'int' published_by_id: 'int' topic_id: 'int' is_in_sub_queue: 'bool' topic_name: 'str' cluster_id: 'int' delivery_count: 'int' pub_time_iso: 'str' ext_pub_time_iso: 'str' expiration_time_iso: 'str' reply_to_sk: 'strlistempty' deliver_to_sk: 'strlistempty' user_ctx: 'any_' zato_ctx: 'any_' serialized: 'any_' opaque1: 'any_' def __init__(self) -> 'None': self.recv_time = utcnow_as_ms() self.recv_time_iso = '' self.server_name = '' self.server_pid = 0 self.topic = None self.sub_key = '' self.pub_msg_id = '' self.pub_correl_id = '' self.in_reply_to = None self.ext_client_id = '' self.group_id = '' self.position_in_group = -1 self.pub_time = 0.0 self.ext_pub_time = 0.0 self.data = '' self.data_prefix = '' self.data_prefix_short = '' self.mime_type = '' self.priority = PUBSUB.PRIORITY.DEFAULT self.expiration = -1 self.expiration_time = 0.0 self.has_gd = False self.delivery_status = '' self.pub_pattern_matched = '' self.sub_pattern_matched = {} self.size = -1 self.published_by_id = 0 self.topic_id = 0 self.is_in_sub_queue = False self.topic_name = '' self.cluster_id = 0 self.delivery_count = 0 self.pub_time_iso = '' self.ext_pub_time_iso = '' self.expiration_time_iso = '' self.reply_to_sk = [] self.deliver_to_sk = [] self.user_ctx = None self.zato_ctx = {} self.serialized = None # May be set by hooks to provide an explicitly serialized output for this message setattr(self, GENERIC.ATTR_NAME, None) # To make this class look more like an SQLAlchemy one # ################################################################################################################################ def to_dict( self, skip=None, # type: tupnone needs_utf8_encode=False, # type: bool needs_utf8_decode=False, # type: bool add_id_attrs=False, # type: bool _data_keys=_data_keys # type: strtuple ) -> 'commondict': """ Returns a dict representation of self. """ _skip = skip or () # type: anytuple out = {} # type: stranydict for key in sorted(PubSubMessage.pub_attrs): if key != 'topic' and key not in _skip: value = getattr(self, key) if value is not None: if needs_utf8_encode: if key in _data_keys: value = value.encode('utf8') if isinstance(value, str) else value if needs_utf8_decode: if key in _data_keys: value = value.decode('utf8') if isinstance(value, bytes) else value out[key] = value if add_id_attrs: out['msg_id'] = self.pub_msg_id if self.pub_correl_id: out['correl_id'] = self.pub_correl_id # Append the generic opaque attribute to make the output look as though it was produced from an SQLAlchemy object # but do it only if there is any value, otherwise skip it. opaque_value = getattr(self, GENERIC.ATTR_NAME) if opaque_value: out[GENERIC.ATTR_NAME] = opaque_value return out # ################################################################################################################################ # For compatibility with code that already expects dictalchemy objects with their .asdict method def asdict(self) -> 'commondict': out = self.to_dict() out[GENERIC.ATTR_NAME] = getattr(self, GENERIC.ATTR_NAME) return out # ################################################################################################################################ def to_external_dict(self, skip:'strtuple'=skip_to_external, needs_utf8_encode:'bool'=False) -> 'commondict': """ Returns a dict representation of self ready to be delivered to external systems, i.e. without internal attributes on output. """ out = self.to_dict(skip, needs_utf8_encode=needs_utf8_encode, add_id_attrs=True) if self.reply_to_sk: out['ctx'] = { 'reply_to_sk': self.reply_to_sk } return out # ################################################################################################################################ def to_json(self, *args:'any_', **kwargs:'any_') -> 'str': data = self.to_dict(*args, **kwargs) return dumps(data) # ################################################################################################################################ def to_external_json(self, *args:'any_', **kwargs:'any_') -> 'str': data = self.to_external_dict(*args, **kwargs) return dumps(data) # ################################################################################################################################ # ################################################################################################################################ class SkipDelivery(Exception): """ Raised to indicate to delivery tasks that a given message should be skipped - but not deleted altogether, the delivery will be attempted in the next iteration of the task. """ # ################################################################################################################################ # ################################################################################################################################ class HandleNewMessageCtx: """ Encapsulates information on new messages that a pubsub tool is about to process. """ __slots__ = ('cid', 'has_gd', 'sub_key_list', 'non_gd_msg_list', 'is_bg_call', 'pub_time_max') cid: 'str' has_gd: 'bool' sub_key_list: 'strlist' non_gd_msg_list: 'anylist' is_bg_call: 'bool' pub_time_max: 'float' def __init__( self, cid, # type: str has_gd, # type: bool sub_key_list, # type: strlist non_gd_msg_list, # type: anylist is_bg_call, # type: bool pub_time_max=0.0 # type: float ) -> 'None': self.cid = cid self.has_gd = has_gd self.sub_key_list = sub_key_list self.non_gd_msg_list = non_gd_msg_list self.is_bg_call = is_bg_call self.pub_time_max = pub_time_max # ################################################################################################################################ # ################################################################################################################################ class HookCtx: """ Data and metadata that pub/sub hooks receive on input to their methods. """ __slots__ = ('msg', 'response', 'soap_suds_client') msg: 'any_' soap_suds_client: 'optional[SudsSOAPWrapper]' response: 'any_' def __init__(self, msg:'any_', soap_suds_client:'optional[SudsSOAPWrapper]'=None) -> 'None': self.msg = msg self.soap_suds_client = soap_suds_client self.response = None # ################################################################################################################################ # PubSub's attributes listed separately for ease of making them part of SimpleIO definitions pubsub_main_data = 'cluster_id', 'server_name', 'server_pid', 'server_api_address', 'keep_running', 'subscriptions_by_topic', \ 'subscriptions_by_sub_key', 'sub_key_servers', 'endpoints', 'topics', 'sec_id_to_endpoint_id', \ 'ws_channel_id_to_endpoint_id', 'service_id_to_endpoint_id', 'topic_name_to_id', \ 'pubsub_tool_by_sub_key', 'pubsub_tools', 'sync_backlog', 'msg_pub_counter', 'has_meta_endpoint', \ 'endpoint_meta_store_frequency', 'endpoint_meta_data_len', 'endpoint_meta_max_history', 'data_prefix_len', \ 'data_prefix_short_len' # ################################################################################################################################ class dict_keys: endpoint = 'id', 'name', 'endpoint_type', 'role', 'is_active', 'is_internal', 'topic_patterns', \ 'pub_topic_patterns', 'sub_topic_patterns' subscription = 'id', 'creation_time', 'sub_key', 'endpoint_id', 'endpoint_name', 'topic_id', 'topic_name', \ 'sub_pattern_matched', 'task_delivery_interval', 'unsub_on_wsx_close', 'ext_client_id' topic = 'id', 'name', 'is_active', 'is_internal', 'max_depth_gd', 'max_depth_non_gd', 'has_gd', 'depth_check_freq',\ 'pub_buffer_size_gd', 'task_delivery_interval', 'meta_store_frequency', 'task_sync_interval', 'msg_pub_counter', \ 'msg_pub_counter_gd', 'msg_pub_counter_non_gd', 'last_synced', 'sync_has_gd_msg', 'sync_has_non_gd_msg', \ 'gd_pub_time_max' sks = 'sub_key', 'cluster_id', 'server_name', 'server_pid', 'endpoint_type', 'channel_name', 'pub_client_id', \ 'ext_client_id', 'wsx_info', 'creation_time', 'endpoint_id' # ################################################################################################################################ all_dict_keys = dict_keys.endpoint + dict_keys.subscription + dict_keys.topic + dict_keys.sks all_dict_keys = set(all_dict_keys) # type: ignore[assignment] all_dict_keys = list(all_dict_keys) # type: ignore[assignment] # ################################################################################################################################ # ################################################################################################################################ def ensure_subs_exist( session: 'SQLSession', topic_name: 'str', gd_msg_list: 'anylist', sub_key_aware_objects:'anylist', log_action:'str', context_str:'str', ) -> 'anylist': # A list of input objects that we will return, which will mean that they do exist in the database out = [] # type: anylist # Length of what we have on input, for logging purposes len_orig_sk_list = len(sub_key_aware_objects) # A list of sub keys from which we will potentially remove subscriptions that do not exist sk_set = {elem['sub_key'] for elem in sub_key_aware_objects} query = pubsub_sub_key_list(session) # type: ignore query = query.filter(cast_('Column', PubSubSubscription.sub_key).in_(sk_set)) # type: ignore existing_sk_list = query.all() # type: ignore existing_sk_set = {elem.sub_key for elem in existing_sk_list} # type: ignore # Find the intersection (shared elements) of what we have on input and what the database actually contains .. shared = sk_set & existing_sk_set # .. populate the output list .. for sub in sub_key_aware_objects: if sub['sub_key'] in shared: out.append(sub) # .. log if there was anything removed .. to_remove = sk_set - shared if to_remove: logger.info('Removed sub_keys -> %s -> %s before %s `%s`; len_orig:%s, len_out:%s; left %s -> %s', context_str, to_remove, log_action, topic_name, len_orig_sk_list, len(out), sorted(elem['sub_key'] for elem in out), # type: ignore sorted(elem['pub_msg_id'] for elem in gd_msg_list) ) # .. and return the result to our caller. return out # ################################################################################################################################ # ################################################################################################################################
18,595
Python
.py
356
45.969101
130
0.457445
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,559
tls.py
zatosource_zato/code/zato-common/src/zato/common/test/tls.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import socket import ssl from http.client import OK from tempfile import NamedTemporaryFile from threading import Thread from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer # Python 2/3 compatibility from zato.common.py23_.past.builtins import xrange # Zato from zato.common.api import ZATO_OK from zato.common.test.tls_material import ca_cert, server1_cert, server1_key def get_free_port(start=20001, end=50000): # psutil import psutil taken = [] for c in psutil.net_connections(kind='inet'): if c.status == psutil.CONN_LISTEN: taken.append(c.laddr[1]) for port in xrange(start, end): if port not in taken: return port class _HTTPHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(OK) self.send_header('Content-Type', 'application/json') self.wfile.write('\n') self.wfile.write('"{}"'.format(ZATO_OK)) do_DELETE = do_OPTIONS = do_POST = do_PUT = do_PATCH = do_GET def log_message(self, *ignored_args, **ignored_kwargs): pass # Base class logs to stderr and we want to silence it outs class _TLSServer(HTTPServer): def __init__(self, cert_reqs, ca_cert): self.port = get_free_port() self.cert_reqs = cert_reqs self.ca_cert=None self.socket = None self.server_address = None HTTPServer.__init__(self, ('0.0.0.0', self.port), _HTTPHandler) def server_bind(self): with NamedTemporaryFile(prefix='zato-tls', delete=False) as server1_key_tf: server1_key_tf.write(server1_key) server1_key_tf.flush() with NamedTemporaryFile(prefix='zato-tls', delete=False) as server1_cert_tf: server1_cert_tf.write(server1_cert) server1_cert_tf.flush() with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf: ca_cert_tf.write(ca_cert) ca_cert_tf.flush() self.socket = ssl.wrap_socket( # pylint: disable=deprecated-method self.socket, server1_key_tf.name, server1_cert_tf.name, True, self.cert_reqs, ca_certs=ca_cert_tf.name) if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) self.server_address = self.socket.getsockname() class TLSServer(Thread): def __init__(self, cert_reqs=ssl.CERT_NONE, ca_cert=None): Thread.__init__(self) self.setDaemon(True) self.server = None self.cert_reqs = cert_reqs self.ca_cert=None def get_port(self): return self.server.port def stop(self): self.server.server_close() def run(self): self.server = _TLSServer(self.cert_reqs, self.ca_cert) self.server.serve_forever()
3,194
Python
.py
75
34.36
127
0.647268
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,560
hl7_.py
zatosource_zato/code/zato-common/src/zato/common/test/hl7_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ test_data = """ MSH|^~\\&|MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5 EVN||200605290901||||200605290900 PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260 GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL'S PICKLES^10000 W 100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^AN PV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900 """.strip().replace('\n', '\r') # noqa: E501, W605
775
Python
.py
11
69.181818
226
0.687254
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,561
config.py
zatosource_zato/code/zato-common/src/zato/common/test/config.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os # ################################################################################################################################ # ################################################################################################################################ class TestConfig: # This is a shared topic with multiple subscribers pubsub_topic_shared = '/zato/demo/sample' # This is a different shared topic pubsub_topic_test = '/zato/test/sample' # This topic has only one subscriber pubsub_topic_name_unique = '/zato/demo/unique' # Tests will create topics with this pattern - note the trailing dot. pubsub_topic_name_unique_auto_create = '/zato/demo/unique.' # Tests will also create topics with alsothis pattern - note the trailing dot. pubsub_topic_name_perf_auto_create = '/test-perf.' default_stdout = b'(None)\n' current_app = 'CRM' super_user_name = 'zato.unit-test.admin1' super_user_password = 'hQ9nl93UDqGus' super_user_totp_key = 'KMCLCWN4YPMD2WO3' username_prefix = 'test.{}+{}' random_prefix = 'rand.{}+{}' server_address = 'http://localhost:17010{}' server_location = os.path.expanduser('~/env/qs-1/server1') scheduler_host = 'localhost' scheduler_port = 31530 scheduler_address = 'http://{}:{}{{}}'.format(scheduler_host, scheduler_port) scheduler_location = os.path.expanduser('~/env/qs-1/scheduler') invalid_base_address = '<invalid-base-address>' # ################################################################################################################################ # ################################################################################################################################
1,916
Python
.py
36
49.055556
130
0.498926
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,562
rest_client.py
zatosource_zato/code/zato-common/src/zato/common/test/rest_client.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging from http.client import OK from json import dumps, loads from time import sleep # Bunch from bunch import Bunch, bunchify # Requests import requests # Zato from zato.common.crypto.api import CryptoManager from zato.common.test import BaseZatoTestCase from zato.common.test.config import TestConfig from zato.sso import status_code # ################################################################################################################################ # ################################################################################################################################ if 0: from requests import Response from zato.common.typing_ import any_, anydictnone, anytuple, callable_, optional # ################################################################################################################################ # ################################################################################################################################ logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') logger = logging.getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class RESTClientTestCase(BaseZatoTestCase): needs_bunch = True needs_current_app = True payload_only_messages = True def __init__(self, *args, **kwargs) -> 'None': # type: ignore super().__init__(*args, **kwargs) self.rest_client = RESTClient(self.needs_bunch, self.needs_current_app, self.payload_only_messages) # ################################################################################################################################ def api_invoke(self, *args, **kwargs) -> 'any_': return self.rest_client.api_invoke(*args, **kwargs) # ################################################################################################################################ def get(self, *args, **kwargs): # type: ignore return self.rest_client.get(*args, **kwargs) # ################################################################################################################################ def post(self, *args, **kwargs): # type: ignore return self.rest_client.post(*args, **kwargs) # ################################################################################################################################ def patch(self, *args, **kwargs): # type: ignore return self.rest_client.patch(*args, **kwargs) # ################################################################################################################################ def delete(self, *args, **kwargs): # type: ignore return self.rest_client.delete(*args, **kwargs) # ################################################################################################################################ # ################################################################################################################################ class RESTClient: def __init__( self, needs_bunch=True, # type: bool needs_current_app=True, # type: bool payload_only_messages=True # type: bool ) -> 'None': self.needs_bunch = needs_bunch self.needs_current_app = needs_current_app self.payload_only_messages = payload_only_messages self._api_invoke_username = 'pubapi' self._api_invoke_password = '' self._auth = None self.base_address = '<invalid-base-address>' # ################################################################################################################################ def init(self, /, username:'str'='', sec_name:'str'='') -> 'None': # Zato from zato.common.util.cli import get_zato_sh_command username = username or 'pubapi' sec_name = sec_name or 'pubapi' # Assign for later use self._api_invoke_username = username # A shortcut command = get_zato_sh_command() # Generate a new password .. self._api_invoke_password = CryptoManager.generate_password().decode('utf8') # .. wrap everything in a dict .. payload = { 'name': sec_name, 'password1': self._api_invoke_password, 'password2': self._api_invoke_password, } # .. serialise to JSON, as expected by the CLI .. payload = dumps(payload) # .. log what we are about to do .. logger.info('Changing password for HTTP Basic Auth `%s`', sec_name) # .. reset the password now .. command('service', 'invoke', TestConfig.server_location, 'zato.security.basic-auth.change-password', '--payload', payload) sleep(4) # .. and store the credentials for later use. self._auth = (self._api_invoke_username, self._api_invoke_password) # ################################################################################################################################ def _invoke( self, func, # type: callable_ func_name, # type: str url_path, # type: str request, # type: any_ expect_ok, # type: bool auth=None, # type: optional[anytuple] qs=None, # type: anydictnone _unexpected=object() # type: any_ ) -> 'Bunch': if self.base_address != TestConfig.invalid_base_address: base_adddress = self.base_address else: base_adddress = TestConfig.server_address address = base_adddress.format(url_path) if self.needs_current_app: if request: request['current_app'] = TestConfig.current_app data = dumps(request) if request else '' auth = auth or self._auth logger.info('Invoking %s %s with %s (%s) (%s)', func_name, address, data, auth, qs) response = func(address, data=data, auth=auth, params=qs) # type: Response logger.info('Response received %s %s', response.status_code, response.text) # Most tests require for responses to indicate a successful invocation if expect_ok: # This checks HTTP headers only if response.status_code != OK: raise Exception('Unexpected response.status_code found in response_data `{}` ({})'.format( response.text, response.status_code)) if response.text: response_data = loads(response.text) if self.needs_bunch: response_data = bunchify(response_data) else: response_data = response.text # This is used if everything about the response is in the payload itself, # e.g. HTTP headers are not used to signal or relay anything. if self.payload_only_messages: cid = response_data.get('cid', _unexpected) if cid is _unexpected: raise Exception('Unexpected CID found in response `{}`'.format(response.text)) if response_data['status'] != status_code.ok: raise Exception('Unexpected response_data.status found in response `{}` ({})'.format( response.text, response_data['status'])) # We are here if expect_ok is not True else: if response.text: response_data = loads(response.text) response_data = bunchify(response_data) else: response_data = response.text return response_data # ################################################################################################################################ def api_invoke(self, service:'str', request:'any_'=None) -> 'any_': prefix = '/zato/api/invoke/' url_path = prefix + service auth = (self._api_invoke_username, self._api_invoke_password) return self.post(url_path, request or {}, auth=auth) # ################################################################################################################################ def get(self, url_path:'str', request:'str'='', expect_ok:'bool'=True, auth:'any_'=None) -> 'Bunch': return self._invoke(requests.get, 'GET', url_path, request, expect_ok, auth) # ################################################################################################################################ def post(self, url_path:'str', request:'any_'='', expect_ok:'bool'=True, auth:'any_'=None) -> 'Bunch': return self._invoke(requests.post, 'POST', url_path, request, expect_ok, auth) # ################################################################################################################################ def patch(self, url_path:'str', request:'str'='', expect_ok:'bool'=True, auth:'any_'=None) -> 'Bunch': return self._invoke(requests.patch, 'PATCH', url_path, request, expect_ok, auth) # ################################################################################################################################ def delete(self, url_path:'str', request:'str'='', expect_ok:'bool'=True, auth:'any_'=None, qs:'anydictnone'=None) -> 'Bunch': qs = qs or {} return self._invoke(requests.delete, 'DELETE', url_path, request, expect_ok, auth, qs) # ################################################################################################################################ # ################################################################################################################################
10,010
Python
.py
171
50.45614
130
0.436016
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,563
unittest_.py
zatosource_zato/code/zato-common/src/zato/common/test/unittest_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from time import sleep # Zato from zato.common import PUBSUB from zato.common.test import PubSubConfig from zato.common.test.rest_client import RESTClient, RESTClientTestCase from zato.common.typing_ import cast_ # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, anylist, stranydict # ################################################################################################################################ # ################################################################################################################################ _default = PUBSUB.DEFAULT sec_name = _default.DEFAULT_SECDEF_NAME username = _default.DEFAULT_USERNAME # ################################################################################################################################ # ################################################################################################################################ class PubSubAPIRestImpl: def __init__(self, test:'BasePubSubRestTestCase', rest_client:'RESTClient') -> 'None': self.test = test self.rest_client = rest_client # ################################################################################################################################ def _publish(self, topic_name:'str', data:'any_') -> 'stranydict': request = {'data': data, 'has_gd':True} response = self.rest_client.post(PubSubConfig.PathPublish + topic_name, request) # type: stranydict sleep(6) return response # ################################################################################################################################ def _receive(self, topic_name:'str', needs_sleep:'bool'=True, expect_ok:'bool'=True) -> 'anylist': # Wait a moment to make sure a previously published message is delivered - # the server's delivery task runs once in 2 seconds. sleep(6) return cast_('anylist', self.rest_client.patch(PubSubConfig.PathReceive + topic_name, expect_ok=expect_ok)) # ################################################################################################################################ def _subscribe(self, topic_name:'str', needs_unsubscribe:'bool'=False) -> 'str': if needs_unsubscribe: _ = self._unsubscribe(topic_name) response = self.rest_client.post(PubSubConfig.PathSubscribe + topic_name) sleep(6) return response['sub_key'] # ################################################################################################################################ def _unsubscribe(self, topic_name:'str') -> 'anydict': # Delete a potential subscription based on our credentials response = self.rest_client.delete(PubSubConfig.PathUnsubscribe + topic_name) # type: anydict # Wait a moment to make sure the subscription is deleted sleep(6) # We always expect an empty dict on reply from unsubscribe self.test.assertDictEqual(response, {}) # Our caller may want to run its own assertion too return response # ################################################################################################################################ # ################################################################################################################################ class BasePubSubRestTestCase(RESTClientTestCase): needs_current_app = False payload_only_messages = False should_init_rest_client = True # ################################################################################################################################ def setUp(self) -> 'None': super().setUp() if self.should_init_rest_client: self.rest_client.init(username=username, sec_name=sec_name) self.api_impl = PubSubAPIRestImpl(self, self.rest_client) # ################################################################################################################################ def _publish(self, topic_name:'str', data:'any_') -> 'stranydict': return self.api_impl._publish(topic_name, data) # ################################################################################################################################ def _receive(self, topic_name:'str', needs_sleep:'bool'=True, expect_ok:'bool'=True) -> 'anylist': return self.api_impl._receive(topic_name, needs_sleep, expect_ok) # ################################################################################################################################ def _subscribe(self, topic_name:'str', needs_unsubscribe:'bool'=False) -> 'str': return self.api_impl._subscribe(topic_name, needs_unsubscribe) # ################################################################################################################################ def _unsubscribe(self, topic_name:'str') -> 'anydict': return self.api_impl._unsubscribe(topic_name) # ################################################################################################################################ # ################################################################################################################################
5,681
Python
.py
82
63.95122
130
0.382554
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,564
marshall_.py
zatosource_zato/code/zato-common/src/zato/common/test/marshall_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato from zato.common.ext.dataclasses import dataclass, field from zato.common.marshal_.api import Model from zato.common.typing_ import anynone, anydictnone, anylistnone, dict_field, list_, list_field, optional # ################################################################################################################################ # ################################################################################################################################ def get_default_address_details(): return {'hello':'world'} # ################################################################################################################################ def get_default_address_characteristics(): return ['zzz', 'qqq'] # ################################################################################################################################ # ################################################################################################################################ # Note that the two classes below have the same 'name' attribute which is used by validation tests. @dataclass(init=False, repr=False) class LineDetails(Model): name: str @dataclass(init=False, repr=False) class LineParent(Model): name: str details: LineDetails # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class Address(Model): locality: str post_code: optional[str] details: optional[dict] characteristics: optional[list] # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class AddressWithDefaults(Model): locality: str = 'abc' post_code: optional[str] = '12345' details: optional[dict] = field(default_factory=get_default_address_details) # type: ignore characteristics: optional[list] = field(default_factory=get_default_address_characteristics) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class User(Model): user_name: str address: Address # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class Role(Model): type: str name: str # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class CreateUserRequest(Model): request_id: int user: User role_list: list_[Role] = field(default_factory=list) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class Attr(Model): type: str name: str # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class Phone(Model): attr_list: list_[Attr] = field(default_factory=list) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class Modem(Model): attr_list: list_[Attr] = field(default_factory=list) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class CreatePhoneListRequest(Model): phone_list: list_[Phone] = field(default_factory=list) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=True, repr=False) class CreateAttrListRequest(Model): attr_list: list_[Attr] = field(default_factory=list) # type: ignore # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False, repr=False) class WithAny(Model): str1: anynone list1: anylistnone = list_field() dict1: anydictnone = dict_field() # ################################################################################################################################ # ################################################################################################################################ class TestService: pass # ################################################################################################################################ # ################################################################################################################################
6,528
Python
.py
100
62.72
130
0.275188
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,565
wsx_.py
zatosource_zato/code/zato-common/src/zato/common/test/wsx_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from json import dumps # Zato from zato.common.api import GENERIC, WEB_SOCKET from zato.common.test import CommandLineTestCase from zato.common.typing_ import cast_ from zato.distlock import LockManager from zato.server.connection.pool_wrapper import ConnectionPoolWrapper # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, stranydict, strintdict, strlist, strlistnone from zato.server.generic.api.outconn.wsx.base import OutconnWSXWrapper from zato.server.generic.api.outconn.wsx.client_zato import _ZatoWSXClientImpl # ################################################################################################################################ # ################################################################################################################################ ExtraProperties = WEB_SOCKET.ExtraProperties # ################################################################################################################################ # ################################################################################################################################ class _ParallelServer: def __init__(self) -> 'None': self.zato_lock_manager = LockManager('zato-pass-through', 'zato', cast_('any_', None)) self.wsx_connection_pool_wrapper = ConnectionPoolWrapper(cast_('any_', self), GENERIC.CONNECTION.TYPE.OUTCONN_WSX) def is_active_outconn_wsx(self, _ignored_conn_id:'str') -> 'bool': return True def on_wsx_outconn_stopped_running(self, conn_id:'str') -> 'None': pass def on_wsx_outconn_connected(self, conn_id:'str') -> 'None': pass # ################################################################################################################################ # ################################################################################################################################ class WSXOutconnBaseCase(CommandLineTestCase): def _get_config( self, name:'str', wsx_channel_address:'str', username:'str' = '', secret:'str' = '', queue_build_cap:'float' = 30.0 ) -> 'stranydict': config = {} config['id'] = 1 config['name'] = name config['username'] = username config['secret'] = secret config['pool_size'] = 1 config['is_zato'] = True config['is_active'] = True config['needs_spawn'] = False config['queue_build_cap'] = queue_build_cap config['subscription_list'] = '' config['has_auto_reconnect'] = False config['auth_url'] = config['address'] = config['address_masked'] = wsx_channel_address return config # ################################################################################################################################ def _get_test_server(self): return _ParallelServer() # ################################################################################################################################ def _check_connection_result( self, wrapper:'OutconnWSXWrapper', wsx_channel_address:'str', *, needs_credentials:'bool', should_be_authenticated:'bool', ) -> 'None': outconn_wsx_queue = wrapper.client.queue.queue self.assertEqual(len(outconn_wsx_queue), 1) impl = outconn_wsx_queue[0].impl zato_client = impl._zato_client # type: _ZatoWSXClientImpl self.assertEqual(zato_client.config.address, wsx_channel_address) if should_be_authenticated: self.assertTrue(zato_client.auth_token.startswith('zwsxt')) self.assertTrue(zato_client.is_connected) self.assertTrue(zato_client.is_authenticated) self.assertTrue(zato_client.keep_running) else: self.assertEqual(zato_client.auth_token, '') self.assertFalse(zato_client.is_connected) self.assertFalse(zato_client.is_authenticated) self.assertFalse(zato_client.keep_running) if needs_credentials: self.assertTrue(zato_client.needs_auth) self.assertTrue(zato_client.is_auth_needed) else: self.assertFalse(zato_client.needs_auth) self.assertFalse(zato_client.is_auth_needed) # ################################################################################################################################ # ################################################################################################################################ class WSXChannelManager: test_case: 'CommandLineTestCase' username: 'str' password: 'str' channel_id: 'str' security_id: 'str' security_name: 'str' pubsub_endpoint_id: 'int' needs_credentials: 'bool' wsx_channel_address: 'str' run_cli: 'bool' topics: 'strlistnone' def __init__( self, test_case:'CommandLineTestCase', username:'str' = '', password:'str' = '', needs_credentials:'bool' = False, needs_pubsub:'bool' = False, run_cli:'bool' = True, topics: 'strlistnone' = None ) -> 'None': self.test_case = test_case self.username = username self.password = password self.needs_pubsub = needs_pubsub self.needs_credentials = needs_credentials self.run_cli = run_cli self.topics = topics or [] self.topic_name_to_id = {} # type: strintdict self.channel_id = '' self.security_id = '' self.security_name = '' self.wsx_channel_address = '' # ################################################################################################################################ def create_basic_auth(self): # Command to invoke .. cli_params = ['create', 'basic-auth', '--username', self.username, '--password', self.password] # .. always run in verbose mode .. cli_params.append('--verbose') # .. get the command's response as a dict .. if self.run_cli: out = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # .. and store the security definition's details for later use. self.security_id = out['id'] self.security_name = out['name'] # ################################################################################################################################ def create_topics(self, topics:'strlist') -> 'None': for topic_name in topics: # Command to invoke .. cli_params = ['pubsub', 'create-topic', '--name', topic_name] # .. always run in verbose mode .. cli_params.append('--verbose') if self.run_cli: response = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict self.topic_name_to_id[topic_name] = response['id'] # ################################################################################################################################ def delete_topics(self, topics:'strlist') -> 'None': for topic_name in topics: # Command to invoke .. cli_params = ['pubsub', 'delete-topic', '--name', topic_name] # .. always run in verbose mode .. cli_params.append('--verbose') if self.run_cli: _ = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # ################################################################################################################################ def create_pubsub_endpoint(self, wsx_id:'str') -> 'None': # Command to invoke .. cli_params = ['pubsub', 'create-endpoint', '--wsx-id', wsx_id] # .. always run in verbose mode .. cli_params.append('--verbose') # .. get the command's response as a dict .. if self.run_cli: out = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # .. and store the endpoint's details for later use. self.pubsub_endpoint_id = out['id'] # ################################################################################################################################ def __enter__(self) -> 'WSXChannelManager': # Command to invoke .. cli_params = ['create-wsx-channel'] # .. credentials are optional .. if self.needs_credentials: # .. first, we need a Basic Auth definition for the WSX channel .. self.create_basic_auth() # .. now, we can make use of that definition .. cli_params.append('--security') cli_params.append(self.security_name) # .. we want for the channel to store the runtime context for later use .. extra_properties = dumps({ ExtraProperties.StoreCtx: True }) cli_params.append('--extra-properties') cli_params.append(extra_properties) # .. always run in verbose mode .. cli_params.append('--verbose') # .. get the command's response as a dict .. if self.run_cli: out = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # .. store for later use .. self.channel_id = out['id'] self.wsx_channel_address = out['address'] # .. pub/sub is optional .. if self.needs_pubsub: if self.topics: self.create_topics(self.topics) self.create_pubsub_endpoint(self.channel_id) # .. and return control to the caller. return self # ################################################################################################################################ def delete_basic_auth(self): # Command to invoke .. cli_params = ['delete', 'basic-auth', '--id', self.security_id] # .. now, invoke the command, ignoring the result. if self.run_cli: _ = self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # ################################################################################################################################ def __exit__(self, type_:'any_', value:'any_', traceback:'any_'): if self.needs_credentials: self.delete_basic_auth() # Note that deleting the channel below will also cascade to delete its endpoint # which means that, if we did create an endpoint earlier on, we do not need # to delete it explicitly. # Command to invoke .. cli_params = ['delete-wsx-channel', '--id', self.channel_id, '--verbose'] # .. get its response as a dict .. if self.run_cli: self.test_case.run_zato_cli_json_command(cli_params) # type: anydict # If we created any topics, they need to be deleted now if self.topics: self.delete_topics(self.topics) # ################################################################################################################################ # ################################################################################################################################
11,749
Python
.py
226
43.473451
130
0.463496
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,566
apispec_.py
zatosource_zato/code/zato-common/src/zato/common/test/apispec_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Bunch from bunch import Bunch # PyYAML from yaml import FullLoader, load as yaml_load # Zato from zato.common.util.file_system import fs_safe_name from zato.server.service import Service # ################################################################################################################################ # ################################################################################################################################ if 0: from unittest import TestCase from zato.common.typing_ import anydict # ################################################################################################################################ # ################################################################################################################################ sio_config = Bunch() sio_config.int = Bunch() sio_config.bool = Bunch() sio_config.secret = Bunch() sio_config.bytes_to_str = Bunch() sio_config.int.prefix = set() sio_config.int.exact = set() sio_config.int.suffix = {'_id'} sio_config.bool.prefix = set() sio_config.bool.exact = set() sio_config.bool.suffix = set() service_name = 'helpers.dataclass-service' # ################################################################################################################################ # ################################################################################################################################ class CyMyService(Service): """ This is my service. It has a docstring. """ class SimpleIO: """ * input_req_user_id - This is the first line. Here is another. And here are some more lines. * input_opt_user_name - b111 * output_req_address_id - c111 c222 c333 c444 * output_opt_address_name - d111 d222 """ input_required = 'input_req_user_id', 'input_req_customer_id' input_optional = 'input_opt_user_name', 'input_opt_customer_name' output_required = 'output_req_address_id', 'output_req_address_name' output_optional = 'output_opt_address_type', 'output_opt_address_subtype' # ################################################################################################################################ # ################################################################################################################################ def run_common_apispec_assertions(self:'TestCase', data:'str', with_all_paths:'bool'=True) -> 'None': result = yaml_load(data, FullLoader) components = result['components'] # type: anydict info = result['info'] # type: anydict openapi = result['openapi'] # type: anydict paths = result['paths'] # type: anydict servers = result['servers'] # type: anydict # # Servers # localhost = servers[0] # type: anydict self.assertEqual(localhost['url'], 'http://127.0.0.1:17010') # # Info # self.assertEqual(info['title'], 'API spec') self.assertEqual(info['version'], '1.0') self.assertEqual(openapi, '3.0.3') # # Schemas # schemas = components['schemas'] user_class = 'zato.server.service.internal.helpers.MyUser' account_class = 'zato.server.service.internal.helpers.MyAccount' account_list_class = 'zato.server.service.internal.helpers.MyAccountList' self.assertListEqual(sorted(schemas), [ 'request_helpers_dataclass_service', 'response_helpers_dataclass_service', f'{account_class}', f'{account_list_class}', f'{user_class}', ]) user = schemas[f'{user_class}'] # type: anydict account = schemas[f'{account_class}'] # type: anydict account_list = schemas[f'{account_list_class}'] # type: anydict request = schemas['request_helpers_dataclass_service'] # type: anydict response = schemas['response_helpers_dataclass_service'] # type: anydict # # Request my.service # self.assertEqual(request['title'], 'Request object for helpers.dataclass-service') self.assertEqual(request['type'], 'object') self.assertListEqual(request['required'], ['request_id', 'user']) self.assertDictEqual(request['properties'], { 'request_id': { 'description': '', 'type': 'integer', }, 'user': { '$ref': f'#/components/schemas/{user_class}', 'description': '', }, }) # # Response my.service # self.assertEqual(response['title'], 'Response object for helpers.dataclass-service') self.assertEqual(response['type'], 'object') self.assertListEqual(response['required'], ['account_list', 'current_balance', 'pref_account']) self.assertDictEqual(response['properties'], { 'account_list': { '$ref': f'#/components/schemas/{account_list_class}', 'description': '', }, 'current_balance': { 'description': '', 'type': 'integer', }, 'last_account_no': { 'description': '', 'type': 'integer', }, 'pref_account': { '$ref': f'#/components/schemas/{account_class}', 'description': '', }, }) # # Account schema # self.assertListEqual(account['required'], ['account_no', 'account_segment', 'account_type']) self.assertDictEqual(account['properties'], { 'account_no': { 'description': 'This description is above the field', 'type': 'integer', }, 'account_segment': { 'description': """This is a multiline description, it has two lines.""", 'type': 'string', }, 'account_type': { 'description': 'This is an inline description', 'type': 'string', }, }) # # AccountList schema # self.assertListEqual(account_list['required'], ['account_list']) self.assertDictEqual(account_list['properties'], { 'account_list': { 'description': '', 'type': 'array', 'items': { '$ref': f'#/components/schemas/{account_class}', } } }) # # User schema # self.assertListEqual(user['required'], ['address_data', 'phone_list', 'user_name']) self.assertDictEqual(user['properties'], { 'address_data': { 'description': 'This is a dict', 'type': 'object', 'additionalProperties': {}, }, 'email_list': { 'description': 'This is an optional list', 'type': 'array', 'items': {} }, 'prefs_dict': { 'description': 'This is an optional dict', 'type': 'object', 'additionalProperties': {}, }, 'phone_list': { 'description': 'This is a list', 'type': 'array', 'items': {} }, 'user_name': { 'description': 'This is a string', 'type': 'string', }, }) localhost = servers[0] self.assertEqual(localhost['url'], 'http://127.0.0.1:17010') if with_all_paths: # Both /test/{phone_number} and /zato/api/invoke/helpers.dataclass-service expected_len_paths = 2 url_paths = ['/test/{phone_number}', '/zato/api/invoke/helpers.dataclass-service'] else: # Only /zato/api/invoke/helpers.dataclass-service expected_len_paths = 1 url_paths = ['/zato/api/invoke/helpers.dataclass-service'] self.assertEqual(len(paths), expected_len_paths) # # Information generic to all channels # for url_path in url_paths: service_path = paths[url_path] # type: anydict post = service_path['post'] # type: anydict self.assertEqual(post['operationId'], 'post_{}'.format(fs_safe_name(url_path))) self.assertTrue(post['requestBody']['required']) self.assertEqual( post['requestBody']['content']['application/json']['schema']['$ref'], '#/components/schemas/request_helpers_dataclass_service') self.assertEqual( post['responses']['200']['content']['application/json']['schema']['$ref'], '#/components/schemas/response_helpers_dataclass_service') # # Only the dedicated channel gets path parameters .. # if with_all_paths: path = paths['/test/{phone_number}'] params = path['post']['parameters'] self.assertListEqual(params, [{ 'description': '', 'in': 'path', 'name': 'phone_number', 'required': True, 'schema': { 'format': 'string', 'type': 'string' } }]) # .. whereas the generic API invoker has no path parameters. path = paths['/zato/api/invoke/helpers.dataclass-service'] self.assertNotIn('parameters', path['post']) # ################################################################################################################################ # ################################################################################################################################
9,543
Python
.py
240
32.3875
130
0.49746
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,567
__init__.py
zatosource_zato/code/zato-common/src/zato/common/test/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime from logging import getLogger from tempfile import NamedTemporaryFile from time import sleep from random import choice, randint from unittest import TestCase from uuid import uuid4 # Bunch from bunch import Bunch, bunchify # mock from mock import MagicMock, Mock # six from six import string_types # SQLAlchemy from sqlalchemy import create_engine # Zato from zato.common.api import CHANNEL, DATA_FORMAT, SIMPLE_IO from zato.common.ext.configobj_ import ConfigObj from zato.common.json_internal import loads from zato.common.log_message import CID_LENGTH from zato.common.marshal_.api import MarshalAPI from zato.common.odb import model from zato.common.odb.model import Cluster, ElasticSearch from zato.common.odb.api import SessionWrapper, SQLConnectionPool from zato.common.odb.query import search_es_list from zato.common.simpleio_ import get_bytes_to_str_encoding, get_sio_server_config, simple_io_conf_contents from zato.common.py23_ import maxint from zato.common.typing_ import cast_ from zato.common.util.api import is_port_taken, new_cid from zato.server.service import Service # Zato - Cython from zato.simpleio import CySimpleIO # Python 2/3 compatibility from zato.common.py23_.past.builtins import basestring, cmp, unicode, xrange # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.odb.api import ODBManager from zato.common.typing_ import any_, anydict, anylist, intnone, strnone from zato.common.util.search import SearchResults SearchResults = SearchResults # ################################################################################################################################ # ################################################################################################################################ test_class_name = '<my-test-class>' # ################################################################################################################################ # ################################################################################################################################ class test_odb_data: cluster_id = 1 name = 'my.name' is_active = True es_hosts = 'my.hosts' es_timeout = 111 es_body_as = 'my.body_as' # ################################################################################################################################ # ################################################################################################################################ class PubSubConfig: PathPublish = '/zato/pubsub/topic/' PathReceive = '/zato/pubsub/topic/' PathSubscribe = '/zato/pubsub/subscribe/topic/' PathUnsubscribe = '/zato/pubsub/subscribe/topic/' TestTopicPrefix = '/zato/test/internal/' # ################################################################################################################################ # ################################################################################################################################ def rand_bool(): return choice((True, False)) # ################################################################################################################################ def rand_csv(count=3): return ','.join(str(elem) for elem in rand_int(count=count)) # ################################################################################################################################ def rand_dict(): out = {} funcs = [rand_bool, rand_int, rand_string] for _x in range(rand_int(30)): out[choice(funcs)()] = choice(funcs)() return out # ################################################################################################################################ def rand_list(): out = [] funcs = [rand_bool, rand_int, rand_string] for _x in range(rand_int(30)): out.append(choice(funcs)()) return out # ################################################################################################################################ def rand_list_of_dicts(): out = [] for _x in range(rand_int(30)): out.append(rand_dict()) return out # ################################################################################################################################ def rand_opaque(): return rand_object() rand_nested = rand_opaque # ################################################################################################################################ def rand_datetime(to_string=True): value = datetime.utcnow() # Current time is as random any other return value.isoformat() if to_string else value # ################################################################################################################################ def rand_int(start:'int'=1, stop:'int'=100, count:'int'=1) -> 'any_': if count == 1: return randint(start, stop) else: return [randint(start, stop) for x in range(count)] # ################################################################################################################################ def rand_float(start=1.0, stop=100.0): return float(rand_int(start, stop)) # ################################################################################################################################ def rand_string(count=1, prefix='') -> 'any_': prefix = ('-' + prefix + '-') if prefix else '' if count == 1: return 'a' + prefix + uuid4().hex else: return ['a' + prefix + uuid4().hex for x in range(count)] # ################################################################################################################################ def rand_unicode(): return 'abc-123-ϠϡϢ-ΩΩΩ-ÞÞÞ' # ################################################################################################################################ def rand_object(): return object() # ################################################################################################################################ def rand_date_utc(as_string=False): value = datetime.utcnow() # Now is as random as any other date if as_string: return cast_(str, value.isoformat()) return value # ################################################################################################################################ def is_like_cid(cid): """ Raises ValueError if the cid given on input does not look like a genuine CID produced by zato.common.util.new_cid """ if not isinstance(cid, string_types): raise ValueError('CID `{}` should be string like instead of `{}`'.format(cid, type(cid))) len_given = len(cid) if len_given != CID_LENGTH: raise ValueError('CID `{}` should have length `{}` instead of `{}`'.format(cid, CID_LENGTH, len_given)) return True # ################################################################################################################################ def get_free_tcp_port(start=40000, stop=40500): """ Iterates between start and stop, returning first free TCP port. Must not be used except for tests because it comes with a race condition - another process may want to bind the port we find before our caller does. """ for port in xrange(start, stop): if not is_port_taken(port): return port else: raise Exception('Could not find any free TCP port between {} and {}'.format(start, stop)) # ################################################################################################################################ def enrich_with_static_config(object_): """ Adds to an object (service instance or class) all attributes that are added by service store. Useful during tests since there is no service store around to do it. """ object_.component_enabled_ibm_mq = True object_.component_enabled_zeromq = True object_.component_enabled_patterns = True object_.component_enabled_target_matcher = True object_.component_enabled_invoke_matcher = True object_.component_enabled_sms = True object_.get_name() def target_match(*args, **kwargs): return True is_allowed = target_match object_._worker_config = Bunch(out_odoo=None, out_soap=None) object_._worker_store = Bunch( sql_pool_store=None, outgoing_web_sockets=None, cassandra_api=None, cassandra_query_api=None, email_smtp_api=None, email_imap_api=None, search_es_api=None, search_solr_api=None, target_matcher=Bunch(target_match=target_match, is_allowed=is_allowed), invoke_matcher=Bunch(is_allowed=is_allowed), vault_conn_api=None, sms_twilio_api=None) # ################################################################################################################################ # ################################################################################################################################ class TestCluster: def __init__(self, name:'str') -> 'None': self.name = name # ################################################################################################################################ # ################################################################################################################################ class TestParallelServer: def __init__( self, cluster, # type: TestCluster odb, # type: ODBManager server_name # type: str ) -> 'None': self.cluster = cluster self.cluster_name = self.cluster.name self.odb = odb self.name = server_name def decrypt(self, data:'str') -> 'str': return data def invoke_all_pids(*args, **kwargs): return [] # ################################################################################################################################ # ################################################################################################################################ class Expected: """ A container for the data a test expects the service to return. """ def __init__(self): self.data = [] def add(self, item): self.data.append(item) def get_data(self): if not self.data or len(self.data) > 1: return self.data else: return self.data[0] # ################################################################################################################################ # ################################################################################################################################ class TestBrokerClient: def __init__(self): self.publish_args = [] self.publish_kwargs = [] self.invoke_async_args = [] self.invoke_async_kwargs = [] def publish(self, *args, **kwargs): raise NotImplementedError() def invoke_async(self, *args, **kwargs): self.invoke_async_args.append(args) self.invoke_async_kwargs.append(kwargs) # ################################################################################################################################ # ################################################################################################################################ class TestKVDB: class TestConn: def __init__(self): self.setnx_args = None self.setnx_return_value = True self.expire_args = None self.delete_args = None def return_none(self, *ignored_args, **ignored_kwargs): return None get = hget = return_none def setnx(self, *args): self.setnx_args = args return self.setnx_return_value def expire(self, *args): self.expire_args = args def delete(self, args): self.delete_args = args def __init__(self): self.conn = self.TestConn() def translate(self, *ignored_args, **ignored_kwargs): raise NotImplementedError() # ################################################################################################################################ # ################################################################################################################################ class TestServices: def __getitem__(self, ignored): return {'slow_threshold': 1234} # ################################################################################################################################ # ################################################################################################################################ class TestServiceStore: def __init__(self, name_to_impl_name=None, impl_name_to_service=None): self.services = TestServices() self.name_to_impl_name = name_to_impl_name or {} self.impl_name_to_service = impl_name_to_service or {} def new_instance(self, impl_name, is_active=True): return self.impl_name_to_service[impl_name](), is_active # ################################################################################################################################ # ################################################################################################################################ class TestODB: def session(self, *ignored_args, **ignored_kwargs): pass # ################################################################################################################################ # ################################################################################################################################ class TestServer: def __init__(self, service_store_name_to_impl_name=None, service_store_impl_name_to_service=None, worker_store=None): self.odb = TestODB() self.kvdb = TestKVDB() self.service_store = TestServiceStore(service_store_name_to_impl_name, service_store_impl_name_to_service) self.marshal_api = MarshalAPI() self.worker_store = worker_store self.repo_location = rand_string() self.delivery_store = None self.user_config = Bunch() self.static_config = Bunch() self.time_util = Bunch() self.servers = [] self.ipc_api = None self.component_enabled = Bunch() self.cluster_id = 1 self.name = 'TestServerObject' self.pid = 9988 self.fs_server_config = Bunch() self.fs_server_config.misc = Bunch() self.fs_server_config.misc.zeromq_connect_sleep = 0.1 self.fs_server_config.misc.internal_services_may_be_deleted = False self.fs_server_config.pubsub = Bunch() self.fs_server_config.pubsub_meta_topic = Bunch() self.fs_server_config.pubsub_meta_endpoint_pub = Bunch() self.fs_server_config.pubsub.data_prefix_len = 9999 self.fs_server_config.pubsub.data_prefix_short_len = 123 self.fs_server_config.pubsub.log_if_deliv_server_not_found = True self.fs_server_config.pubsub.log_if_wsx_deliv_server_not_found = False self.fs_server_config.pubsub_meta_topic.enabled = True self.fs_server_config.pubsub_meta_topic.store_frequency = 1 self.fs_server_config.pubsub_meta_endpoint_pub.enabled = True self.fs_server_config.pubsub_meta_endpoint_pub.store_frequency = 1 self.fs_server_config.pubsub_meta_endpoint_pub.data_len = 1234 self.fs_server_config.pubsub_meta_endpoint_pub.max_history = 111 self.ctx = {} # ################################################################################################################################ def invoke(self, service:'any_', request:'any_') -> 'None': self.ctx['service'] = service self.ctx['request'] = request # ################################################################################################################################ def on_wsx_outconn_stopped_running(self, conn_id:'str') -> 'None': pass # ################################################################################################################################ def on_wsx_outconn_connected(self, conn_id:'str') -> 'None': pass # ################################################################################################################################ # ################################################################################################################################ class SIOElemWrapper: """ Makes comparison between two SIOElem elements use their names. """ def __init__(self, value): self.value = value def __cmp__(self, other): # Compare to either other's name or to other directly. In the latter case it means it's a plain string name # of a SIO attribute. return cmp(self.value.name, getattr(other, 'name', other)) # ################################################################################################################################ # ################################################################################################################################ class ServiceTestCase(TestCase): def __init__(self, *args, **kwargs): self.maxDiff = None super(ServiceTestCase, self).__init__(*args, **kwargs) def invoke(self, class_, request_data, expected, mock_data=None, channel=CHANNEL.HTTP_SOAP, job_type=None, data_format=DATA_FORMAT.JSON, service_store_name_to_impl_name=None, service_store_impl_name_to_service=None): """ Sets up a service's invocation environment, then invokes and returns an instance of the service. """ mock_data = mock_data or {} class_.component_enabled_email = True class_.component_enabled_search = True class_.component_enabled_msg_path = True class_.has_sio = getattr(class_, 'SimpleIO', False) instance = class_() server = MagicMock() server.component_enabled.stats = False worker_store = MagicMock() worker_store.worker_config = MagicMock worker_store.worker_config.outgoing_connections = MagicMock(return_value=(None, None, None, None)) worker_store.worker_config.cloud_aws_s3 = MagicMock(return_value=None) worker_store.invoke_matcher.is_allowed = MagicMock(return_value=True) simple_io_config = { 'int_parameters': SIMPLE_IO.INT_PARAMETERS.VALUES, 'int_parameter_suffixes': SIMPLE_IO.INT_PARAMETERS.SUFFIXES, 'bool_parameter_prefixes': SIMPLE_IO.BOOL_PARAMETERS.SUFFIXES, } class_.update( instance, channel, TestServer(service_store_name_to_impl_name, service_store_impl_name_to_service, worker_store), None, worker_store, new_cid(), request_data, request_data, simple_io_config=simple_io_config, data_format=data_format, job_type=job_type) def get_data(self, *ignored_args, **ignored_kwargs): return expected.get_data() instance.get_data = get_data for attr_name, mock_path_data_list in mock_data.items(): setattr(instance, attr_name, Mock()) attr = getattr(instance, attr_name) for mock_path_data in mock_path_data_list: for path, value in mock_path_data.items(): split = path.split('.') new_path = '.return_value.'.join(elem for elem in split) + '.return_value' attr.configure_mock(**{new_path:value}) broker_client_publish = getattr(self, 'broker_client_publish', None) if broker_client_publish: instance.broker_client = TestBrokerClient() instance.broker_client.publish = broker_client_publish def set_response_func(*args, **kwargs): pass instance.handle() instance.update_handle( set_response_func, instance, request_data, channel, data_format, None, server, None, worker_store, new_cid(), None) return instance def _check_sio_request_input(self, instance, request_data): for k, v in request_data.items(): self.assertEqual(getattr(instance.request.input, k), v) sio_keys = set(getattr(instance.SimpleIO, 'input_required', [])) sio_keys.update(set(getattr(instance.SimpleIO, 'input_optional', []))) given_keys = set(request_data.keys()) diff = sio_keys ^ given_keys self.assertFalse(diff, 'There should be no difference between sio_keys {} and given_keys {}, diff {}'.format( sio_keys, given_keys, diff)) def check_impl(self, service_class, request_data, response_data, response_elem, mock_data=None): mock_data = mock_data or {} expected_data = sorted(response_data.items()) instance = self.invoke(service_class, request_data, None, mock_data) self._check_sio_request_input(instance, request_data) if response_data: if not isinstance(instance.response.payload, basestring): response = loads(instance.response.payload.getvalue())[response_elem] # Raises KeyError if 'response_elem' doesn't match else: response = loads(instance.response.payload)[response_elem] self.assertEqual(sorted(response.items()), expected_data) def check_impl_list(self, service_class, item_class, request_data, # noqa response_data, request_elem, response_elem, mock_data={}): # noqa expected_keys = response_data.keys() expected_data = tuple(response_data for x in range(rand_int(10))) expected = Expected() for datum in expected_data: item = item_class() for key in expected_keys: value = getattr(datum, key) setattr(item, key, value) expected.add(item) instance = self.invoke(service_class, request_data, expected, mock_data) response = loads(instance.response.payload.getvalue())[response_elem] for idx, item in enumerate(response): expected = expected_data[idx] given = Bunch(item) for key in expected_keys: given_value = getattr(given, key) expected_value = getattr(expected, key) self.assertEqual(given_value, expected_value) self._check_sio_request_input(instance, request_data) def wrap_force_type(self, elem): return SIOElemWrapper(elem) # ################################################################################################################################ # ################################################################################################################################ class ODBTestCase(TestCase): def setUp(self): engine_url = 'sqlite:///:memory:' pool_name = 'ODBTestCase.pool' config = { 'engine': 'sqlite', 'sqlite_path': ':memory:', 'fs_sql_config': { 'engine': { 'ping_query': 'SELECT 1' } } } # Create a standalone engine .. self.engine = create_engine(engine_url) # .. all ODB objects for that engine.. model.Base.metadata.create_all(self.engine) # .. an SQL pool too .. self.pool = SQLConnectionPool(pool_name, config, config) # .. a session wrapper on top of everything .. self.session_wrapper = SessionWrapper() self.session_wrapper.init_session(pool_name, config, self.pool) # .. and all ODB objects for that wrapper's engine too .. model.Base.metadata.create_all(self.session_wrapper.pool.engine) # Unrelated to the above, used in individual tests self.ODBTestModelClass = ElasticSearch def tearDown(self): model.Base.metadata.drop_all(self.engine) self.ODBTestModelClass = None def get_session(self): return self.session_wrapper.session() def get_sample_odb_orm_result(self, is_list): # type: (bool) -> object cluster = Cluster() cluster.id = test_odb_data.cluster_id cluster.name = 'my.cluster' cluster.odb_type = 'sqlite' cluster.broker_host = 'my.broker.host' cluster.broker_port = 1234 cluster.lb_host = 'my.lb.host' cluster.lb_port = 5678 cluster.lb_agent_port = 9012 es = self.ODBTestModelClass() es.name = test_odb_data.name es.is_active = test_odb_data.is_active es.hosts = test_odb_data.es_hosts es.timeout = test_odb_data.es_timeout es.body_as = test_odb_data.es_body_as es.cluster_id = test_odb_data.cluster_id session = self.session_wrapper._session session.add(cluster) session.add(es) session.commit() session = self.session_wrapper._session result = search_es_list(session, test_odb_data.cluster_id) # type: tuple result = result[0] # type: SearchResults # This is a one-element tuple of ElasticSearch ORM objects result = result.result # type: tuple return result if is_list else result[0] # ################################################################################################################################ # ################################################################################################################################ class MyODBService(Service): class SimpleIO: output = 'cluster_id', 'is_active', 'name' # ################################################################################################################################ # ################################################################################################################################ class MyODBServiceWithResponseElem(MyODBService): class SimpleIO(MyODBService.SimpleIO): response_elem = 'my_response_elem' # ################################################################################################################################ # ################################################################################################################################ class MyZatoClass: def to_zato(self): return { 'cluster_id': test_odb_data.cluster_id, 'is_active': test_odb_data.is_active, 'name': test_odb_data.name, } # ################################################################################################################################ # ################################################################################################################################ class BaseSIOTestCase(TestCase): def setUp(self): self.maxDiff = maxint def get_server_config(self, needs_response_elem=False): with NamedTemporaryFile(delete=False) as f: contents = simple_io_conf_contents.format(bytes_to_str_encoding=get_bytes_to_str_encoding()) if isinstance(contents, unicode): contents = contents.encode('utf8') f.write(contents) f.flush() temporary_file_name=f.name sio_fs_config = ConfigObj(temporary_file_name) sio_fs_config = bunchify(sio_fs_config) import os os.remove(temporary_file_name) sio_server_config = get_sio_server_config(sio_fs_config) if not needs_response_elem: sio_server_config.response_elem = None return sio_server_config # ################################################################################################################################ def get_sio(self, declaration, class_): sio = CySimpleIO(None, self.get_server_config(), declaration) sio.build(class_) return sio # ################################################################################################################################ # ################################################################################################################################ class BaseZatoTestCase(TestCase): maxDiff = 1234567890 def __init__(self, *args, **kwargs) -> 'None': self.logger = getLogger('zato.test') super().__init__(*args, **kwargs) def create_pubsub_topic( self, *, topic_name: 'strnone' = None, topic_prefix:'strnone' = PubSubConfig.TestTopicPrefix, limit_retention:'intnone' = None, limit_message_expiry:'intnone' = None, limit_sub_inactivity:'intnone' = None ) -> 'anydict': if not (topic_name or topic_prefix): raise Exception('Either topic_name or topic_prefix is required') if topic_name and topic_prefix: raise Exception('Cannot provide both topic_name and topic_prefix') if not topic_name: topic_name = topic_prefix + datetime.utcnow().isoformat() # These parameters for the Command to invoke will always exist .. cli_params = ['pubsub', 'create-topic', '--name', topic_name] self.logger.info(f'Creating topic {topic_name} ({self.__class__.__name__})') # .. whereas these ones are optional .. if limit_retention: cli_params.append('--limit-retention') cli_params.append(limit_retention) if limit_message_expiry: cli_params.append('--limit-message-expiry') cli_params.append(limit_message_expiry) if limit_sub_inactivity: cli_params.append('--limit-sub-inactivity') cli_params.append(limit_sub_inactivity) # Create the test topic here .. return self.run_zato_cli_json_command(cli_params) # type: anydict # ################################################################################################################################ def _handle_cli_out( self, out:'str', assert_ok:'bool', load_json:'bool' = False ) -> 'str': # We do not need any extra new lines out = out.strip() # If told do, make sure that the response indicates a success .. if assert_ok: self.assertEqual(out, 'OK') # .. load a JSON response if configured to do so .. if load_json: out = loads(out) # .. and return our output. return out # ################################################################################################################################ def run_zato_cli_command( self, cli_params:'anylist', command_name:'str'='zato', assert_ok:'bool'=False, load_json:'bool'=False, ) -> 'any_': # Zato from zato.common.util.cli import CommandLineInvoker # Prepare the invoker .. invoker = CommandLineInvoker(check_stdout=False) # .. append the path to our test server .. cli_params.append('--path') cli_params.append(invoker.server_location) # .. invoke the service and obtain its response .. out = invoker.invoke_cli(cli_params, command_name) # type: str # .. let the changes propagate across servers .. sleep(1) # .. and let the parent class handle the result return self._handle_cli_out(out, assert_ok, load_json) # ################################################################################################################################ def run_zato_cli_json_command(self, *args, **kwargs) -> 'any_': return self.run_zato_cli_command(*args, **kwargs, load_json=True) # ################################################################################################################################ def delete_pubsub_topics_by_pattern(self, pattern:'str') -> 'any_': cli_params = ['pubsub', 'delete-topics', '--pattern', pattern] return self.run_zato_cli_json_command(cli_params) # ################################################################################################################################ # ################################################################################################################################ class CommandLineTestCase(BaseZatoTestCase): pass # ################################################################################################################################ # ################################################################################################################################ class CommandLineServiceTestCase(BaseZatoTestCase): def run_zato_service_test(self, service_name:'str', assert_ok:'bool'=True) -> 'str': # Zato from zato.common.util.cli import CommandLineServiceInvoker # Prepare the invoker invoker = CommandLineServiceInvoker(check_stdout=False) # .. invoke the service and obtain its response .. out = invoker.invoke_and_test(service_name) # type: str # .. and let the parent class handle the result return self._handle_cli_out(out, assert_ok) # ################################################################################################################################ # ################################################################################################################################
33,881
Python
.py
626
46.84984
136
0.460443
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,568
ftp.py
zatosource_zato/code/zato-common/src/zato/common/test/ftp.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from tempfile import gettempdir from threading import Thread # pyftpdlib from pyftpdlib.authorizers import DummyAuthorizer as _DummyAuthorizer from pyftpdlib.handlers import FTPHandler as _FTPHandler from pyftpdlib.servers import FTPServer as _ImplFTPServer # ################################################################################################################################ # ################################################################################################################################ class config: port = 11021 username = '111' password = '222' directory = gettempdir() # ################################################################################################################################ # ################################################################################################################################ def create_ftp_server(): # type: () -> _ImplFTPServer authorizer = _DummyAuthorizer() authorizer.add_user(config.username, config.password, config.directory, 'elradfmwMT') handler = _FTPHandler handler.authorizer = authorizer handler.banner = 'Welcome to Zato' handler.log_prefix = '[%(username)s]@%(remote_ip)s' address = ('', config.port) server = _ImplFTPServer(address, handler) server.max_cons = 10 server.max_cons_per_ip = 10 return server # ################################################################################################################################ # ################################################################################################################################ class FTPServer(Thread): def __init__(self): self.impl = create_ftp_server() Thread.__init__(self, target=self.impl.serve_forever) self.setDaemon(True) def stop(self): self.impl.close_all() # ################################################################################################################################ # ################################################################################################################################
2,310
Python
.py
45
47.666667
130
0.380614
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,569
tls_material.py
zatosource_zato/code/zato-common/src/zato/common/test/tls_material.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # # ############################################################################################################################## # # ** WARNING ** WARNING ** WARNING ** # # Crypto material below is not safe for use outside of Zato's own unittests. Don't use it anywhere else. # # # ############################################################################################################################## ca_key = """ -----BEGIN RSA PRIVATE KEY----- MIIJKAIBAAKCAgEAvx4Np3z+u6MJkXfqRby7nNk5ucqDFHY0ZB4Tj+0xM1AKQP80 4YtPAkTrGSnpjJqGl8LlG+NYy8WWrYggObuwXpgkcPjG2TkzlCDXW2gnzFUuI/iM StTl7dZMH6/MG89eTnWeruglkH4Dp3kx+MfkpFLcnPr2IkL4/drfZsFXhYMdLTj/ zkq5mkx32kzh77AIdlO2COZ3qTIF9LtZS9X6RwXSowWkT+KPCortI79mjJyiQ2K+ H18N75adcdWmDVHQL+HlEVee1NR2THRVaYsf9yGFcjD0EOJPZsv2GGKzIR0eiQOa 4nK5ZS40uqoGsB7hj+j3aC+2QncXNYPm9Rzjp/NQBG5RCczFefJ6X5Fu1VTSf4AX b9Qln4UsWHbqbkHpuFivVtgg8yyjQTJmqZme62xdyZv+B58pXbPQf7H/eVHxJaO2 LFV0tIrYNIc9VDFiRPmUjGIXb2zX5X5p2vcy5/osmd4UJQA+cJLSOsEbPntfDDaN zKEzTMH4dI+5qO/8raoIhTSv7CbvUzI6sb3C8NltGOs+l24UhI/apjDJs3YAwiq8 PZomOgXSCHqVYkGE9dUK9x5SRNH8dLXOv3TFoqxvWBvZ0moaRIiaUWNEyKlyUB3/ ePXZSOvJT+4bwB9j/eFFzxseaC1TSNlKHz0SLkGqW2rfV6TZYiUtq0RQOVsCAwEA AQKCAgEAkBIbwPLdJJ3XDK4VENUhqS+n8ILVJYumGwMBRDJOMJxZ3n2EY7IcsV06 zRFnWfLzG1x0Uf2kZphg6hgAEwWGAwk2D2O6ou4YD8ZiEioGNmbQDZXETHUJj61I XWqstxovwX2xTbD7AF2+a3VVUnF9ztIYNM6K1XEfOl7QoimFzMP2Lq0VSXHTUJns j8f9Wi6dcnXQeA0kj4uCKedBfYWk0f11uCb8oqvroMrx0UzsBXveZmX9ZLDHVKF5 tuKT9t6Bzla/0771oQM42pGoAZQ7WJUQf/CfTEsOCDQhJGjjGEdXSXpKPAK396pJ XZ3mxMXCzDWWrBerkZctC86PQJ+yjQ2viLsLaF/pHMe4g6vn8yqalJDOOzpal+Jx XFAD10oslzzfBrSaL5kl8Gem/qitFAO032hPW3lUVRgsSJ9ilHYqdIrERqROeDED yVntTTnqCjyNaHhkZl483z+wWam7skGp6G/OWI8ZveSMKRj2g+8mFcEv1ocJ+Z8h gAS4YLQqWhtWr2zFZ6YK/Vd3PmNwyaFjZIQ5vpOESyAiQzo/SXj4MQ4FFCLUOEH7 z39ZL6GmWwSEgOBq850yPAGGflcR7dwTDIZTvffZ81wpup9IJaaginkkoan6GT7t LCtcDqXJpoNhA/lLLQVD2E6QQE3YM5ztkFvqqhgLRMr4f7JU5IECggEBAPdYD1Lw FukDO1wuGpvZygyum3q8CFhucRPy0PFICYRuyx3ZeZC8Y1s3Dydl1QmDX//9a8+e E3ae3/zbbS8tLjkNpHPTUkXrRsZ3f4Pkju2efkpvdLxCBXScGhRNE4jv0d/6gniM 7EgvvutELoxBRE3GFiORhSpa+vWOdMD/aKb7uJ6QNmzpfVHzPo9KfQqDHf4cn3wr Kd8AYpGXn8n0xEsAZMVtrpxRHII3kigCw/9N6GX+jeCPP6IiaoeSWYfC8Iza6YNI St5XDpI8bFs5MPIV8rlM+6IJoz+3z5nh/wb92h48N0znsLWUqR0bciAP1vmSJMSw MTLJrwMwhlobyrECggEBAMXOQ0atRNPKjW21JsdM9cuaWaZ0PC5vhC9OYyONlk8R Ve91xqBJXeklrIgda/SCyFYMfRHBNM1yT42JmS0ubQtWu6wpUQfx6U2XT4ZEEZCq fQG5LpVUlLdHZN/yp5VIuWITh2BFFGB+jYPvZOmX76kuuvbfDjOACh5aSuPjSIgf X22WeNah06a6m2Qh27nIWOh4glk3xMrnHuHGj/GgvrTucjcIcs2elkzM92T0P3rU wuJlp5VgQXCSoPikvShvArh1PBO042kQ28SYbya/mjW47RspiAJQQzvm1DVsi8FI FXm/vu0fSHjWs18ypBYQHeyJeu/qWLxxlt7Dp3sQL8sCggEAHjY2YPYMhlert322 KFU41cW6Hgq7pjmPPFWLaf1XlEKIMtQughxQsoKOKkzI8cmHP1hwA8MWM4YCa/tN YdbN75AYB0HHqdysH2/XNoADaUjTujnU823JBs5ObS5g9Xf9lbMenqTv831Jf6kr WlxagHlymNOchWjpgHbvEefgm4zhpxSMYU8/zHO+r3f0wAT18+UBIgSPr7p3T7tK fDuWgmbA6FCWZGeP6OPqyVJVKGkWuuaV49j7d81mX7rjjq6j/UB8B1ocMv5FPF1/ CsF4lglSRYn+rnMo6o6EIBK3uN3m94x5YL5oGjXXVkPU88+bfY55SUEQMVjrNKOH tZfxcQKCAQAmdIwlwGfCGP3X10D7vB2JAK/vKWfNy0ZSgBXMAqm3I3KmhCoiXUER o45gRAAJ4Ccce38RJZOjYVbP+HE8FGuEqc8AkGO9fK1TtVfzjWYwzsRQwnSo+XGU FCArXZxw7FuGEq/d6nAktlXC0Za3xx8DsB8PAZxcLMdK0Vj/5t7h/99oibliWMGy B1NQazixbJ7ESzFkMPBkVfxt/lFbs1mACV9RDaZsDSnBMpPiH437zkM5CnRDGRx/ yzHaRQS1SKepvrj4R9FySqG/Hbd2PAe57ALEphVYBcycZ6rX3Atrfx0Vt05iARPw 0iS7HDhERcvbgXrSC6hGsnqXQkhcJ3BzAoIBAEd3ZQEWhPu/ChO8AUbtXK3p+G8n s6C7lv8eh+S39+rWYNeuzyvXfVtHSseWG7TWDnDne3WmbQr4nlsLCcsp4wZYxTB+ ysfQnv1qXOQeR4FGGrJ2x9co2rXuIqLiECWY+4IAo5vsjMVi8ZZ4Alj1l78Lg02W WYI7lUgWGFaz6QfMZBCQ08Xnys6ueRZuR8SvI2SvStvehVeCpqOHP8uLxjBkLmSA uosil5GtOP9pgnn+W1tkscTSsTIgsCF3i9qDD7XYdtEDZel80ugDn3SUYbkLRgpi q39wvU1nNWuOlUvW4Eg0ofYIWdgffJvRGLJNJ6+KhBovnkA54JJg1Stwokc= -----END RSA PRIVATE KEY----- """.strip() ca_cert = """ -----BEGIN CERTIFICATE----- MIIFoDCCA4igAwIBAgIJAMpUuR9ijhIRMA0GCSqGSIb3DQEBBQUAMBsxCzAJBgNV BAYTAkFVMQwwCgYDVQQDEwNDQTIwHhcNMTQwNzIwMTgyMTU2WhcNMjQwNzE3MTgy MTU2WjAbMQswCQYDVQQGEwJBVTEMMAoGA1UEAxMDQ0EyMIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEAnMEaU26+UqOtQkiDkCiJdfB/Pv4sL7yef3iE9Taf bpuTPdheqzkeR9NHxklyjKMjrAlVrIDu1D4ZboIDmgcq1Go4OCWhTwriFrATJYlp LZhOlzd5/hC0SCJ1HljR4/mOWsVj/KanftMYzSNADjQ0cxVtPguj/H8Y7CDlQxQ4 d6I1+JPGCUIwG3HfSwC5Lxqp/QLUC6OuKqatwDetaE7+t9Ei6LXrFvOg6rPb4cuQ jymzWnql0Q1NEOGyifbhXaQgO6mM5DaT/q3XtakqviUZDLbIo4IWJAmvlB8tbcbP wzku+6jEBhkdTAzAb6K6evTK4wUUSrHTE6vF/PHq5+KLrGReX/NrCgdTH/LB/Aux 817IF2St4ohiI8XVtWoC/Ye94c1ju/LBWIFPZAxFoNJJ5zvlLwJN8/o1wuIVNQ3p 4FWTXVArmSOGEmQL48UTUFq/VKJeoDstUoyIsKnBn4uRMcYPIsMh1VF6Heayq1T9 eO2Uwkw75IZVLVA9WaXnCIc07peDREFbyWtyKzpDa2Bh8bLVQ/tyB+sBJkO2lGPb PMRZl50IhdD7JENNfTG89LCBNioPDNQXN9q3XQYSZgQ9H70Zp+Y3/ipXvIAelPwq Uyg7YoIjOTqFF25g2c/XSrwSpKCr22lb1vkCLUT7pA0tslMVdULo1FkkkfIDDiHs FC8CAwEAAaOB5jCB4zAdBgNVHQ4EFgQUmh+yIUO2PG/fMMMjXjestsQPg48wSwYD VR0jBEQwQoAUmh+yIUO2PG/fMMMjXjestsQPg4+hH6QdMBsxCzAJBgNVBAYTAkFV MQwwCgYDVQQDEwNDQTKCCQDKVLkfYo4SETAPBgNVHRMBAf8EBTADAQH/MBEGCWCG SAGG+EIBAQQEAwIBBjAJBgNVHRIEAjAAMCsGCWCGSAGG+EIBDQQeFhxUaW55Q0Eg R2VuZXJhdGVkIENlcnRpZmljYXRlMAkGA1UdEQQCMAAwDgYDVR0PAQH/BAQDAgEG MA0GCSqGSIb3DQEBBQUAA4ICAQBJsjzUBFUOpuOGz3n2MwcH8IaDtHyKNTsvhuT8 rS2zVpnexUdRgMzdG0K0mgfKLc+t/oEt8oe08ZtRnpj1FVJLvz68cPbEBxsqkTWi Kf65vtTtoZidVBnpIC4Tq7Kx0XQXg8h+3iykqFF6ObqxZix/V9hs3QDRnTNiWGE7 thGCAWWVy1r56nkS91uhQhSWt471FevmdxOdf7+4Df8OsQGcPF6sH/TQcOVgDc20 EiapNMpRxQmhyOI7HBZdYGmHM6okGTf/mtUFhBLKDfdLfBHoGhUINiv939O6M6X3 LFserZ9DEd9IIOTsvYQyWhJDijekEtvBfehwp1NjQcity/l/pwUajw/NUok56Dj7 jHBjHJSSgb5xJ9EMrtJ2Qm2a5pUZXwF2cJIxBjQR5bufJpgiYPRjzxbncStuibps JjSGwiGvoyGbg2xLw7sSI7C2G9KGMtwbS4Di1/e0M1WfFg/ibT3Z1VhqtEL6Yr+m CG6rI1BBiPfJqqeryLg8q9a4CQFA+vhXSzvly/pT7jZcLyXc/6pCU6GqjFZDaiGI sBQseOvrJQ1CouAMnwc9Z8vxOOThqtMTZsGGawi+16+5NmpLwW53V/wtHUZuk39F 29ICmBRa3wrCyhNMb+AFhaPjO34jtRGqeOJA98eS29GooycDnh/Uwi3txZu6DNmZ NVRV1A== -----END CERTIFICATE----- """.strip() ca_cert_invalid = """ -----BEGIN CERTIFICATE----- MIIF4TCCA8mgAwIBAgIJAOnUIE1WsqOoMA0GCSqGSIb3DQEBBQUAMDAxCzAJBgNV BAYTAkRFMSEwHwYDVQQDExh6YXRvLnVuaXR0ZXN0LmNhLmludmFsaWQwIBcNMTQw ODAxMTYyNTMwWhgPMjExNDA3MDgxNjI1MzBaMDAxCzAJBgNVBAYTAkRFMSEwHwYD VQQDExh6YXRvLnVuaXR0ZXN0LmNhLmludmFsaWQwggIiMA0GCSqGSIb3DQEBAQUA A4ICDwAwggIKAoICAQCevYnCOWEf3ez1utRrUuoBDxRI8VhokIg+q6QcUQyuoTsg ofxgVTnJC9rO/S3xXRUN0cfAbA3wzPvctTvRCcZP+3KZvL58mOfGK6GTIq2Fe2LW tD7YPIaQRsWCWTTy/jKr9CLRqyJ+TVQLjU/CG4MCyUZ/I9+XATPMLy5ew8l24G99 Q1hYk0aB2jEtOGFV3zH4JHD2SlDgrZozcVIkVSRUPMVL8tqNZpLwohV8D4mr58ZB 0ll8SnnT4nZAGb4pgOEUgjials38gBHp3PhNhLG1BN6MdZGDqHjpI3n8T9VX3uhm wv6nYeKG8/SqqjKgq30pEqH/gGjOBAqjdAOi7DTbsq+n6Xk0bDWEUGJG+2D8Odfu AntUm1xpfEEKABQ/JO91HdMIi6bU+Rp30cAxBJqFl3GJt2ypADqh+h3q2vWbZtR1 XgW3j/GzhxzzgGfJ0bqZmDq/bOlcm1zbB43jiUdjay3C+HKUDmnYEkKY0+Ar9gXm QKBgFYEnstNt2ceJiMXhrInFMMLdmHnuiQsGYHPXUvQJQqWcr1a8BSP11AXqf55p wyONLNcKsPIqS8q0OOK89CLzsqUso7tpDYFy237nOKE9ZBMn8NtlRd9UfCLQPC6p 5lFo3/QZsuucVmKZzD2iSSIeCeTDzZsozycOkj/Cr5m4V1S4TmBQl0eA4lIlWQID AQABo4H7MIH4MB0GA1UdDgQWBBRU926sfA4IdgQogtv3jPjcj6dYBTBgBgNVHSME WTBXgBRU926sfA4IdgQogtv3jPjcj6dYBaE0pDIwMDELMAkGA1UEBhMCREUxITAf BgNVBAMTGHphdG8udW5pdHRlc3QuY2EuaW52YWxpZIIJAOnUIE1WsqOoMA8GA1Ud EwEB/wQFMAMBAf8wEQYJYIZIAYb4QgEBBAQDAgEGMAkGA1UdEgQCMAAwKwYJYIZI AYb4QgENBB4WHFRpbnlDQSBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwCQYDVR0RBAIw ADAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggIBAAQY6PF59X5eZ0ju 1J3KwqD41AZPymcNUAn423vQjwyN6h/gavyjyO/a9ZRw/Duk0AZ9Oca7U2ufOG5c QtDksi2Ukk5hQNBo/UDqguPM/+buvNtGF/ibWzzIKj6YxMfFRzrTic+qAEBMli3z UrcrgUQo//iBVx5EYMM/xZm+49Cl6wFJntzM3AL3uvphcR8vvRs9ieEpm11KtMtt G9j/6gsOGH7INX3VRUM9MdxXF45gt/R7Xm915Juh3Qt4ZYrD+eKjuL3JypB56Tb9 7cWaLffzHKGwePYedJXczvQb5nPkgrSYN1SZQoOxaN+f3q3tkn9RcL4zsteoOHSm PJkYTdXkUMluopXFjPOPolNKljEs8Ys0ow+6QT/PLSlGBgH7L/gUWtgxzOpd6NNK 8NES9aZtL+xpmmLkciWH/tXt9s+9+vzCUwEuXF8uvPieJgjgW6hVxFofJpyGy2Vz ZNxG+oBSP8fXDQyNM1PFTVSdP2xVzX2VIhnZOoqUTPAbFHYlsyvXnybcourP2Jtv Ytm+X6SGyQR4eo8wGtXHqu1H8R4/LyFuLy7Xb/ILk/Sp9F1MklNWYUA59d3PlG/a Ds0Vj2YzSEyStP1a+HaahUZEj0+3/W/x+f8068HyWsVDGa2/9U8IZwn7+C7pK9fN wSQh3r/cB+X3alAbvPwTlzyNXFu1 -----END CERTIFICATE----- """.strip() client1_key = """ -----BEGIN RSA PRIVATE KEY----- MIIJKQIBAAKCAgEAzBsxWVTPDi8jBQFVofwMBoSdKvE+VYe+S6w+bTSUekL+pvzf pirRGD7owGcySKgzgZ4Jj8yGEk4tjVxCwq5epEL06XLP5XMEKzk0TMYu+aINcZ2v YCrW3Sr6/GZ9PWw3oHK2pul7g+o1sMPFtOcM1sRfVG5LdXXDXclRd5QTPO2FTrDP cTr5LoC1jtOAJhJ0XqQd/LOV/95j4+k0ypOCCkFI5kl9caZSnaG7xMrSsssLkBrk a99hSN4CB+1/A0vZUsPRIb4yzudlVzn/w7aWKMOQYxLrFE/NJ+4fTiJ9bBpL20jE yiq87kCgVRbx1tVo2Rzyp+bQcDvcKZ6YXrZqj4I9s5JPiygvdnxB5dPegYBFWYkK eosZO8gTif53vZz7yQIiYU768FYpbRW7UVWY2fk+MGBIj0hlCsclPUh66SZYiRlm OaxaufMC4m5ofS4zJNs5HryynvnyTwxqde4iPvukPxuQKASs+z25kSWjqv8R9HqW ct6i0GQNKO1FbcuiX8vlRjXB6bMYEJbSgccESe1yZTSIWvnw0ihFA0K+7K3NsERs IAEdbRxREzgW6eDbTMU8wsaudQsyKHzvZD+blejkgXUEyFO554u9m8VINk/JCmdA P95a+XumFnoNrUQ9n2c4kHfFgT6dzB5i5okXMm1GFrx7d2VLdVBCSAYKIO0CAwEA AQKCAgEAlmu3+9j328E7ctXf8Uha6HbVia9PPCOVSBnBzCPDBTPYjuKwRLsrbE34 pMupEEj95Jm+/D5D1LvO8G49OVLepvo9msqlkrkoKl63P5mTRyB5/fCzLhGEVmz1 mgxCYoEdod7I48wQ3lA+j25Ih6D8Ik+I3iWG8SL//1997b2wS+fUpgDCcPWAbRgo NgGDYQuavaEABJupgW+5eF8HLAB4BuzEOAuTKq3kFw353veHPoNLm0FmdGWlQdlz 77nFMH22xTtRJigRM9DvK9CvwOIQWix+fbWUkFybmsDwS1o5yvC6VPqVJVVH9eKl BvCo/KY85j1iTAFcPkqvX/Dk5HBVqOrmx4NQU5o/9eJnSknfcGAdsWr3952wrHxa kGjjkwsp6fBb/NkVqJuODgzSC7XwJR0D4OwnzTuzcoi2uXwjDohAJEYd6M8rITP1 6RckzXu9upM3bh4cFnv76TF9Dbca0paBb9VPeXSUZYMZazwsXYlETWDLZjhX9RLv CA2pk1gBSorMyqx8KOLfH2Lx8ZbB9QBdqU6WAUz00cO72TiVw2dbU8Gp34BO78N2 mpahflg98WnRLQhzb6iwcCXHzfVdHUYsHcALq5vBh4RkDK74xzXp4sjE0za3BiqA MaO+0+Tsfw7loyXMWXimXFazxD3FZ/YLWQPNlEGJMOma/94DBEECggEBAObaShP9 9RzbpiHltH6/JIOI5f61agc7vyCnHQ9TUejOsUbXrgcsWnVcqSdNa0azpGpqtwKO S2haF+DviKF+zM6znJJ41AyBjqIyBipDAKcF8Tervq2dPP/16SEMO/D1CX0IwFUd M2Si1eWU49bk/y7fkH5zw/0xJXLXrKyDSBTaiyRj6+KGj6h2uJPmRhStlgvuyufu PD0TcffBOP9tx5HfkWcGmnPJrZZ+ehe4Kn5q8BR4W11V64/a03ALbx+2f6DcOU48 8m3O9tXucExjOuDUOC9JZXMQucUEtrOMADnIMLXEjYjW/VbV5jP+QYCj+Er028Ip xoNXjSwyFgduYd0CggEBAOJXCJ0eo9EUSJgSH1ZKPyziRCmhmnEXBVwQOPOYOO73 rPHWdpjG+HUkQSWOsFxa3Yjia9r9z3DA8ynVzPnmbG8Otc4i2IN/S4ksbFFjHtjs F0hQBFmYI21VqkUqK8iFOOwQacFmyYs8lqg7PnQhS7GoQsnbnHE0HOpe9zjQr6Fl T5AY6bJ9cdhXPnap/2LLP08wpNcaW0XbKWRT0+hAl5WvZry3ftn7ubNstF/HAUTU bxLBn0CYMtTg/jAGyYtj5MvNLFGUFGx3Lg51mBS3TZWstOeF/7sAD5w453VjVWKy Qkj4OkWJRxxbB5fuJVGrqTXc/SNh/+z25iuUX0EAMlECggEAVklhRve1loPDJQhm 3rkzPLb+wKWua+W5Gstb4U6TXyFiwcf8FFJPvW5VC4u0fUjIO76HiT0GkoqaQklG GJb8loYsD9N57vK+DYIFK+a/Z66g6t4W922+Ty3rZZ7dCMOOOF39BdNUUllK+fUc 9EXD3BFUQO+kYg7soHBc6l5nouPM/l0a3iDNsXouo5l+uFvpqawny2kQuwN5pdFj LJYr8ipOfuPI9156s7WyjQsZVwdBlWUnQUvMMIjqXwbnEkN0kPu/r664LrMdL/lf oC225DJujb4xXUDzLuEEKTg7HV3mVwqQnIU/TCXHVcfDVAH13I6JVZmnyZAABHT0 JvLrQQKCAQEAmiRboWU0ezctGSN+Y+28iHyvnwqHe20KIWCK6JpKa7QQ+8HqkrEu k9hU5Zb/VGYtaQOKIGGp3EgLUfpg1e+u+RMzjWb9vM/8STcPrX2rjF98m6qiy8Fo nxUwGFpX5v+TfHDRFP1DVKe2kmuGZOAoBJ1qnr4JFK9A4fw6sV6tvWSZgrD0trHn zkXcLEQpwMZaHzwphrRUZIaU8daFAi67DR2fAfaVVS6xkRf+3xtQKefinQtvwTXl qERx15NHvr4RGxpnjEckgZnIq+A56iHLnJs5uFLxjhDEkMfQGYnEpKpxqfAi/yg2 XYFA8p8kmzIk0qHlYytid6bNqfApzsKrgQKCAQAqDHO2DSVZEiqpG9ony4WcRTMY lZ85e3S1gCWDwDHfhGBFLgg7JgmqVsM6De1s6+gcSRK8wXVJzRbF4XWkBLmXU2Nr FS4ZCFoSPDUFrETtd7X5a6UL14gkpmFxNp3NEfIkGHFemti2U2Iv+v2E/A23sQbR oAhWdJru5/ToQEGSS2lThIxebj8laedmKoyI2c4muxwvkB3grrSN1FNDs7bmUSTP CKyAiZSy8T+YHPL4r9Up5M86LRbUvHmIVy7kJaYjQTGeqNJFPX0WMqb6xTm3VA7G 4Zfx4Q3uMFdRgGHQIhwIIYe14sw8ImHbAyRKuXT0Noo/ETmWCaVZzi8pil9M -----END RSA PRIVATE KEY----- """.strip() client1_cert = """ -----BEGIN CERTIFICATE----- MIIF0DCCA7igAwIBAgIBBzANBgkqhkiG9w0BAQUFADAbMQswCQYDVQQGEwJBVTEM MAoGA1UEAxMDQ0EyMB4XDTE0MDkxMzEyNDIwOVoXDTIxMTIxNTEyNDIwOVowNzEL MAkGA1UEBhMCQVUxEDAOBgNVBAMTB0NsaWVudDQxFjAUBgkqhkiG9w0BCQEWB0Ns aWVudDQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDMGzFZVM8OLyMF AVWh/AwGhJ0q8T5Vh75LrD5tNJR6Qv6m/N+mKtEYPujAZzJIqDOBngmPzIYSTi2N XELCrl6kQvTpcs/lcwQrOTRMxi75og1xna9gKtbdKvr8Zn09bDegcram6XuD6jWw w8W05wzWxF9Ubkt1dcNdyVF3lBM87YVOsM9xOvkugLWO04AmEnRepB38s5X/3mPj 6TTKk4IKQUjmSX1xplKdobvEytKyywuQGuRr32FI3gIH7X8DS9lSw9EhvjLO52VX Of/DtpYow5BjEusUT80n7h9OIn1sGkvbSMTKKrzuQKBVFvHW1WjZHPKn5tBwO9wp nphetmqPgj2zkk+LKC92fEHl096BgEVZiQp6ixk7yBOJ/ne9nPvJAiJhTvrwVilt FbtRVZjZ+T4wYEiPSGUKxyU9SHrpJliJGWY5rFq58wLibmh9LjMk2zkevLKe+fJP DGp17iI++6Q/G5AoBKz7PbmRJaOq/xH0epZy3qLQZA0o7UVty6Jfy+VGNcHpsxgQ ltKBxwRJ7XJlNIha+fDSKEUDQr7src2wRGwgAR1tHFETOBbp4NtMxTzCxq51CzIo fO9kP5uV6OSBdQTIU7nni72bxUg2T8kKZ0A/3lr5e6YWeg2tRD2fZziQd8WBPp3M HmLmiRcybUYWvHt3ZUt1UEJIBgog7QIDAQABo4IBATCB/jAJBgNVHRMEAjAAMBEG CWCGSAGG+EIBAQQEAwIEsDArBglghkgBhvhCAQ0EHhYcVGlueUNBIEdlbmVyYXRl ZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUffrp+KrDJFGTgUARU2M+RvvRlJkwSwYD VR0jBEQwQoAUmh+yIUO2PG/fMMMjXjestsQPg4+hH6QdMBsxCzAJBgNVBAYTAkFV MQwwCgYDVQQDEwNDQTKCCQDKVLkfYo4SETAJBgNVHRIEAjAAMBIGA1UdEQQLMAmB B0NsaWVudDQwDgYDVR0PAQH/BAQDAgWgMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMC MA0GCSqGSIb3DQEBBQUAA4ICAQAuspxaskmlZSNIaK4qE2gUWLm37Otr6hwJdP4P s6B4jkjMW5n2gQ0ZjtWVXEG2xA771pTqL9XNtqBdUGRNBs3tj2lSp5n7KTuxilVX S79EaoOVr7/vbEGscgrpRcIhYhXxS9JxdL64drWJybjMBuw945lxPmYA8G3bW3LN R40raEN//gui9Hb0hIW+2uu/WM8Hw60Gmc50q5mQh3A3n8ZUocFxKkUfb3tLqeG3 cgqCYgUctTqISJsHbQkTI594rRhQeYyaGirg0t2OgeVaXBX+7HBnDAomR1VPxahU hhqxc8cE6l6ufIKusljOYljWydcgcinJnwGyH/gxSdMCItolPj4gAiVvCbJ/Pu38 GNlgCPc1pfJ2vSgzoUeMr5HLTx/jwfNpHDE3on/qtiaYCWWkZqKJOC/0Nq2Jz9lM jvbWTSnQ+oRq7B/5cH02u+M2dcuZFrrmosQq680Ov8K/f4/jBjwGgFXg46fCXzsR mNc0s6Dx3nS2ecIocDQfR7cy+oqYVHQOhvBrp6zSbb2H265D8i82jV/i5j6DbZ6P s/Ab7xtyW6AwGr6O+s9Wix4w6vVKds7uq5lTUIjjl5dw6JcHjpBmlmPsKvQH2izx 1fLOfvz9aFHvvXEKFqpptwd9ZQL2KpmNIrOp7jrnpQ1e18zbL8HnX6W4V0rKUAn4 svkkFA== -----END CERTIFICATE----- """.strip() server1_key = """ -----BEGIN RSA PRIVATE KEY----- MIIJKgIBAAKCAgEAtvCbou2IcBSHbMdFWJ4PzPYsxrsprli027OLFEPXs6a3X7L9 z2gNL9BuK7Zh/XK9XNAPYYsjYWVkP0O4JbyK4rH2kOPXuUIYGFztz2BwXPvDLjlr uqNVWAbil3g7EIUqcRJfxkx6aZRG6KlWOfGsJHGd46pUDRF79WupkSauC3t0EgqH C18WcDuQtCkYVxoFiRflfkLdjVl2TD2RcXOBvDnxj1N5668HyVHsEU32l0xfOByq LeLl5z4uk+DrgvmwOFVi/4ij2uSm/+oa2rKFFPLlWUbeUtdiEHQ3Sw+6aY0+95gH sUjMXfqzIF6/Yo/nlk6JjGh4FLaJyDCyOj8MGdG7kgvDl5Ho1cmJip63Y/z95aRf 4gtrZq0nD7upwyZC6XlWS7jr6V7Pd0KrRT9bLbrLeCZEZ1rWiM4KItM8GViolRSY aRyJgQOMh5F0jIV9w9Ai9Oxta72jmCaSFozwQyjWL3CqCxCUsvIFiEQEdiGaGFRs 3DehWI1dHpCmgrTtChCIu1+bEMogl75d1VPYKAHhRcblFySkwjbgpatajxEkKxmb tKeg2kuH8josU+3hxCyj+66JwzfiYt1UNh1uHzrOvheosl3p+5JpotBuVAm4+ofP anEydEXEg9ORxYD08Ddqql62QGO8QUMLt+SwcdWRQRQkjAxvX0lFotMI/eUCAwEA AQKCAgEApgyTWDm+o+0eVzAw05T0xpeUYPY1iRjfYKQBU22Y9moW+/hdxMqvXX0U 4vxyyThChWIc8+71OExtx7bSCP6wGcBrC2yjvHYvpL2E5bylgODMcsKP9CKZLoNh XRc2lXIp6eRBpp54Zii+jCRYLdQc6h9urt1F2W7LUyJcEXJIfAecfVus5Dd1CH4o hD7g5v6pk5xrJEXRD6HqbJ1dzNqJIa5+ghfFDJYcvTFs0vAvKXma3DW4ilnvUAvy /ysi2gmFWDy41TTTdbYhlxyJL4TmovMuFfDrj8oMKt8x6SHnlDMuulH2eYaYaZ1K xdD6ap4wGRBEbXvNsw9U1K7Ot2vOsH+AUK46bZfkw+Oe28j6i342gL/o29z6BwSe GP+an+VeCS87WUuYCzGugucVBU7UnbGkXyYXbSpYS1h0FrSxElqCTxXBmteo4KJL uWo3iQXg7ik8gpPG89Xo5c8tylEVEvA9wLB7lZNPURsY9QNXLyYGffJuW8AYFJyv ymhdiVtLNV5rBUgXmjl+g8g416u6Oj/sx5NfcCQTCw04q5LbCeiHW/KsvIhV3eHz mj7kQ/OrAtdwZA7ER3mhm7cXqw0EutA+p+HZ87BWYi5HBV7eOgxrxHTw9SK4OIFt OhKH6l0nghsI/P7PNBR3b+yySFkrn06ctttYCLm6NRYqRoWFrmkCggEBAOOYJOHw bT/EgJM3vugXl6DKQs4OnfmRdQ2T08HWHCu6tMzEp7veNtE2oAz39XezpOK+gclJ VGnGBLiZC2eTAsyb7WxAbmRW2Q17+K9NC1SXpYvFDFFaWI65sQciiZBdDZlDzUJw NlIXgKfJSuAuqXx78slcQuV69Ii7CYys3AbbPeGgKVEqOHGn74hFhUlmWpoE2lM9 tr2p5pZMdKBIe98dyFnzPbBB81dbIfILzH5wSWJLGPuSWhB28a0cY21OAczd59Eq FyYMTItdk5X8bZLjj0NZ803WWq1usl+X5z3Kr/2aQvV/FRJH26/UBz8z2Pqdk67D WhBLavhTrj1k68sCggEBAM3Ftj5fr2BKV7TiGroZnLDi+9UdOE344K6OI/sM85/m YcUJWGxJFTVgOIpMtIJQ9CxHc9xhTabFSGzJ6VOLYW4r5EbiBFY3WrL4lrUeOIzF XAxBJQR8vt1d/wQD7h0WKDSimpToM4wOcFzEHEkyB9bVbyw2sWj+bM+sD8O5Q0gv a5Z1W406Ssn+z1gvVBM3MDbUqrrzTTXqHvWOwdDvkxb1eIY++Kco5FIhy7NecdT1 oV+8GfOUCFMqLXTRrHg7atQgS7vcehsILuQqhXs0y3PSbbemVgLLG9E0CZ+w/zbX HBu14Hhjj4XogSJi+HC5uyUTafNmq0bYhL29wCax5w8CggEBANAC7CK8VX1koYbr +kWx2lmQwsIFxgilEvCX3YBZqmGlQT2ttwgTrtJENL/lmKoQvHCoYYKQzN/npcT5 y9ycFoDfOn4n3T1Dyxlx5vaBWgu0lg9Kx1lLU4kO2meE/2m8QoOD3oQMfvlElcfE R/ThcPJfbqTu+A049WpKWA4Epwx1MPeYJGsURYZLULehopJVRBVkvg46Z1ytfhx8 QFOGLADd/ZGIqScA/+ElX78TXZFqGwgFTw4O0tYdgAER4yWxmB+f6RHYgFO8BfGS UyNQFO2dogCSo7bOZQ4CEHEiKqzlJTiJ1wz9W0rb9kObbAwt3PAhOSsPTK973oac JLHkHUUCggEAa3ZfsL9j5ZOtrkeO0bXigPZpsmiqKP5ayI5u+ANRkCZO1QoGZbbd Hpz7qi5Y7t28Rwuh1Gv0k63gHwBrnDfkUBcYBnSu8x/BfEoa2sfHnKzNX5D99hP3 0b/vGHe8+O/DW4m31SBXG0PHJos8gnVgZq/ceWiuyjhlNyeSrBKqsp4hP9hWUbEp scgjHNjKvaZKxbfW2f+KSSfVt0QwsB8N4CWeJe3pCdNvOf1wVmJybFdDSa4Al5at qlESoDmIKtpM9i9PnfKMymVBp+MVBr0Rq5Evv4Nc0+SiyGS2yfEzt74rbcVUT0sf fz1ngz/Qo3474Cb9ZCIwPLWCzVy1Zv/tvQKCAQEAv8uxjmM/CqtKDW9c/z4Z4y6O squI4AjCgbml8VzC2aS1zQwbCsq0KmGYVgYALKT4dSH+B+6koy+J5GPpVX9xL0Zq MZJlo1Hmi2hDW+gi/w+Q62iRdqO+SoqbFZJ5aX4iF3dyX9rvDyOzRFr+kddtuQ6y tru00ATHMp2hix8LoKDo8dLY9bX6Y9RmgWAVOYbFHm4OB9wE2fya3feo6O3znJY9 EqlYKE0bzcHQQzeT0+Lh9+1KLBg6B6jfyAscVKmSgJyEHLW7gzgF/h10py8XMEVj syS6C3/DMznzpQSyjdTHqdiGuLfagF9oHxRaRacXaxLP2CzILIUFIaEIvJevYg== -----END RSA PRIVATE KEY----- """.strip() server1_cert = """ -----BEGIN CERTIFICATE----- MIIFwTCCA6mgAwIBAgIBBjANBgkqhkiG9w0BAQUFADAbMQswCQYDVQQGEwJBVTEM MAoGA1UEAxMDQ0EyMB4XDTE0MDkxMzEyNDEzN1oXDTIxMTIxNTEyNDEzN1owOTEL MAkGA1UEBhMCQVUxEjAQBgNVBAMTCWxvY2FsaG9zdDEWMBQGCSqGSIb3DQEJARYH U2VydmVyNDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALbwm6LtiHAU h2zHRVieD8z2LMa7Ka5YtNuzixRD17Omt1+y/c9oDS/Qbiu2Yf1yvVzQD2GLI2Fl ZD9DuCW8iuKx9pDj17lCGBhc7c9gcFz7wy45a7qjVVgG4pd4OxCFKnESX8ZMemmU RuipVjnxrCRxneOqVA0Re/VrqZEmrgt7dBIKhwtfFnA7kLQpGFcaBYkX5X5C3Y1Z dkw9kXFzgbw58Y9TeeuvB8lR7BFN9pdMXzgcqi3i5ec+LpPg64L5sDhVYv+Io9rk pv/qGtqyhRTy5VlG3lLXYhB0N0sPummNPveYB7FIzF36syBev2KP55ZOiYxoeBS2 icgwsjo/DBnRu5ILw5eR6NXJiYqet2P8/eWkX+ILa2atJw+7qcMmQul5Vku46+le z3dCq0U/Wy26y3gmRGda1ojOCiLTPBlYqJUUmGkciYEDjIeRdIyFfcPQIvTsbWu9 o5gmkhaM8EMo1i9wqgsQlLLyBYhEBHYhmhhUbNw3oViNXR6QpoK07QoQiLtfmxDK IJe+XdVT2CgB4UXG5RckpMI24KWrWo8RJCsZm7SnoNpLh/I6LFPt4cQso/uuicM3 4mLdVDYdbh86zr4XqLJd6fuSaaLQblQJuPqHz2pxMnRFxIPTkcWA9PA3aqpetkBj vEFDC7fksHHVkUEUJIwMb19JRaLTCP3lAgMBAAGjgfEwge4wCQYDVR0TBAIwADAR BglghkgBhvhCAQEEBAMCBkAwKwYJYIZIAYb4QgENBB4WHFRpbnlDQSBHZW5lcmF0 ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFHewxkloJzmR2Cj0/za/ZHS0yl92MEsG A1UdIwREMEKAFJofsiFDtjxv3zDDI143rLbED4OPoR+kHTAbMQswCQYDVQQGEwJB VTEMMAoGA1UEAxMDQ0EyggkAylS5H2KOEhEwCQYDVR0SBAIwADASBgNVHREECzAJ gQdTZXJ2ZXI0MBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUA A4ICAQA+EAj846j4u/PZvLITPX/kI1+8Y9JIULKwdQ2v8O5mMf9In2Pk9MQ+81RP rpDZo3ZsfkkdoAR7j5ZeTdMargFAeyErfJpZ5Fv4LryaNotJB0/iG8vcWpOJ7qa7 bae+5hQ0vzAoeIxg7kRXN2noSyHHhd3riddOp3/TxetKoFdWSjjnMXqBvZbYzUcf asdKMXKcvZlan01f+zV8CkR7+Scd+5uW33lNHnUmCzeGA5G8z1vA05u9TVAkwU5r XbdJbUjCE3d+X/jkaS5IvhBu6tKSA1YFcD9Brh8CmMjtCWLk8ETv+78WJzqyjiaT OisFTUI/jC18dKgFyyehEeeYo5SZO7BIsNgplDX2UOumQwZYdUX4M3ObRt2n33Fb ReVhPf39oCDSOGEckRGeJX6ydVRjWJHC/qT3gDKaMPZd5lN0M1BOqyAFakM0oU/7 VPf9dUQsw/BeUvm+34hE382JIefzBA32SsyfQjNf6L6tV1JYEfeaebSI+cIny9me lfvTgPmoabqCXVN03hyppf7/0tD8BpitC9ghFrN61oJLEgJOJ9tLuQz0h5gbxeZP mOAkPcQs5FMuzNmP/amLSfCFfdUT5iIqZ3uIAsqnw0ftp8OOEAdyoC4/vgVx3y6b BOX+H+pK1aZXjNzcacyPSawHJTvqexNJFWV167okb1BmOFJL9w== -----END CERTIFICATE----- """.strip()
18,846
Python
.py
314
58.974522
130
0.940058
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,570
common.py
zatosource_zato/code/zato-common/src/zato/common/test/pubsub/common.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from time import sleep from json import loads from logging import getLogger # Zato from zato.common import PUBSUB from zato.common.pubsub import MSG_PREFIX, skip_to_external from zato.common.test import rand_date_utc from zato.common.test.config import TestConfig from zato.common.typing_ import cast_ # ################################################################################################################################ # ################################################################################################################################ if 0: from unittest import TestCase TestCase = TestCase # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class PubSubTestingClass: def _subscribe(self, *args, **kwargs): # type: ignore raise NotImplementedError() def _unsubscribe(self, *args, **kwargs): # type: ignore raise NotImplementedError() def _publish(self, *args, **kwargs): # type: ignore raise NotImplementedError() def _receive(self, *args, **kwargs): # type: ignore raise NotImplementedError() # ################################################################################################################################ # ################################################################################################################################ topic_name_shared = TestConfig.pubsub_topic_shared topic_name_unique = TestConfig.pubsub_topic_name_unique # ################################################################################################################################ # ################################################################################################################################ class FullPathTester: def __init__(self, test:'PubSubTestingClass', sub_before_publish:'bool', topic_name:'str'='') -> 'None': self.test = test self.sub_before_publish = sub_before_publish self.sub_after_publish = not self.sub_before_publish self.topic_name = topic_name self.sub_key = '<no-sk>' # # If we subscribe to a topic before we publish, we can use the shared topic, # because we are sure that our subscription is going to receive a message. # # However, if we subscribe after a publication, we need to use an exclusive topic. # If we were to use a shared one then, before we managed to subscribe, another subscriber # could have already received our own message that we have just published. # if self.sub_before_publish: self.topic_name = topic_name_shared self.needs_unique = False self.runner_name = 'Shared{}'.format(self.__class__.__name__) else: self.topic_name = topic_name or topic_name_unique self.needs_unique = True self.runner_name = 'Unique{}'.format(self.__class__.__name__) # ################################################################################################################################ def _run(self): # For type hints test = cast_('TestCase', self.test) # Always make sure that we are unsubscribed before the test runs self._unsubscribe('before') # We may potentially need to subscribe before the publication, # in which case we can subscribe to a shared if self.sub_before_publish: logger.info('Subscribing %s (1) (%s)', self.runner_name, self.sub_key) self.sub_key = self.test._subscribe(self.topic_name) # Publish the message data = cast_(str, rand_date_utc(True)) logger.info('Publishing from %s (%s)', self.runner_name, self.sub_key) response_publish = self.test._publish(self.topic_name, data) # We expect to have a correct message ID on output msg_id = response_publish['msg_id'] # type: str test.assertTrue(msg_id.startswith(MSG_PREFIX.MSG_ID)) # We may potentially need to subscribe after the publication if self.sub_after_publish: logger.info('Subscribing %s (2) (%s)', self.runner_name, self.sub_key) self.sub_key = self.test._subscribe(self.topic_name) logger.info('Received sub_key %s for %s (2) (after)', self.sub_key, self.runner_name) # Synchronization tasks run once in 0.5 second, which is why we wait a bit longer # to give them enough time to push the message to a delivery task. sleep_time = 3.6 logger.info('%s sleeping for %ss (%s)', self.runner_name, sleep_time, self.sub_key) sleep(sleep_time) # Now, read the message back from our own queue - we can do it because # we know that we are subscribed already. logger.info('Receiving by %s (%s)', self.runner_name, self.sub_key) response_received = self.test._receive(self.topic_name) # Right now, this is a string because handle_PATCH in pubapi.py:TopicService serializes data to JSON, # which is why we need to load it here. if isinstance(response_received, str): response_received = loads(response_received) # We do not know how many messages we receive because it is possible # that there may be some left over from previous tests. However, we still # expect that the message that we have just published will be the first one # because messages are returned in the Last-In-First-Out order (LIFO). msg_received = response_received[0] test.assertEqual(msg_received['data'], data) test.assertEqual(msg_received['size'], len(data)) test.assertEqual(msg_received['sub_key'], self.sub_key) test.assertEqual(msg_received['delivery_count'], 1) test.assertEqual(msg_received['priority'], PUBSUB.PRIORITY.DEFAULT) test.assertEqual(msg_received['mime_type'], PUBSUB.DEFAULT.MIME_TYPE) test.assertEqual(msg_received['expiration'], PUBSUB.DEFAULT.LimitMessageExpiry) test.assertEqual(msg_received['topic_name'], self.topic_name) # Dates will start with 2nnn, e.g. 2022, or 2107, depending on a particular field date_start = '2' test.assertTrue(msg_received['pub_time_iso'].startswith(date_start)) test.assertTrue(msg_received['expiration_time_iso'].startswith(date_start)) test.assertTrue(msg_received['recv_time_iso'].startswith(date_start)) # Make sure that keys that are not supposed to be returned to external callers # are not returned in the message. for name in skip_to_external: if name in msg_received: test.fail(f'Key `{name}` should not be in message {msg_received}') # ################################################################################################################################ def _unsubscribe(self, action:'str') -> 'None': logger.info('Unsubscribing %s (%s) (%s)', self.runner_name, action, self.sub_key) self.test._unsubscribe(self.topic_name) # If this is a topic with a single subscriber that needs exclusive access, # we need to wait to make sure that we are truly unsubscribed if self.needs_unique: sleep_time = 1 logger.info('%s sleeping for %ss (%s) (%s)', self.runner_name, sleep_time, action, self.sub_key) sleep(sleep_time) # ################################################################################################################################ def run(self): try: self._run() finally: # Always clean up after our tests self._unsubscribe('after') # ################################################################################################################################ # ################################################################################################################################
8,617
Python
.py
141
53.531915
130
0.509132
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,571
publisher.py
zatosource_zato/code/zato-common/src/zato/common/test/pubsub/publisher.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato from zato.common.test import TestServer from zato.common.typing_ import cast_ from zato.server.pubsub import PubSub, Topic # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.server.base.parallel import ParallelServer ParallelServer = ParallelServer # ################################################################################################################################ # ################################################################################################################################ cluster_id = 1 test_server = TestServer() topic_config = {} topic_config['server_name'] = test_server.name topic_config['server_pid'] = test_server.pid topic_config['id'] = 1 topic_config['name'] = 'My Topic' topic_config['is_active'] = True topic_config['is_internal'] = True topic_config['max_depth_gd'] = 111 topic_config['max_depth_non_gd'] = 222 topic_config['has_gd'] = True topic_config['depth_check_freq'] = 333 topic_config['pub_buffer_size_gd'] = 444 topic_config['task_delivery_interval'] = 555 topic_config['meta_store_frequency'] = 666 topic_config['task_sync_interval'] = 777 topic = Topic(topic_config, test_server.name, test_server.pid) # ################################################################################################################################ # ################################################################################################################################ def my_service_invoke_func(): pass def my_new_session_func(): pass # ################################################################################################################################ # ################################################################################################################################ class PublisherTestData: cid = '123' cluster_id = cluster_id server = test_server pubsub = PubSub(cluster_id, cast_('ParallelServer', test_server)) topic = topic endpoint_id = 1 endpoint_name = 'My Endpoint' subscriptions_by_topic = [] msg_id_list = [] pub_pattern_matched = '/*' ext_client_id = 'abc' is_first_run = False now = 1.0 is_wsx = True service_invoke_func = my_service_invoke_func new_session_func = my_new_session_func # ################################################################################################################################ # ################################################################################################################################
2,929
Python
.py
61
45.459016
130
0.387662
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,572
_template_simple_05.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_05.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_05 = """ security: - name: 'Test.Enmasse.Simple-05.Demo Security Definition.{test_suffix}' username: 'Demo Security Definition.{test_suffix}' type: basic_auth realm: 'Demo Security Definition' pubsub_endpoint: - name: 'Test.Enmasse.Simple-05.Demo Endpoint' endpoint_type: rest security_name: 'Test.Enmasse.Simple-05.Demo Security Definition.{test_suffix}' topic_patterns: |- pub=/* sub=/* outgoing_rest: - name: 'Test.Enmasse.Simple-05.Demo REST Connection.{test_suffix}' host: https://example.com url_path: / security_name: 'Test.Enmasse.Simple-05.Demo Security Definition.{test_suffix}' pubsub_subscription: - name: Test.Enmasse.Simple-05.Subscription.000000001.{test_suffix} endpoint_name: 'Test.Enmasse.Simple-05.Demo Endpoint' endpoint_type: rest delivery_method: notify rest_connection: 'Test.Enmasse.Simple-05.Demo REST Connection.{test_suffix}' rest_method: POST topic_list: - /demo/enmasse/simple-05/topic-01.{test_suffix} - /demo/enmasse/simple-05/topic-02.{test_suffix} pubsub_topic: - name: /demo/enmasse/simple-05/topic-01.{test_suffix} - name: /demo/enmasse/simple-05/topic-02.{test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
1,912
Python
.py
41
42.926829
130
0.515625
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,573
_template_simple_06.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_06.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_06 = """ pubsub_endpoint: - name: 'Test.Enmasse.Simple-06.Demo Endpoint' endpoint_type: service service_name: 'pub.helpers.input-logger' topic_patterns: |- pub=/* sub=/* pubsub_subscription: - name: Test.Enmasse.Simple-06.Subscription.000000001.{test_suffix} endpoint_name: 'Test.Enmasse.Simple-06.Demo Endpoint' endpoint_type: service delivery_method: notify topic_list: - /demo/enmasse/simple-06/topic-01.{test_suffix} - /demo/enmasse/simple-06/topic-02.{test_suffix} pubsub_topic: - name: /demo/enmasse/simple-06/topic-01.{test_suffix} - name: /demo/enmasse/simple-06/topic-02.{test_suffix} zato_generic_connection: - name: '{test_suffix}.Microsoft365' type_: cloud-microsoft-365 tenant_id: {test_suffix} - My Teant ID client_id: {test_suffix} - My Client ID secret: "{test_suffix} - My Secret" scopes: https://graph.microsoft.com/.default """ # ################################################################################################################################ # ################################################################################################################################
1,634
Python
.py
36
41.75
130
0.469401
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,574
_template_complex_04.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_complex_04.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_complex_04 = """ zato_cache_builtin: - cache_id: 1 cache_type: "builtin" current_size: 11 extend_expiry_on_get: true extend_expiry_on_set: true id: 1 is_active: true is_default: true max_item_size: 10000 max_size: 10000 name: default opaque: null persistent_storage: "sql" sync_method: "in-background" - cache_id: 1 cache_type: "builtin" current_size: 11 extend_expiry_on_get: true extend_expiry_on_set: true id: 1 is_active: true is_default: false max_item_size: 10000 max_size: 10000 name: "test.complex-01.from-json.002.{test_suffix}" opaque: "{{}}" persistent_storage: "no-persistent-storage" sync_method: "in-background" channel_plain_http: - cache_expiry: 0 cache_id: null cache_name: null cache_type: null connection: "channel" content_encoding: "" content_type: "" data_encoding: "utf-8" data_format: "json" has_rbac: false hl7_version: "hl7-v2" host: "" http_accept: "" id: 98 is_active: true is_audit_log_received_active: false is_audit_log_sent_active: false is_internal: false is_rate_limit_active: false json_path: "" match_slash: true max_bytes_per_message_received: "" max_bytes_per_message_sent: "" max_len_messages_received: "" max_len_messages_sent: "" merge_url_params_req: "True" method: "" name: "/test/api/complex-01/from-json/001/{test_suffix}" params_pri: "channel-params-over-msg" ping_method: "HEAD" pool_size: 20 rate_limit_check_parent_def: false rate_limit_def: "" rate_limit_type: "" sec_def: "zato-no-security" sec_tls_ca_cert_id: null sec_type: null sec_use_rbac: false security_id: null security_name: null serialization_type: "string" service: "pub.zato.ping" service_id: 707 service_name: "pub.zato.ping" service_whitelist: [ "" ] should_parse_on_input: false should_return_errors: false should_validate: false soap_action: "" soap_version: null timeout: "10" transport: "plain_http" url_params_pri: "qs-over-path" url_path: "/test/api/complex-01/from-json/001/{test_suffix}" - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/api/complex-01/001/{test_suffix} params_pri: channel-params-over-msg sec_def: zato-no-security service: pub.zato.ping service_name: pub.zato.ping transport: plain_http url_path: /test/api/complex-01/001/{test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
3,302
Python
.py
108
25.972222
130
0.549827
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,575
_template_complex_01.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_complex_01.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # flake8: noqa # ################################################################################################################################ # ################################################################################################################################ template_complex_01 = """ channel_plain_http: - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/enmasse1/{test_suffix} params_pri: channel -params-over-msg sec_def: zato-no-security service_name: pub.zato.ping transport: plain_http url_path: /test/enmasse1/{test_suffix} - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/enmasse2/{test_suffix} params_pri: channel-params-over-msg sec_def: zato-no-security service: pub.zato.ping service_name: pub.zato.ping transport: plain_http url_path: /test/enmasse2/{test_suffix} zato_generic_connection: - address: ws://localhost:12345 cache_expiry: 0 has_auto_reconnect: true is_active: true is_channel: true is_internal: false is_outconn: false is_zato: true name: test.enmasse.{test_suffix} on_connect_service_name: pub.zato.ping on_message_service_name: pub.zato.ping pool_size: 1 sec_use_rbac: false security_def: ZATO_NONE subscription_list: type_: outconn-wsx # These are taken from generic.connection.py -> extra_secret_keys oauth2_access_token: null consumer_key: null consumer_secret: null def_sec: - name: "Test Basic Auth {test_suffix}" is_active: true type: basic_auth username: "MyUser {test_suffix}" password: "MyPassword" realm: "My Realm" email_smtp: - name: test.email.smtp.complex-01.{smtp_config.name}.{test_suffix} host: {smtp_config.host} is_active: true is_debug: false mode: starttls port: 587 timeout: 300 username: {smtp_config.username} password: {smtp_config.password} ping_address: {smtp_config.ping_address} web_socket: - address: "ws://0.0.0.0:10203/api/{test_suffix}" data_format: "json" id: 1 is_active: true is_audit_log_received_active: false is_audit_log_sent_active: false is_internal: false max_bytes_per_message_received: null max_bytes_per_message_sent: null max_len_messages_received: null max_len_messages_sent: null name: "wsx.enmasse.{test_suffix}" new_token_wait_time: 5 opaque1: '{{"max_bytes_per_message_sent":null,"max_bytes_per_message_received":null,"ping_interval":30,"extra_properties":null,"is_audit_log_received_active":false,"max_len_messages_received":null,"pings_missed_threshold":2,"max_len_messages_sent":null,"security":null,"is_audit_log_sent_active":false,"service_name":"pub.zato.ping"}}' ping_interval: 30 pings_missed_threshold: 2 sec_def: "zato-no-security" sec_type: null security_id: null service: "pub.zato.ping" service_name: "pub.zato.ping" token_ttl: 3600 """ # ################################################################################################################################ # ################################################################################################################################
3,553
Python
.py
96
31.854167
341
0.574289
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,576
_template_complex_05.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_complex_05.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_complex_05 = """ zato_generic_connection: - address: null app_name: tagging auth_mechanism: SCRAM-SHA-256 auth_source: admin cache_expiry: null cache_id: null client_id: null cluster_id: 1 compressor_list: conn_def_id: null connect_timeout: 10 consumer_key: null consumer_secret: null data_encoding: null data_format: null document_class: end_seq: null extra: null hb_frequency: 10 hl7_version: null id: 1 is_active: true is_audit_log_received_active: false is_audit_log_sent_active: false is_channel: false is_internal: false is_outconn: true is_rate_limit_active: false is_tls_enabled: false is_tls_match_hostname_enabled: true is_tz_aware: false is_write_fsync_enabled: true is_write_journal_enabled: false json_path: null logging_level: null max_bytes_per_message_received: null max_bytes_per_message_sent: null max_idle_time: 600 max_len_messages_received: null max_len_messages_sent: null max_msg_size: null max_wait_time: null name: test.mongodb.complex-05.{test_suffix} oauth2_access_token: null oauth_def: null pool_size: 1 pool_size_max: 10 port: null rate_limit_check_parent_def: null rate_limit_def: null rate_limit_type: null read_buffer_size: null read_pref_max_stale: -1 read_pref_tag_list: read_pref_type: primary recv_timeout: null replica_set: sec_tls_ca_cert_id: null sec_use_rbac: false secret: "{test_suffix}" secret_type: null security_id: null server_list: localhost server_select_timeout: 5 should_log_messages: false should_retry_write: false socket_timeout: 30 start_seq: null tenant_id: null timeout: null tls_ca_certs_file: tls_cert_file: tls_ciphers: tls_crl_file: tls_pem_passphrase: null tls_private_key_file: tls_validate: CERT_REQUIRED tls_version: SSLv23 type_: outconn-mongodb username: {test_suffix} username_type: null version: null wait_queue_timeout: 10 write_timeout: 5 write_to_replica: true zlib_level: -1 - address: ws://test.complex-05.{test_suffix} cache_expiry: 0 cache_id: null client_id: null cluster_id: 1 conn_def_id: null consumer_key: null consumer_secret: null data_encoding: null data_format: null end_seq: null extra: null has_auto_reconnect: true hl7_version: null id: 2 is_active: true is_audit_log_received_active: false is_audit_log_sent_active: false is_channel: false is_internal: false is_outconn: true is_rate_limit_active: false is_zato: true json_path: null logging_level: null max_bytes_per_message_received: null max_bytes_per_message_sent: null max_len_messages_received: null max_len_messages_sent: null max_msg_size: null max_wait_time: null name: test.wsx.outconn.complex-05.{test_suffix} oauth2_access_token: null oauth_def: null on_close_service_name: helpers.pubsub.hook on_connect_service_name: helpers.pubsub.hook on_message_service_name: helpers.pubsub.hook pool_size: 1 port: null rate_limit_check_parent_def: null rate_limit_def: null rate_limit_type: null read_buffer_size: null recv_timeout: null sec_tls_ca_cert_id: null sec_use_rbac: false secret: null secret_type: null security_def: ZATO_NONE security_id: null should_log_messages: false start_seq: null subscription_list: tenant_id: null timeout: null type_: outconn-wsx username: null username_type: null version: null """ # ################################################################################################################################ # ################################################################################################################################
4,429
Python
.py
157
23.490446
130
0.598265
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,577
_template_complex_03.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_complex_03.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_complex_03 = """ pubsub_topic: # ################################################################################################################################ - depth_check_freq: 100 has_gd: false hook_service_name: helpers.pubsub.hook is_active: true is_api_sub_allowed: false is_internal: false max_depth_gd: 10000 max_depth_non_gd: 1000 name: /test/complex-03/001/{test_suffix} on_no_subs_pub: drop task_delivery_interval: 2000 task_sync_interval: 500 - depth_check_freq: 100 has_gd: false hook_service_name: helpers.pubsub.hook is_active: true is_api_sub_allowed: false is_internal: false max_depth_gd: 10000 max_depth_non_gd: 1000 name: /test/complex-03/002/{test_suffix} on_no_subs_pub: accept task_delivery_interval: 2000 task_sync_interval: 500 # ################################################################################################################################ - depth_check_freq: 100 has_gd: false hook_service_name: helpers.pubsub.hook is_active: true is_api_sub_allowed: false is_internal: false max_depth_gd: 10000 max_depth_non_gd: 1000 name: /test/complex-03/003/{test_suffix} on_no_subs_pub: drop task_delivery_interval: 2000 task_sync_interval: 500 - depth_check_freq: 100 has_gd: false hook_service_name: helpers.pubsub.hook is_active: true is_api_sub_allowed: false is_internal: false max_depth_gd: 10000 max_depth_non_gd: 1000 name: /test/complex-03/004/{test_suffix} on_no_subs_pub: accept task_delivery_interval: 2000 task_sync_interval: 500 # ################################################################################################################################ """ # ################################################################################################################################ # ################################################################################################################################
2,498
Python
.py
63
35.52381
130
0.428159
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,578
base.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/base.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import basicConfig, getLogger, WARN from traceback import format_exc from unittest import TestCase # Zato from zato.common.test.config import TestConfig # ################################################################################################################################ # ################################################################################################################################ basicConfig(level=WARN, format='%(asctime)s - %(message)s') logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ if 0: from sh import RunningCommand from zato.common.typing_ import any_ # ################################################################################################################################ # ################################################################################################################################ class BaseEnmasseTestCase(TestCase): def _warn_on_error(self, stdout:'any_', stderr:'any_') -> 'None': logger.warning(format_exc()) logger.warning('stdout -> %s', stdout) logger.warning('stderr -> %s', stderr) # ################################################################################################################################ def _assert_command_line_result(self, out:'RunningCommand') -> 'None': self.assertEqual(out.exit_code, 0) stdout = out.stdout.decode('utf8') stderr = out.stderr.decode('utf8') if 'error' in stdout: self._warn_on_error(stdout, stderr) self.fail('Found an error in stdout while invoking enmasse') if 'error' in stderr: self._warn_on_error(stdout, stderr) self.fail('Found an error in stderr while invoking enmasse') # ################################################################################################################################ def invoke_enmasse(self, config_path:'str', require_ok:'bool'=True, missing_wait_time:'int'=1) -> 'RunningCommand': # Zato from zato.common.util.cli import get_zato_sh_command # A shortcut command = get_zato_sh_command() # Invoke enmasse .. out:'RunningCommand' = command('enmasse', TestConfig.server_location, '--import', '--input', config_path, '--replace', '--verbose', '--missing-wait-time', missing_wait_time ) # .. if told to, make sure there was no error in stdout/3stderr .. if require_ok: self._assert_command_line_result(out) return out # ################################################################################################################################
3,149
Python
.py
57
48.807018
130
0.394651
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,579
_template_simple_04.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_04.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_04 = """ pubsub_endpoint: - name: 'Test.Enmasse.Simple-04.Demo Endpoint.Service.{test_suffix}' endpoint_type: service service_name: pub.zato.ping topic_patterns: |- pub=/* sub=/* pubsub_subscription: - name: Test.Enmasse.Simple-04.Subscription.000000001.{test_suffix} endpoint_name: 'Test.Enmasse.Simple-04.Demo Endpoint.Service.{test_suffix}' endpoint_type: service delivery_method: notify topic_list: - /demo/enmasse/simple-04/topic-01.{test_suffix} - /demo/enmasse/simple-04/topic-02.{test_suffix} pubsub_topic: - name: /demo/enmasse/simple-04/topic-01.{test_suffix} - name: /demo/enmasse/simple-04/topic-02.{test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
1,392
Python
.py
29
44.551724
130
0.433432
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,580
_template_complex_02.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_complex_02.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023 Zato Source s.r.o. https://zato.io Licensed under LGPLv3 see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_complex_02 = """ channel_plain_http: - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/api/complex-01/002/{test_suffix} params_pri: channel-params-over-msg sec_def: zato-no-security service: pub.zato.ping service_name: pub.zato.ping transport: plain_http url_path: /test/api/complex-01/002/{test_suffix} - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/api/complex-01/003/{test_suffix} params_pri: channel-params-over-msg sec_def: zato-no-security service: pub.zato.ping service_name: pub.zato.ping transport: plain_http url_path: /test/api/complex-01/003/{test_suffix} - connection: channel is_active: true is_internal: false merge_url_params_req: true name: /test/api/complex-01/004/{test_suffix} params_pri: channel-params-over-msg sec_def: zato-no-security service: pub.zato.ping service_name: pub.zato.ping transport: plain_http url_path: /test/api/complex-01/004/{test_suffix} def_sec: - name: Test.Complex-01.DefSec.BasicAuth.001.{test_suffix} realm: Test.Complex-01.DefSec.BasicAuth.001.{test_suffix} username: Test.Complex-01.DefSec.BasicAuth.001.{test_suffix} is_active: true type: basic_auth password: "{test_suffix}" - name: ide_publisher realm: ide_publisher username: ide_publisher is_active: true type: basic_auth password: "{test_suffix}" outconn_sql: - db_name: {test_suffix}?charset=utf8 engine: mysql+pymysql engine_display_name: MySQL host: {test_suffix} is_active: true name: Test.Complex-01.SQL.001.{test_suffix} pool_size: 10 port: 3306 username: {test_suffix} password: "{test_suffix}" pubsub_endpoint: - endpoint_type: wsx is_active: true is_internal: false name: Test.Complex-01.PubSub.Endpoint.001.{test_suffix} role: pub-sub sec_def: zato-no-security security_id: service_id: topic_patterns: pub=/* sub=/* ws_channel_name: Test.Complex-01.WSX.Channel.001.{test_suffix} - endpoint_type: wsx is_active: true is_internal: false name: Test.Complex-01.PubSub.Endpoint.002.{test_suffix} role: pub-sub sec_def: zato-no-security security_id: service_id: topic_patterns: pub=/test/{test_suffix}/* sub=/test/{test_suffix}/* ws_channel_name: Test.Complex-01.WSX.Channel.002.{test_suffix} web_socket: - address: ws://0.0.0.0:33100/{test_suffix} data_format: json is_active: true is_internal: false is_out: false name: Test.Complex-01.WSX.Channel.001.{test_suffix} new_token_wait_time: 60 ping_interval: 30 pings_missed_threshold: 4 service: pub.zato.ping service_name: pub.zato.ping token_ttl: 3600 sec_def: zato-no-security - address: ws://0.0.0.0:33101/{test_suffix} data_format: json is_active: true is_internal: false is_out: false name: Test.Complex-01.WSX.Channel.002.{test_suffix} new_token_wait_time: 60 ping_interval: 30 pings_missed_threshold: 4 service: pub.zato.ping service_name: pub.zato.ping token_ttl: 3600 sec_type: basic_auth sec_def: 'Test.Complex-01.DefSec.BasicAuth.001.{test_suffix}' zato_cache_builtin: - cache_type: builtin extend_expiry_on_get: true extend_expiry_on_set: true is_active: true is_default: true max_item_size: 1000 max_size: 10000 name: default persistent_storage: sql sync_method: in-background email_smtp: - host: example.com is_active: true is_debug: false mode: starttls name: Test.Complex-01.E-mail.SMTP.001.{test_suffix} opaque1: {{}} ping_address: no-reply@example.com port: 587 timeout: 300 username: "{test_suffix}" password: "{test_suffix}" email_smtp: - host: example.com is_active: true is_debug: false mode: starttls name: Test.Complex-01.E-mail.SMTP.002.{test_suffix} opaque1: {{}} ping_address: no-reply@example.com port: 587 timeout: 300 username: "{test_suffix}" outconn_redis: - db: 0 host: localhost is_active: true name: default port: 8712 redis_sentinels: "" redis_sentinels_master: "" use_redis_sentinels: false password: {test_suffix}" """ # ################################################################################################################################ # ################################################################################################################################
5,099
Python
.py
166
26.078313
130
0.609263
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,581
_template_simple_01.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_01.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_01 = """ security: - name: Test Basic Auth Simple username: "MyUser {test_suffix}" password: "MyPassword" type: basic_auth realm: "My Realm" - name: Test Basic Auth Simple.2 username: "MyUser {test_suffix}.2" type: basic_auth realm: "My Realm" channel_rest: - name: /test/enmasse1/simple/{test_suffix} service: pub.zato.ping url_path: /test/enmasse1/simple/{test_suffix} outgoing_rest: - name: Outgoing Rest Enmasse {test_suffix} host: https://example.com url_path: /enmasse/simple/{test_suffix} - name: Outgoing Rest Enmasse {test_suffix}.2 host: https://example.com url_path: /enmasse/simple/{test_suffix}.2 data_format: form outgoing_ldap: - name: Enmasse LDAP {test_suffix} username: 'CN=example.ldap,OU=example01,OU=Example,OU=Groups,DC=example,DC=corp' auth_type: NTLM server_list: 127.0.0.1:389 password: {test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
1,620
Python
.py
39
38.025641
130
0.463944
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,582
_template_simple_02.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_02.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_02 = """ security: - name: 'Test.Unittest.Test Basic.{test_suffix}' username: 'Test.Unittest.Basic.{test_suffix}' type: basic_auth realm: 'My Realm' - name: Test.Unittest.APIKey.{test_suffix} username: Test.Unittest.APIKey.{test_suffix} type: apikey - name: Test.Unittest.NTLM.{test_suffix} username: domain\\Test.Unittest.NTLM.{test_suffix} type: ntlm - name: Test.Unittest.BearerToken.{test_suffix} username: Test.Unittest.BearerToken.{test_suffix} type: bearer_token auth_endpoint: https://example.com client_id_field: client_id client_secret_field: client_secret grant_type: client_credentials extra_fields: - audience=https://example.com pubsub_endpoint: - name: 'Test.Unittest.My Endpoint.{test_suffix}' endpoint_type: rest security_name: 'Test.Unittest.Test Basic.{test_suffix}' topic_patterns: |- pub=/* sub=/* pubsub_topic: - name: /topic/01.{test_suffix} - name: /topic/02.{test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
1,707
Python
.py
41
37.853659
130
0.476392
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,583
_template_simple_03.py
zatosource_zato/code/zato-common/src/zato/common/test/enmasse_/_template_simple_03.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ template_simple_03 = """ security: - name: 'Test.Enmasse.Simple-03.Demo Security Definition.{test_suffix}' username: 'Demo Security Definition.{test_suffix}' type: basic_auth realm: 'Demo Security Definition' outgoing_rest: - name: 'Test.Enmasse.Simple-03.Demo REST Connection.{test_suffix}' host: https://example.com url_path: / security_name: 'Test.Enmasse.Simple-03.Demo Security Definition.{test_suffix}' - name: 'Test.Enmasse.Simple-03.Outgoing Rest Enmasse abc-123-{test_suffix}.2' host: https://example.com url_path: /enmasse/simple/abc-123-{test_suffix}.2 data_format: "json" - name: 'Test.Enmasse.Simple-03.Outgoing Rest Enmasse abc-123-{test_suffix}.3' host: https://example.com url_path: /enmasse/simple/abc-123-{test_suffix}.3 data_format: form - name: 'Test.Enmasse.Simple-03.Outgoing Rest Enmasse abc-123-{test_suffix}.4' host: https://example.com url_path: /enmasse/simple/abc-123-{test_suffix}.4 data_format: "" pubsub_endpoint: - name: 'Test.Enmasse.Simple-03.Demo Endpoint.{test_suffix}' endpoint_type: rest security_name: 'Test.Enmasse.Simple-03.Demo Security Definition.{test_suffix}' topic_patterns: |- pub=/* sub=/* pubsub_subscription: - name: Test.Enmasse.Simple-03.Subscription.000000001.{test_suffix} endpoint_name: 'Test.Enmasse.Simple-03.Demo Endpoint.{test_suffix}' endpoint_type: rest delivery_method: notify rest_connection: 'Test.Enmasse.Simple-03.Demo REST Connection.{test_suffix}' rest_method: POST topic_list: - /demo/enmasse/simple-03/topic-01.{test_suffix} - /demo/enmasse/simple-03/topic-02.{test_suffix} pubsub_topic: - name: /demo/enmasse/simple-03/topic-01.{test_suffix} - name: /demo/enmasse/simple-03/topic-02.{test_suffix} """ # ################################################################################################################################ # ################################################################################################################################
2,504
Python
.py
53
43.301887
130
0.558981
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,584
totp_.py
zatosource_zato/code/zato-common/src/zato/common/crypto/totp_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # PyOTP import pyotp from pyotp.totp import TOTP # ################################################################################################################################ # ################################################################################################################################ class TOTPManager: @staticmethod def generate_totp_key() -> 'str': return pyotp.random_base32() @staticmethod def verify_totp_code(totp_key:'str', totp_code:'str') -> 'str': return TOTP(totp_key).verify(totp_code) @staticmethod def get_current_totp_code(totp_key:'str') -> 'str': return TOTP(totp_key).now() # ################################################################################################################################ # ################################################################################################################################
1,090
Python
.py
22
45.954545
130
0.341832
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,585
const.py
zatosource_zato/code/zato-common/src/zato/common/crypto/const.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # ################################################################################################################################ # ################################################################################################################################ well_known_data = '3.141592...' # π number zato_stdin_prefix = 'zato+stdin:///' # ################################################################################################################################ # ################################################################################################################################
846
Python
.py
12
69
130
0.263285
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,586
secret_key.py
zatosource_zato/code/zato-common/src/zato/common/crypto/secret_key.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import os import sys # Zato from zato.common.const import SECRETS # ################################################################################################################################ # ################################################################################################################################ def resolve_secret_key(secret_key, _url_prefix=SECRETS.URL_PREFIX): """ Finds a secret key among command line options or via environment variables. """ # We always require a string secret_key = secret_key or '' if secret_key and (not isinstance(_url_prefix, bytes)): _url_prefix = _url_prefix.encode('utf8') # This is a direct value, to be used as-is if not secret_key.startswith(_url_prefix): return secret_key else: # We need to look it up somewhere secret_key = secret_key.replace(_url_prefix, '', 1) # Command line options if secret_key.startswith('cli'): # This will be used by check-config for idx, elem in enumerate(sys.argv): if elem == '--secret-key': secret_key = sys.argv[idx+1] break # This will be used when components are invoked as subprocesses else: # To prevent circular imports from zato.common.util.api import parse_cmd_line_options cli_options = parse_cmd_line_options(sys.argv[1]) secret_key = cli_options['secret_key'] # Environment variables elif secret_key.startswith('env'): env_key = secret_key.replace('env.', '', 1) secret_key = os.environ[env_key] # Unknown scheme, we need to give up else: raise ValueError('Unknown secret key type `{}`'.format(secret_key)) # At this point, we have a secret key extracted in one way or another return secret_key if isinstance(secret_key, bytes) else secret_key.encode('utf8') # ################################################################################################################################ # ################################################################################################################################
2,516
Python
.py
50
42.48
130
0.497141
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,587
api.py
zatosource_zato/code/zato-common/src/zato/common/crypto/api.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import base64 import logging import os from datetime import datetime from math import ceil # Bunch from bunch import bunchify # cryptography from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.primitives.constant_time import bytes_eq # Python 2/3 compatibility from builtins import bytes # Zato from zato.common.const import SECRETS from zato.common.crypto.const import well_known_data, zato_stdin_prefix from zato.common.ext.configobj_ import ConfigObj from zato.common.json_internal import loads # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, strbytes # ################################################################################################################################ # ################################################################################################################################ logger = logging.getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ def is_string_equal(data1:'strbytes', data2:'strbytes') -> 'bool': if isinstance(data1, str): data1 = data1.encode('utf8') if isinstance(data2, str): data2 = data2.encode('utf8') return bytes_eq(data1, data2) # ################################################################################################################################ class SecretKeyError(Exception): pass # ################################################################################################################################ class CryptoManager: """ Used for encryption and decryption of secrets. """ def __init__(self, repo_dir=None, secret_key=None, stdin_data=None, well_known_data=None): # We always get it on input rather than reading it directly because our caller # may want to provide it to subprocesses in which case reading it in this process # would consume it and the other process would not be able to access it. self.stdin_data = stdin_data # In case we have a repository directory on input, look up the secret keys and well known data here .. if not secret_key: if repo_dir: secret_key, well_known_data = self.get_config(repo_dir) # .. no matter if given on input or through repo_dir, we can set up crypto keys now. self.set_config(secret_key, well_known_data) # Callers will be able to register their hashing scheme which will end up in this dict by name self.hash_scheme = {} # ################################################################################################################################ def add_hash_scheme(self, name, rounds, salt_size): """ Adds a new named PBKDF2 hashing scheme, i.e. a set of named variables and a hashing object. """ # hashlib from passlib import hash as passlib_hash self.hash_scheme[name] = passlib_hash.pbkdf2_sha512.using(rounds=rounds, salt_size=salt_size) # ################################################################################################################################ def get_config(self, repo_dir): raise NotImplementedError('Must be implemented by subclasses') # ################################################################################################################################ def _find_secret_key(self, secret_key): """ It's possible that what is in config files is not a secret key directly, but information where to find it, e.g. in environment variables or stdin. This method looks it up in such cases. """ secret_key = secret_key.decode('utf8') if isinstance(secret_key, bytes) else secret_key # Environment variables if secret_key.startswith('$'): try: env_key = secret_key[1:].upper() value = os.environ[env_key] except KeyError: raise SecretKeyError('Environment variable not found `{}`'.format(env_key)) # Read from stdin elif secret_key.startswith(zato_stdin_prefix): value = self.stdin_data if not value: raise SecretKeyError('No data provided on stdin') elif not secret_key: raise SecretKeyError('Secret key is missing') # Use the value as it is else: value = secret_key # Fernet keys always require encoding value = value if isinstance(value, bytes) else value.encode('utf8') # Create a transient key just to confirm that what we found was syntactically correct. # Note that we use our own invalid backend which will not be used by Fernet for anything # but we need to provide it to make sure Fernet.__init__ does not import its default backend. try: Fernet(value, backend='invalid') except Exception as e: raise SecretKeyError(e.args) else: return value # ################################################################################################################################ def set_config(self, secret_key, well_known_data): """ Sets crypto attributes and, to be double sure that they are correct, decrypts well known data to itself in order to confirm that keys are valid / expected. """ key = self._find_secret_key(secret_key) self.secret_key = Fernet(key) self.well_known_data = well_known_data if well_known_data else None if self.well_known_data: self.check_consistency() # ################################################################################################################################ def check_consistency(self): """ Used as a consistency check to confirm that a given component's key can decrypt well-known data. """ try: decrypted = self.decrypt(self.well_known_data) except InvalidToken: raise SecretKeyError('Invalid key, could not decrypt well-known data') else: if decrypted != well_known_data: raise SecretKeyError('Expected for `{}` to equal to `{}`'.format(decrypted, well_known_data)) # ################################################################################################################################ @staticmethod def generate_key(): """ Creates a new random string for Fernet keys. """ return Fernet.generate_key() # ################################################################################################################################ @staticmethod def generate_secret(bits=256, as_str=False) -> 'bytes | str': """ Generates a secret string of bits size. """ value = base64.urlsafe_b64encode(os.urandom(int(bits / 8))) if as_str: value = value.decode('utf8') return value # ################################################################################################################################ @staticmethod def generate_password(bits=192, to_str=False): """ Generates a string strong enough to be a password (default: 192 bits) """ # type: (int, bool) -> str value = CryptoManager.generate_secret(bits) return value.decode('utf8') if to_str else value # ################################################################################################################################ @classmethod def from_repo_dir(cls, secret_key, repo_dir, stdin_data): """ Creates a new CryptoManager instance from a path to configuration file(s). """ return cls(secret_key=secret_key, repo_dir=repo_dir, stdin_data=stdin_data) # ################################################################################################################################ @classmethod def from_secret_key(cls, secret_key, well_known_data=None, stdin_data=None): """ Creates a new CryptoManager instance from an already existing secret key. """ return cls(secret_key=secret_key, well_known_data=well_known_data, stdin_data=stdin_data) # ################################################################################################################################ def encrypt(self, data:'any_', *, needs_str:'bool'=False) -> 'bytes | str': """ Encrypts incoming data, which must be a string. """ # Make sure we encrypt bytes .. if not isinstance(data, bytes): data = data.encode('utf8') # .. get the encrypted bytes .. data = self.secret_key.encrypt(data) # .. optionally, make sure that we return a string .. if needs_str: data = data.decode('utf8') # .. now, we are ready to return our result. return data # ################################################################################################################################ def decrypt(self, encrypted, _prefix=SECRETS.PREFIX_BYTES): """ Returns input data in a clear-text, decrypted, form. """ if not isinstance(encrypted, bytes): encrypted = encrypted.encode('utf8') if encrypted.startswith(_prefix): encrypted = encrypted.replace(_prefix, b'') result = self.secret_key.decrypt(encrypted).decode('utf8') return result # ################################################################################################################################ def hash_secret(self, data:'any_', name:'str'='zato.default') -> 'str': """ Hashes input secret using a named configured (e.g. PBKDF2-SHA512, 100k rounds, salt 32 bytes). """ return self.hash_scheme[name].hash(data) # ################################################################################################################################ def verify_hash(self, given:'any_', expected:'any_', name='zato.default') -> 'bool': return self.hash_scheme[name].verify(given, expected) # ################################################################################################################################ @staticmethod def get_hash_rounds(goal, header_func=None, progress_func=None, footer_func=None): return HashParamsComputer(goal, header_func, progress_func, footer_func).get_info() # ################################################################################################################################ def get_config_entry(self, entry): raise NotImplementedError('May be implemented by subclasses') # ################################################################################################################################ class WebAdminCryptoManager(CryptoManager): """ CryptoManager for web-admin instances. """ def get_config(self, repo_dir): conf_path = os.path.join(repo_dir, 'web-admin.conf') conf = bunchify(loads(open(conf_path).read())) return conf['zato_secret_key'], conf['well_known_data'] # ################################################################################################################################ class SchedulerCryptoManager(CryptoManager): """ CryptoManager for schedulers. """ def get_config(self, repo_dir): conf_path = os.path.join(repo_dir, 'scheduler.conf') conf = bunchify(ConfigObj(conf_path, use_zato=False)) return conf.secret_keys.key1, conf.crypto.well_known_data # ################################################################################################################################ class ServerCryptoManager(CryptoManager): """ CryptoManager for servers. """ def get_config(self, repo_dir): conf_path = os.path.join(repo_dir, 'secrets.conf') conf = bunchify(ConfigObj(conf_path, use_zato=False)) return conf.secret_keys.key1, conf.zato.well_known_data # ################################################################################################################################ class HashParamsComputer: """ Computes parameters for hashing purposes, e.g. number of rounds in PBKDF2. """ def __init__(self, goal, header_func=None, progress_func=None, footer_func=None, scheme='pbkdf2_sha512', loops=10, iters_per_loop=10, salt_size=64, rounds_per_iter=25000): # hashlib from passlib import hash as passlib_hash self.goal = goal self.header_func = header_func self.progress_func = progress_func self.footer_func = footer_func self.scheme = scheme self.loops = loops self.iters_per_loop = iters_per_loop self.iters = self.loops * self.iters_per_loop self.salt_size = salt_size self.rounds_per_iter = rounds_per_iter self.report_per_cent = 5.0 self.report_once_in = self.iters * self.report_per_cent / 100.0 self.hash_scheme = getattr(passlib_hash, scheme).using(salt_size=salt_size, rounds=rounds_per_iter) self.cpu_info = self.get_cpu_info() self._round_down_to_nearest = 1000 self._round_up_to_nearest = 5000 # ################################################################################################################################ def get_cpu_info(self): """ Returns metadata about current CPU the computation is executed on. """ # py-cpuinfo from cpuinfo import get_cpu_info cpu_info = get_cpu_info() return { 'brand': cpu_info['brand'], 'hz_actual': cpu_info['hz_actual'] } # ################################################################################################################################ def get_info(self, _utcnow=datetime.utcnow): if self.header_func: self.header_func(self.cpu_info, self.goal) all_results = [] current_iter = 0 current_loop = 0 # We have several iterations to take into account sudden and unexpected CPU usage spikes, # outliers stemming from such cases which will be rejected. while current_loop < self.loops: current_loop += 1 current_loop_iter = 0 current_loop_result = [] while current_loop_iter < self.iters_per_loop: current_iter += 1 current_loop_iter += 1 start = _utcnow() self.hash_scheme.hash(well_known_data) current_loop_result.append((_utcnow() - start).total_seconds()) if self.progress_func: if current_iter % self.report_once_in == 0: per_cent = int((current_iter / self.iters) * 100) self.progress_func(per_cent) all_results.append(sum(current_loop_result) / len(current_loop_result)) # On average, that many seconds were needed to create a hash with self.rounds rounds .. sec_needed = min(all_results) # .. we now need to extrapolate it to get the desired self.goal seconds. rounds_per_second = int(self.rounds_per_iter / sec_needed) rounds_per_second = self.round_down(rounds_per_second) rounds = int(rounds_per_second * self.goal) rounds = self.round_up(rounds) rounds_per_second_str = '{:,d}'.format(rounds_per_second) rounds_str = '{:,d}'.format(rounds).rjust(len(rounds_per_second_str)) if self.footer_func: self.footer_func(rounds_per_second_str, rounds_str) return { 'rounds_per_second': int(rounds_per_second), 'rounds_per_second_str': rounds_per_second_str.strip(), 'rounds': int(rounds), 'rounds_str': rounds_str.strip(), 'cpu_info': self.cpu_info, 'algorithm': 'PBKDF2-SHA512', 'salt_size': self.salt_size, } # ################################################################################################################################ def round_down(self, value): return int(round(value / self._round_down_to_nearest) * self._round_down_to_nearest) # ################################################################################################################################ def round_up(self, value): return int(ceil(value / self._round_up_to_nearest) * self._round_up_to_nearest) # ################################################################################################################################
17,273
Python
.py
307
48.29316
130
0.479006
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,588
__init__.py
zatosource_zato/code/zato-common/src/zato/common/crypto/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,589
__init__.py
zatosource_zato/code/zato-common/src/zato/common/aux_server/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,590
base.py
zatosource_zato/code/zato-common/src/zato/common/aux_server/base.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import os from json import dumps from logging import getLogger from traceback import format_exc from uuid import uuid4 # Bunch from bunch import Bunch # gevent from gevent.pywsgi import WSGIServer # Zato from zato.common.api import IPC as Common_IPC, ZATO_ODB_POOL_NAME from zato.common.broker_message import code_to_name from zato.common.crypto.api import CryptoManager from zato.common.odb.api import ODBManager, PoolStore from zato.common.typing_ import cast_ from zato.common.util.api import as_bool, absjoin, get_config, is_encrypted, new_cid, set_up_logging from zato.common.util.auth import check_basic_auth from zato.common.util.json_ import json_loads # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, byteslist, callable_, callnone, intnone, strdict, strnone, type_ # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class StatusCode: OK = '200 OK' InternalError = '500 Internal Server error' ServiceUnavailable = '503 Service Unavailable' headers = [('Content-Type', 'application/json')] # ################################################################################################################################ # ################################################################################################################################ class AuxServerConfig: """ Encapsulates configuration of various server-related layers. """ odb: 'ODBManager' username: 'str' = '' password: 'str' = '' env_key_username: 'str' = '' env_key_password: 'str' = '' env_key_auth_required: 'str' = '' server_type: 'str' callback_func: 'callable_' conf_file_name: 'str' crypto_manager: 'CryptoManager' crypto_manager_class: 'type_[CryptoManager]' parent_server_name: 'str' parent_server_pid: 'int' raw_config: 'Bunch' def __init__(self) -> 'None': self.main = Bunch() self.stats_enabled = None self.component_dir = 'not-set-component_dir' # ################################################################################################################################ @staticmethod def get_odb(config:'AuxServerConfig') -> 'ODBManager': odb = ODBManager() sql_pool_store = PoolStore() if config.main.odb.engine != 'sqlite': config.main.odb.host = config.main.odb.host config.main.odb.username = config.main.odb.username config.main.odb.pool_size = config.main.odb.pool_size odb_password:'str' = config.main.odb.password or '' if odb_password and odb_password.startswith('gA'): config.main.odb.password = config.crypto_manager.decrypt(odb_password) sql_pool_store[ZATO_ODB_POOL_NAME] = config.main.odb odb.pool = sql_pool_store[ZATO_ODB_POOL_NAME].pool odb.init_session(ZATO_ODB_POOL_NAME, config.main.odb, odb.pool, False) odb.pool.ping(odb.fs_sql_config) return odb # ################################################################################################################################ def set_credentials_from_env(self) -> 'bool': # Return if there is no environment variable indicating what our credentials are if not self.env_key_auth_required: return False # Return if the variable is set but its boolean value is not True auth_required = os.environ.get(self.env_key_auth_required) auth_required = as_bool(auth_required) if not auth_required: return False # If we are here, we can read our credentials from environment variables username = os.environ.get(self.env_key_username) or 'env_key_username_missing' password = os.environ.get(self.env_key_password) or 'env_key_password_missing.' + uuid4().hex self.username = username self.password = password logger.info(f'Set username from env. variable `{self.env_key_username}`') logger.info(f'Set password from env. variable `{self.env_key_password}`') # Return True to indicate that we have set the credentials return True # ################################################################################################################################ @classmethod def from_repo_location( class_, # type: type_[AuxServerConfig] server_type, # type: str repo_location, # type: str conf_file_name, # type: str crypto_manager_class, # type: type_[CryptoManager] needs_odb=True, # type: bool ) -> 'AuxServerConfig': # Zato from zato.common.util.cli import read_stdin_data # Reusable crypto_manager = crypto_manager_class(repo_location, stdin_data=read_stdin_data()) # Response to produce config = class_() config.server_type = server_type # Path to the component can be built from its repository location component_dir = os.path.join(repo_location, '..', '..') component_dir = os.path.abspath(component_dir) config.component_dir = component_dir # This is optional secrets_conf_location = os.path.join(repo_location, 'secrets.conf') if os.path.exists(secrets_conf_location): secrets_conf = get_config(repo_location, 'secrets.conf', needs_user_config=False) else: secrets_conf = None # Read configuration in raw_config = get_config( repo_location, conf_file_name, crypto_manager=crypto_manager, secrets_conf=secrets_conf, require_exists=True ) config.raw_config = raw_config # type: ignore config.main = cast_('Bunch', raw_config) config.main.crypto.use_tls = as_bool(config.main.crypto.use_tls) # Make all paths absolute if config.main.crypto.use_tls: config.main.crypto.ca_certs_location = absjoin(repo_location, config.main.crypto.ca_certs_location) config.main.crypto.priv_key_location = absjoin(repo_location, config.main.crypto.priv_key_location) config.main.crypto.cert_location = absjoin(repo_location, config.main.crypto.cert_location) # Set up the crypto manager need to access credentials config.crypto_manager = crypto_manager # Optionally, establish an ODB connection has_odb = False if needs_odb: if 'odb' in config.main: config.main.odb.fs_sql_config = get_config(repo_location, 'sql.conf', needs_user_config=False) config.odb = class_.get_odb(config) has_odb = True # We want to have something set, even None, to make sure we do not get AttributeErrors when accessing config.odb if not has_odb: config.odb = None # type: ignore # Decrypt the password used to invoke servers if config.main.get('server'): server_password = config.main.server.server_password or '' # type: str if server_password and server_password.startswith('gA'): server_password = config.crypto_manager.decrypt(server_password) config.main.server.server_password = server_password # Environment variables have precedence .. has_credentials_from_env = config.set_credentials_from_env() # .. if we have not set the credentials in the environment .. # .. we still need to try to set them based on our configuration .. if not has_credentials_from_env: # .. otherwise, check the configuration to obtain the credentials used to invoke schedulers api_clients = config.main.get('api_clients') or {} # Proceed if any API clients are defined .. if api_clients: # .. this will give us all the keys in this part of the configuration .. api_clients_keys = list(api_clients.keys()) # .. out of which we can discard some .. for name in ['auth_required']: if name in api_clients: api_clients_keys.remove(name) # .. if we still have any keys left, we choose the first one to be our API credentials .. if api_clients_keys: # .. note that we currently handle only one username .. username = api_clients_keys[0] # .. decrypt its password .. password = api_clients[username] if is_encrypted(password): password = config.crypto_manager.decrypt(password) # .. make sure both credentials are strings .. username = str(username) password = str(password) # .. we can set its username .. config.username = username config.password = password return config # ################################################################################################################################ # ################################################################################################################################ class AuxServer: """ Main class spawning an auxilliary server and listening for API requests. """ needs_logging_setup: 'bool' api_server: 'WSGIServer' cid_prefix: 'str' server_type: 'str' conf_file_name: 'str' config_class: 'type_[AuxServerConfig]' crypto_manager_class: 'type_[CryptoManager]' needs_odb: 'bool' = True has_credentials: 'bool' = True parent_server_name: 'str' parent_server_pid: 'int' def __init__(self, config:'AuxServerConfig') -> 'None': # Type hints tls_kwargs:'strdict' self.config = config self.parent_server_name = config.parent_server_name self.parent_server_pid = config.parent_server_pid main = self.config.main if main.crypto.use_tls: tls_kwargs = { 'keyfile': main.crypto.priv_key_location, 'certfile': main.crypto.cert_location } else: tls_kwargs = {} # API server self.api_server = WSGIServer((main.bind.host, int(main.bind.port)), self, **tls_kwargs) # ################################################################################################################################ @classmethod def before_config_hook(class_:'type_[AuxServer]') -> 'None': pass # ################################################################################################################################ @classmethod def after_config_hook( class_, # type: type_[AuxServer] config, # type: AuxServerConfig repo_location, # type: str ) -> 'None': logger = getLogger(__name__) logger.info('{} starting (http{}://{}:{})'.format( config.server_type, 's' if config.main.crypto.use_tls else '', config.main.bind.host, config.main.bind.port) ) # ################################################################################################################################ @classmethod def start( class_, # type: type_[AuxServer] *, base_dir=None, # type: strnone bind_host='127.0.0.1', # type: str bind_port=None, # type: intnone username='', # type: str password='', # type: str callback_func=None, # type: callnone server_type_suffix='', # type: str parent_server_name='', # type: str parent_server_pid=-1, # type: int ) -> 'None': # Functionality that needs to run before configuration is created class_.before_config_hook() # Where we keep our configuration base_dir = base_dir or '.' repo_location = os.path.join(base_dir, 'config', 'repo') # Optionally, configure logging if class_.needs_logging_setup: set_up_logging(repo_location) # The main configuration object config = class_.config_class.from_repo_location( class_.server_type, repo_location, class_.conf_file_name, class_.crypto_manager_class, class_.needs_odb, ) config.parent_server_name = parent_server_name config.parent_server_pid = parent_server_pid if not config.username: username = username or 'ipc.username.not.set.' + CryptoManager.generate_secret().decode('utf8') # type: ignore config.username = username if not config.password: password = password or 'ipc.password.not.set.' + CryptoManager.generate_secret().decode('utf8') # type: ignore config.password = password if callback_func: config.callback_func = callback_func config.server_type = config.server_type + server_type_suffix # This is optional if bind_port: config.main.bind = Bunch() config.main.bind.host = bind_host config.main.bind.port = bind_port # Functionality that needs to run before configuration is created class_.after_config_hook(config, repo_location) # Run the server now try: class_(config).serve_forever() except Exception: logger.warning(format_exc()) # ################################################################################################################################ def serve_forever(self) -> 'None': self.api_server.serve_forever() # ################################################################################################################################ def get_action_func_impl(self, action_name:'str') -> 'callable_': raise NotImplementedError() # ################################################################################################################################ def _check_credentials(self, credentials:'str') -> 'None': result = check_basic_auth('', credentials, self.config.username, self.config.password) if result is not True: logger.info('Credentials error -> %s', result) raise Exception('Invalid credentials') # ################################################################################################################################ def should_check_credentials(self) -> 'bool': return True # ################################################################################################################################ def handle_api_request(self, data:'bytes', credentials:'str') -> 'any_': # Convert to a Python dict .. request = json_loads(data) # .. callback functions expect Bunch instances on input .. request = Bunch(request) # type: ignore # .. first, check credentials .. if self.has_credentials: if self.should_check_credentials(): self._check_credentials(credentials) # .. look up the action we need to invoke .. action = request.get('action') # type: ignore # .. make sure that the basic information was given on input .. if not action: raise Exception('No action key found in API request') action_name = code_to_name[action] # type: ignore # .. convert it to an actual method to invoke .. func = self.get_action_func_impl(action_name) # .. finally, invoke the function with the input data. response = func(request) return response # ################################################################################################################################ def __call__(self, env:'anydict', start_response:'callable_') -> 'byteslist': cid = '<cid-unassigned>' response = {} status_text = '<status_text-unassigned>' status_code = StatusCode.ServiceUnavailable try: # Assign a new cid cid = '{}{}'.format(self.cid_prefix, new_cid()) # Get the contents of our request .. request = env['wsgi.input'].read() # .. this is where we expect to find Basic Auth credentials .. credentials = env.get('HTTP_AUTHORIZATION') or '' # .. if there was any, invoke the business function .. if request: response = self.handle_api_request(request, credentials) # If we are here, it means that there was no exception status_text = Common_IPC.Status_OK status_code = StatusCode.OK except Exception: # We are here because there was an exception logger.warning(format_exc()) status_text = 'error' status_code = StatusCode.InternalError finally: # Build our response .. return_data:'any_' = { 'cid': cid, 'status': status_text, 'response': response } # .. make sure that we return bytes representing a JSON object .. return_data = dumps(return_data) return_data = return_data.encode('utf8') start_response(status_code, headers) return [return_data] # ################################################################################################################################ # ################################################################################################################################
18,724
Python
.py
366
41.882514
130
0.509132
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,591
client.py
zatosource_zato/code/zato-common/src/zato/common/ipc/client.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from json import dumps, loads # requests from requests import post as requests_post # Zato from zato.common.api import IPC as Common_IPC from zato.common.broker_message import SERVER_IPC from zato.common.util.config import get_url_protocol_from_config_item from zato.common.typing_ import dataclass # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, anylist # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class IPCResponseMeta: cid: 'str' is_ok: 'bool' service: 'str' request: 'any_' cluster_name: 'str' server_name: 'str' server_pid: 'int' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class IPCResponse: data: 'anydict | anylist | None' meta: 'IPCResponseMeta' # ################################################################################################################################ # ################################################################################################################################ class IPCClient: def __init__( self, use_tls: 'bool', host: 'str', port: 'int', username: 'str', password: 'str', ) -> 'None': self.api_protocol = get_url_protocol_from_config_item(use_tls) self.host = host self.port = port self.username = username self.password = password # ################################################################################################################################ def invoke( self, service, # type: str request, # type: any_ url_path, # type: str *, cluster_name, # type: str server_name, # type: str server_pid, # type: int timeout=90, # type: int source_server_name, # type: str source_server_pid, # type: int ) -> 'IPCResponse': # This is where we can find the IPC server to invoke .. url = f'{self.api_protocol}://{self.host}:{self.port}/{url_path}' # .. prepare the full request .. dict_data = { 'source_server_name': source_server_name, 'source_server_pid': source_server_pid, 'action': SERVER_IPC.INVOKE.value, 'service': service, 'data': request, } # .. serialize it into JSON .. data = dumps(dict_data) # .. build query string parameters to be used in the call .. params = { '_source_server_name': source_server_name, '_source_server_pid': source_server_pid, } # .. append the business data too but skip selected ones .. for key, value in (request or {}).items(): # .. skip selected keys .. for name in ['password', 'secret', 'token']: if name in key: include_value = False break else: include_value = True # .. append the keys with values depending on whether we want to pass them on or not .. value = value if include_value else '******' # .. make sure there is not too much information to keep the query string short .. if isinstance(value, str): value = value[:30] # .. now, do append the new item .. if False: params[key] = value # .. build our credentials .. auth = (self.username, self.password) # .. invoke the server .. response = requests_post(url, data, params=params, auth=auth) # .. de-serialize the response .. response = loads(response.text) ipc_response = IPCResponse() ipc_response.data = response['response'] or None ipc_response.meta = IPCResponseMeta() ipc_response.meta.cid = response['cid'] ipc_response.meta.is_ok = response['status'] == Common_IPC.Status_OK ipc_response.meta.cluster_name = cluster_name ipc_response.meta.server_name = server_name ipc_response.meta.server_pid = server_pid # .. and return its response. return ipc_response # ################################################################################################################################ def main(): # stdlib import logging log_format = '%(asctime)s - %(levelname)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format) logger = logging.getLogger(__name__) host = '127.0.0.1' port = 17050 username = 'test.username' password = 'test.password' service = 'pub.zato.ping' request = {'Hello': 'World'} client = IPCClient(False, host, port, username, password) response = client.invoke(service, request) logger.info('Response -> %s', response) # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
6,188
Python
.py
136
38.191176
130
0.423243
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,592
api.py
zatosource_zato/code/zato-common/src/zato/common/ipc/api.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging # Zato from zato.common.api import IPC from zato.common.ipc.client import IPCClient from zato.common.ipc.server import IPCServer from zato.common.util.api import fs_safe_name, load_ipc_pid_port # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.ipc.client import IPCResponse from zato.common.typing_ import callable_ from zato.server.base.parallel import ParallelServer # ################################################################################################################################ # ################################################################################################################################ logger = logging.getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class IPCAPI: """ API through which IPC is performed. """ pid: 'int' parallel_server: 'ParallelServer' username: 'str' password: 'str' on_message_callback: 'callable_' def __init__(self, parallel_server:'ParallelServer') -> 'None': self.parallel_server = parallel_server self.username = IPC.Credentials.Username self.password = '' # ################################################################################################################################ def set_password(self, password:'str') -> 'None': self.password = password # ################################################################################################################################ def start_server( self, pid, # type: str base_dir, # type: str *, bind_host='', # type: str bind_port=-1, # type: int username='', # type: str password='', # type: str callback_func, # type: callable_ ) -> 'None': username = username or self.username password = password or self.password server_type_suffix = f':{pid}' IPCServer.start( base_dir=base_dir, bind_host=bind_host, bind_port=bind_port, username=username, password=password, callback_func=callback_func, server_type_suffix=server_type_suffix ) # ################################################################################################################################ def invoke_by_pid( self, use_tls, # type: bool service, # type: str request, # type: str cluster_name, # type: str server_name, # type: str target_pid, # type: int timeout=90 # type: int ) -> 'IPCResponse': """ Invokes a service in a specific process synchronously through IPC. """ # This is constant ipc_host = '127.0.0.1' # Get the port that we can find the PID listening on ipc_port = load_ipc_pid_port(cluster_name, server_name, target_pid) # Log what we are about to do log_msg = f'Invoking {service} on {cluster_name}:{server_name}:{target_pid}-tcp:{ipc_port}' logger.debug(log_msg) # Use this URL path to be able to easily find requests in logs url_path = f'{cluster_name}:{server_name}:{target_pid}-tcp:{ipc_port}-service:{service}' url_path = fs_safe_name(url_path) client = IPCClient(use_tls, ipc_host, ipc_port, IPC.Credentials.Username, self.password) response = client.invoke( service, request, url_path, cluster_name=cluster_name, server_name=server_name, server_pid=target_pid, timeout=timeout, source_server_name=self.parallel_server.name, source_server_pid=self.parallel_server.pid, ) return response # ################################################################################################################################ # ################################################################################################################################
4,684
Python
.py
100
39.66
130
0.416849
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,593
__init__.py
zatosource_zato/code/zato-common/src/zato/common/ipc/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,594
server.py
zatosource_zato/code/zato-common/src/zato/common/ipc/server.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import getLogger # Zato from zato.common.aux_server.base import AuxServer, AuxServerConfig from zato.common.crypto.api import ServerCryptoManager # ################################################################################################################################ # ################################################################################################################################ if 0: from bunch import Bunch from zato.common.typing_ import callable_ # ################################################################################################################################ # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class IPCServerConfig(AuxServerConfig): ipc_port: 'int' # ################################################################################################################################ # ################################################################################################################################ class IPCServer(AuxServer): callback_func: 'callable_' needs_logging_setup = False cid_prefix = 'zipc' server_type = 'IPCServer' conf_file_name = 'server.conf' config_class = AuxServerConfig crypto_manager_class = ServerCryptoManager def on_ipc_msg_SERVER_IPC_INVOKE(self, msg:'Bunch') -> 'str': return self.config.callback_func(msg) # ################################################################################################################################ def get_action_func_impl(self, action_name:'str') -> 'callable_': func_name = 'on_ipc_msg_{}'.format(action_name) func = getattr(self, func_name) return func # ################################################################################################################################ # ################################################################################################################################ def main(): # stdlib import logging import os log_format = '%(asctime)s - %(levelname)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format) def my_callback(msg:'Bunch') -> 'str': return 'Hello' bind_host = '127.0.0.1' bind_port = 17050 base_dir = os.environ['Zato_Test_Server_Root_Dir'] username = 'test.username' password = 'test.password' server_type_suffix = ':test' IPCServer.start( base_dir=base_dir, bind_host=bind_host, bind_port=bind_port, username=username, password=password, callback_func=my_callback, server_type_suffix=server_type_suffix ) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
3,799
Python
.py
70
50
130
0.317765
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,595
spring_.py
zatosource_zato/code/zato-common/src/zato/common/py23_/spring_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Python 2/3 compatibility from six import PY2 # ################################################################################################################################ # ################################################################################################################################ """ Copyright 2006-2011 SpringSource (http://springsource.com), All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # ################################################################################################################################ # ################################################################################################################################ # stdlib import http.client as http_client import socket import ssl class CAValidatingHTTPSConnection(http_client.HTTPConnection): """ This class allows communication via SSL/TLS and takes Certificate Authorities into account. """ def __init__(self, host, port=None, ca_certs=None, keyfile=None, certfile=None, cert_reqs=None, strict=None, ssl_version=None, timeout=None): http_client.HTTPConnection.__init__(self, host, port, strict, timeout) self.ca_certs = ca_certs self.keyfile = keyfile self.certfile = certfile self.cert_reqs = cert_reqs self.ssl_version = ssl_version def connect(self): """ Connect to a host on a given (SSL/TLS) port. """ sock = socket.create_connection((self.host, self.port), self.timeout) if self._tunnel_host: self.sock = sock self._tunnel() self.sock = self.wrap_socket(sock) def wrap_socket(self, sock): """ Gets a socket object and wraps it into an SSL/TLS-aware one. May be overridden in subclasses if the wrapping process needs to be customized. """ return ssl.wrap_socket(sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version) class CAValidatingHTTPS(http_client.HTTPConnection): """ A subclass of http.client.HTTPConnection which is aware of Certificate Authorities used in SSL/TLS transactions. """ _connection_class = CAValidatingHTTPSConnection def __init__(self, host=None, port=None, strict=None, ca_certs=None, keyfile=None, certfile=None, cert_reqs=None, ssl_version=None, timeout=None): self._setup(self._connection_class(host, port, ca_certs, keyfile, certfile, cert_reqs, strict, ssl_version, timeout)) # ################################################################################################################################ # ################################################################################################################################ """ Copyright 2006-2011 SpringSource (http://springsource.com), All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # stdlib import logging import sys import traceback if PY2: from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler from xmlrpclib import ServerProxy, Transport else: from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler from xmlrpc.client import ServerProxy, Transport class VerificationException(Exception): """ Raised when the verification of a certificate's fields fails. """ # ############################################################################## # Server # ############################################################################## class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ("/", "/RPC2",) def setup(self): self.connection = self.request # for doPOST self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) class SSLServer(SimpleXMLRPCServer): def __init__(self, host=None, port=None, keyfile=None, certfile=None, ca_certs=None, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None, log_requests=True, **kwargs): if PY2: SimpleXMLRPCServer.__init__(self, (host, port), requestHandler=RequestHandler) else: SimpleXMLRPCServer.__init__(self, (host, port)) self.keyfile = keyfile self.certfile = certfile self.ca_certs = ca_certs self.cert_reqs = cert_reqs self.ssl_version = ssl_version self.do_handshake_on_connect = do_handshake_on_connect self.suppress_ragged_eofs = suppress_ragged_eofs self.ciphers = ciphers # Looks awkward to use camelCase here but that's what SimpleXMLRPCRequestHandler # expects. self.logRequests = log_requests # 'verify_fields' is taken from kwargs to allow for adding more keywords # in future versions. self.verify_fields = kwargs.get("verify_fields") def get_request(self): """ Overridden from SocketServer.TCPServer.get_request, wraps the socket in an SSL context. """ sock, from_addr = self.socket.accept() # 'ciphers' argument is new in 2.7 and we must support 2.6 so add it # to kwargs conditionally, depending on the Python version. kwargs = { "keyfile":self.keyfile, "certfile":self.certfile, "server_side":True, "cert_reqs":self.cert_reqs, "ssl_version":self.ssl_version, "ca_certs":self.ca_certs, "do_handshake_on_connect":self.do_handshake_on_connect, "suppress_ragged_eofs":self.suppress_ragged_eofs } if sys.version_info >= (2, 7): kwargs["ciphers"] = self.ciphers sock = ssl.wrap_socket(sock, **kwargs) if self.logger.isEnabledFor(logging.DEBUG): self.logger.debug("get_request cert='%s', from_addr='%s'" % (sock.getpeercert(), from_addr)) return sock, from_addr def verify_request(self, sock, from_addr): """ Overridden from SocketServer.TCPServer.verify_request, adds validation of the other side's certificate fields. """ try: if self.verify_fields: cert = sock.getpeercert() if not cert: msg = "Couldn't verify fields, peer didn't send the certificate, from_addr='%s'" % (from_addr,) raise VerificationException(msg) allow_peer, reason = self.verify_peer(cert, from_addr) if not allow_peer: self.logger.error(reason) sock.close() return False except Exception: # It was either an error on our side or the client didn't send the # certificate even though self.cert_reqs was CERT_OPTIONAL (it couldn't # have been CERT_REQUIRED because we wouldn't have got so far, the # session would've been terminated much earlier in ssl.wrap_socket call). # Regardless of the reason we cannot accept the client in that case. msg = "Verification error='%s', cert='%s', from_addr='%s'" % ( traceback.format_exc(), sock.getpeercert(), from_addr) self.logger.error(msg) sock.close() return False return True def verify_peer(self, cert, from_addr): """ Verifies the other side's certificate. May be overridden in subclasses if the verification process needs to be customized. """ subject = cert.get("subject") if not subject: msg = "Peer certificate doesn't have the 'subject' field, cert='%s'" % cert raise VerificationException(msg) subject = dict(elem[0] for elem in subject) for verify_field in self.verify_fields: expected_value = self.verify_fields[verify_field] cert_value = subject.get(verify_field, None) if not cert_value: reason = "Peer didn't send the '%s' field, subject fields received '%s'" % ( verify_field, subject) return False, reason if expected_value != cert_value: reason = "Expected the subject field '%s' to have value '%s' instead of '%s', subject='%s'" % ( verify_field, expected_value, cert_value, subject) return False, reason return True, None def register_functions(self): raise NotImplementedError("Must be overridden by subclasses") # ############################################################################## # Client # ############################################################################## class SSLClientTransport(Transport): """ Handles an HTTPS transaction to an XML-RPC server. """ user_agent = "SSL XML-RPC Client (by http://springpython.webfactional.com)" def __init__(self, ca_certs=None, keyfile=None, certfile=None, cert_reqs=None, ssl_version=None, timeout=None, strict=None): self.ca_certs = ca_certs self.keyfile = keyfile self.certfile = certfile self.cert_reqs = cert_reqs self.ssl_version = ssl_version self.timeout = timeout self.strict = strict Transport.__init__(self) def make_connection(self, host): return CAValidatingHTTPS(host, strict=self.strict, ca_certs=self.ca_certs, keyfile=self.keyfile, certfile=self.certfile, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, timeout=self.timeout) class SSLClient(ServerProxy): def __init__(self, uri=None, ca_certs=None, keyfile=None, certfile=None, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1, transport=None, encoding=None, verbose=0, allow_none=0, use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, strict=None): if not transport: _transport=SSLClientTransport(ca_certs, keyfile, certfile, cert_reqs, ssl_version, timeout, strict) else: _transport=transport(ca_certs, keyfile, certfile, cert_reqs, ssl_version, timeout, strict) ServerProxy.__init__(self, uri, _transport, encoding, verbose, allow_none, use_datetime) self.logger = logging.getLogger(self.__class__.__name__) # ################################################################################################################################ # ################################################################################################################################
12,127
Python
.py
231
43.337662
130
0.573869
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,596
__init__.py
zatosource_zato/code/zato-common/src/zato/common/py23_/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import sys from threading import Thread # Python2/3 compatibility from zato.common.ext.future.utils import PY2 if PY2: maxint = sys.maxint from itertools import ifilter from itertools import izip from cPickle import dumps as pickle_dumps from cPickle import loads as pickle_loads else: maxint = sys.maxsize ifilter = filter izip = zip from pickle import dumps as pickle_dumps from pickle import loads as pickle_loads # For pyflakes maxint = maxint ifilter = ifilter izip = izip pickle_dumps = pickle_dumps pickle_loads = pickle_loads def start_new_thread(target, args): return Thread(target=target, args=args).start()
914
Python
.py
31
26.806452
82
0.76
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,597
__init__.py
zatosource_zato/code/zato-common/src/zato/common/py23_/past/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ """ Copyright (c) 2013-2019 Python Charmers Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # ################################################################################################################################ # ################################################################################################################################ """ past: compatibility with Python 2 from Python 3 =============================================== ``past`` is a package to aid with Python 2/3 compatibility. Whereas ``future`` contains backports of Python 3 constructs to Python 2, ``past`` provides implementations of some Python 2 constructs in Python 3 and tools to import and run Python 2 code in Python 3. It is intended to be used sparingly, as a way of running old Python 2 code from Python 3 until the code is ported properly. Potential uses for libraries: - as a step in porting a Python 2 codebase to Python 3 (e.g. with the ``futurize`` script) - to provide Python 3 support for previously Python 2-only libraries with the same APIs as on Python 2 -- particularly with regard to 8-bit strings (the ``past.builtins.str`` type). - to aid in providing minimal-effort Python 3 support for applications using libraries that do not yet wish to upgrade their code properly to Python 3, or wish to upgrade it gradually to Python 3 style. Here are some code examples that run identically on Python 3 and 2:: >>> from zato.common.py23_.past.builtins import str as oldstr >>> philosopher = oldstr(u'\u5b54\u5b50'.encode('utf-8')) >>> # This now behaves like a Py2 byte-string on both Py2 and Py3. >>> # For example, indexing returns a Python 2-like string object, not >>> # an integer: >>> philosopher[0] '\xe5' >>> type(philosopher[0]) <past.builtins.oldstr> >>> # List-producing versions of range, reduce, map, filter >>> from zato.common.py23_.past.builtins import range, reduce >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 15 >>> # Other functions removed in Python 3 are resurrected ... >>> from zato.common.py23_.past.builtins import execfile >>> execfile('myfile.py') >>> from zato.common.py23_.past.builtins import raw_input >>> name = raw_input('What is your name? ') What is your name? [cursor] >>> from zato.common.py23_.past.builtins import reload >>> reload(mymodule) # equivalent to imp.reload(mymodule) in Python 3 >>> from zato.common.py23_.past.builtins import xrange >>> for i in xrange(10): ... pass It also provides import hooks so you can import and use Python 2 modules like this:: $ python3 >>> from zato.common.py23_.past.translation import autotranslate >>> authotranslate('mypy2module') >>> import mypy2module until the authors of the Python 2 modules have upgraded their code. Then, for example:: >>> mypy2module.func_taking_py2_string(oldstr(b'abcd')) Credits ------- :Author: Ed Schofield, Jordan M. Adler, et al :Sponsor: Python Charmers Pty Ltd, Australia: http://pythoncharmers.com Licensing --------- Copyright 2013-2019 Python Charmers Pty Ltd, Australia. The software is distributed under an MIT licence. See LICENSE.txt. """ __title__ = 'past' __author__ = 'Ed Schofield'
4,743
Python
.py
90
49.855556
130
0.646893
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,598
__init__.py
zatosource_zato/code/zato-common/src/zato/common/py23_/past/translation/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ """ Copyright (c) 2013-2019 Python Charmers Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # ################################################################################################################################ # ################################################################################################################################ """ past.translation ================== The ``past.translation`` package provides an import hook for Python 3 which transparently runs ``futurize`` fixers over Python 2 code on import to convert print statements into functions, etc. It is intended to assist users in migrating to Python 3.x even if some dependencies still only support Python 2.x. Usage ----- Once your Py2 package is installed in the usual module search path, the import hook is invoked as follows: >>> from zato.common.py23_.past.translation import autotranslate >>> autotranslate('mypackagename') Or: >>> autotranslate(['mypackage1', 'mypackage2']) You can unregister the hook using:: >>> from zato.common.py23_.past.translation import remove_hooks >>> remove_hooks() Author: Ed Schofield. Inspired by and based on ``uprefix`` by Vinay M. Sajip. """ import imp import logging import marshal import os import sys import copy from lib2to3.pgen2.parse import ParseError from lib2to3.refactor import RefactoringTool from libfuturize import fixes logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) myfixes = (list(fixes.libfuturize_fix_names_stage1) + list(fixes.lib2to3_fix_names_stage1) + list(fixes.libfuturize_fix_names_stage2) + list(fixes.lib2to3_fix_names_stage2)) # We detect whether the code is Py2 or Py3 by applying certain lib2to3 fixers # to it. If the diff is empty, it's Python 3 code. py2_detect_fixers = [ # From stage 1: 'lib2to3.fixes.fix_apply', # 'lib2to3.fixes.fix_dict', # TODO: add support for utils.viewitems() etc. and move to stage2 'lib2to3.fixes.fix_except', 'lib2to3.fixes.fix_execfile', 'lib2to3.fixes.fix_exitfunc', 'lib2to3.fixes.fix_funcattrs', 'lib2to3.fixes.fix_filter', 'lib2to3.fixes.fix_has_key', 'lib2to3.fixes.fix_idioms', 'lib2to3.fixes.fix_import', # makes any implicit relative imports explicit. (Use with ``from __future__ import absolute_import) 'lib2to3.fixes.fix_intern', 'lib2to3.fixes.fix_isinstance', 'lib2to3.fixes.fix_methodattrs', 'lib2to3.fixes.fix_ne', 'lib2to3.fixes.fix_numliterals', # turns 1L into 1, 0755 into 0o755 'lib2to3.fixes.fix_paren', 'lib2to3.fixes.fix_print', 'lib2to3.fixes.fix_raise', # uses incompatible with_traceback() method on exceptions 'lib2to3.fixes.fix_renames', 'lib2to3.fixes.fix_reduce', # 'lib2to3.fixes.fix_set_literal', # this is unnecessary and breaks Py2.6 support 'lib2to3.fixes.fix_repr', 'lib2to3.fixes.fix_standarderror', 'lib2to3.fixes.fix_sys_exc', 'lib2to3.fixes.fix_throw', 'lib2to3.fixes.fix_tuple_params', 'lib2to3.fixes.fix_types', 'lib2to3.fixes.fix_ws_comma', 'lib2to3.fixes.fix_xreadlines', # From stage 2: 'lib2to3.fixes.fix_basestring', # 'lib2to3.fixes.fix_buffer', # perhaps not safe. Test this. # 'lib2to3.fixes.fix_callable', # not needed in Py3.2+ # 'lib2to3.fixes.fix_dict', # TODO: add support for utils.viewitems() etc. 'lib2to3.fixes.fix_exec', # 'lib2to3.fixes.fix_future', # we don't want to remove __future__ imports 'lib2to3.fixes.fix_getcwdu', # 'lib2to3.fixes.fix_imports', # called by libfuturize.fixes.fix_future_standard_library # 'lib2to3.fixes.fix_imports2', # we don't handle this yet (dbm) # 'lib2to3.fixes.fix_input', # 'lib2to3.fixes.fix_itertools', # 'lib2to3.fixes.fix_itertools_imports', 'lib2to3.fixes.fix_long', # 'lib2to3.fixes.fix_map', # 'lib2to3.fixes.fix_metaclass', # causes SyntaxError in Py2! Use the one from ``six`` instead 'lib2to3.fixes.fix_next', 'lib2to3.fixes.fix_nonzero', # TODO: add a decorator for mapping __bool__ to __nonzero__ # 'lib2to3.fixes.fix_operator', # we will need support for this by e.g. extending the Py2 operator module to provide those functions in Py3 'lib2to3.fixes.fix_raw_input', # 'lib2to3.fixes.fix_unicode', # strips off the u'' prefix, which removes a potentially helpful source of information for disambiguating unicode/byte strings # 'lib2to3.fixes.fix_urllib', 'lib2to3.fixes.fix_xrange', # 'lib2to3.fixes.fix_zip', ] class RTs: """ A namespace for the refactoring tools. This avoids creating these at the module level, which slows down the module import. (See issue #117). There are two possible grammars: with or without the print statement. Hence we have two possible refactoring tool implementations. """ _rt = None _rtp = None _rt_py2_detect = None _rtp_py2_detect = None @staticmethod def setup(): """ Call this before using the refactoring tools to create them on demand if needed. """ if None in [RTs._rt, RTs._rtp]: RTs._rt = RefactoringTool(myfixes) RTs._rtp = RefactoringTool(myfixes, {'print_function': True}) @staticmethod def setup_detect_python2(): """ Call this before using the refactoring tools to create them on demand if needed. """ if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]: RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers) RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers, {'print_function': True}) # We need to find a prefix for the standard library, as we don't want to # process any files there (they will already be Python 3). # # The following method is used by Sanjay Vinip in uprefix. This fails for # ``conda`` environments: # # In a non-pythonv virtualenv, sys.real_prefix points to the installed Python. # # In a pythonv venv, sys.base_prefix points to the installed Python. # # Outside a virtual environment, sys.prefix points to the installed Python. # if hasattr(sys, 'real_prefix'): # _syslibprefix = sys.real_prefix # else: # _syslibprefix = getattr(sys, 'base_prefix', sys.prefix) # Instead, we use the portion of the path common to both the stdlib modules # ``math`` and ``urllib``. def splitall(path): """ Split a path into all components. From Python Cookbook. """ allparts = [] while True: parts = os.path.split(path) if parts[0] == path: # sentinel for absolute paths allparts.insert(0, parts[0]) break elif parts[1] == path: # sentinel for relative paths allparts.insert(0, parts[1]) break else: path = parts[0] allparts.insert(0, parts[1]) return allparts def common_substring(s1, s2): """ Returns the longest common substring to the two strings, starting from the left. """ chunks = [] path1 = splitall(s1) path2 = splitall(s2) for (dir1, dir2) in zip(path1, path2): if dir1 != dir2: break chunks.append(dir1) return os.path.join(*chunks) # _stdlibprefix = common_substring(math.__file__, urllib.__file__) def detect_python2(source, pathname): """ Returns a bool indicating whether we think the code is Py2 """ RTs.setup_detect_python2() try: tree = RTs._rt_py2_detect.refactor_string(source, pathname) except ParseError as e: if e.msg != 'bad input' or e.value != '=': raise tree = RTs._rtp.refactor_string(source, pathname) if source != str(tree)[:-1]: # remove added newline # The above fixers made changes, so we conclude it's Python 2 code logger.debug('Detected Python 2 code: {0}'.format(pathname)) return True else: logger.debug('Detected Python 3 code: {0}'.format(pathname)) return False class Py2Fixer(object): """ An import hook class that uses lib2to3 for source-to-source translation of Py2 code to Py3. """ # See the comments on :class:future.standard_library.RenameImport. # We add this attribute here so remove_hooks() and install_hooks() can # unambiguously detect whether the import hook is installed: PY2FIXER = True def __init__(self): self.found = None self.base_exclude_paths = ['future', 'past'] self.exclude_paths = copy.copy(self.base_exclude_paths) self.include_paths = [] def include(self, paths): """ Pass in a sequence of module names such as 'plotrique.plotting' that, if present at the leftmost side of the full package name, would specify the module to be transformed from Py2 to Py3. """ self.include_paths += paths def exclude(self, paths): """ Pass in a sequence of strings such as 'mymodule' that, if present at the leftmost side of the full package name, would cause the module not to undergo any source transformation. """ self.exclude_paths += paths def find_module(self, fullname, path=None): logger.debug('Running find_module: {0}...'.format(fullname)) if '.' in fullname: parent, child = fullname.rsplit('.', 1) if path is None: loader = self.find_module(parent, path) mod = loader.load_module(parent) path = mod.__path__ fullname = child # Perhaps we should try using the new importlib functionality in Python # 3.3: something like this? # thing = importlib.machinery.PathFinder.find_module(fullname, path) try: self.found = imp.find_module(fullname, path) except Exception as e: logger.debug('Py2Fixer could not find {0}') logger.debug('Exception was: {0})'.format(fullname, e)) return None self.kind = self.found[-1][-1] if self.kind == imp.PKG_DIRECTORY: self.pathname = os.path.join(self.found[1], '__init__.py') elif self.kind == imp.PY_SOURCE: self.pathname = self.found[1] return self def transform(self, source): # This implementation uses lib2to3, # you can override and use something else # if that's better for you # lib2to3 likes a newline at the end RTs.setup() source += '\n' try: tree = RTs._rt.refactor_string(source, self.pathname) except ParseError as e: if e.msg != 'bad input' or e.value != '=': raise tree = RTs._rtp.refactor_string(source, self.pathname) # could optimise a bit for only doing str(tree) if # getattr(tree, 'was_changed', False) returns True return str(tree)[:-1] # remove added newline def load_module(self, fullname): logger.debug('Running load_module for {0}...'.format(fullname)) if fullname in sys.modules: mod = sys.modules[fullname] else: if self.kind in (imp.PY_COMPILED, imp.C_EXTENSION, imp.C_BUILTIN, imp.PY_FROZEN): convert = False # elif (self.pathname.startswith(_stdlibprefix) # and 'site-packages' not in self.pathname): # # We assume it's a stdlib package in this case. Is this too brittle? # # Please file a bug report at https://github.com/PythonCharmers/python-future # # if so. # convert = False # in theory, other paths could be configured to be excluded here too elif any(fullname.startswith(path) for path in self.exclude_paths): convert = False elif any(fullname.startswith(path) for path in self.include_paths): convert = True else: convert = False if not convert: logger.debug('Excluded {0} from translation'.format(fullname)) mod = imp.load_module(fullname, *self.found) else: logger.debug('Autoconverting {0} ...'.format(fullname)) mod = imp.new_module(fullname) sys.modules[fullname] = mod # required by PEP 302 mod.__file__ = self.pathname mod.__name__ = fullname mod.__loader__ = self # This: # mod.__package__ = '.'.join(fullname.split('.')[:-1]) # seems to result in "SystemError: Parent module '' not loaded, # cannot perform relative import" for a package's __init__.py # file. We use the approach below. Another option to try is the # minimal load_module pattern from the PEP 302 text instead. # Is the test in the next line more or less robust than the # following one? Presumably less ... # ispkg = self.pathname.endswith('__init__.py') if self.kind == imp.PKG_DIRECTORY: mod.__path__ = [ os.path.dirname(self.pathname) ] mod.__package__ = fullname else: #else, regular module mod.__path__ = [] mod.__package__ = fullname.rpartition('.')[0] try: cachename = imp.cache_from_source(self.pathname) if not os.path.exists(cachename): update_cache = True else: sourcetime = os.stat(self.pathname).st_mtime cachetime = os.stat(cachename).st_mtime update_cache = cachetime < sourcetime # # Force update_cache to work around a problem with it being treated as Py3 code??? # update_cache = True if not update_cache: with open(cachename, 'rb') as f: data = f.read() try: code = marshal.loads(data) except Exception: # pyc could be corrupt. Regenerate it update_cache = True if update_cache: if self.found[0]: source = self.found[0].read() elif self.kind == imp.PKG_DIRECTORY: with open(self.pathname) as f: source = f.read() if detect_python2(source, self.pathname): source = self.transform(source) code = compile(source, self.pathname, 'exec') dirname = os.path.dirname(cachename) try: if not os.path.exists(dirname): os.makedirs(dirname) with open(cachename, 'wb') as f: data = marshal.dumps(code) f.write(data) except Exception: # could be write-protected pass exec(code, mod.__dict__) except Exception as e: # must remove module from sys.modules del sys.modules[fullname] raise # keep it simple if self.found[0]: self.found[0].close() return mod _hook = Py2Fixer() def install_hooks(include_paths=(), exclude_paths=()): if isinstance(include_paths, str): include_paths = (include_paths,) if isinstance(exclude_paths, str): exclude_paths = (exclude_paths,) assert len(include_paths) + len(exclude_paths) > 0, 'Pass at least one argument' _hook.include(include_paths) _hook.exclude(exclude_paths) # _hook.debug = debug enable = sys.version_info[0] >= 3 # enabled for all 3.x+ if enable and _hook not in sys.meta_path: sys.meta_path.insert(0, _hook) # insert at beginning. This could be made a parameter # We could return the hook when there are ways of configuring it #return _hook def remove_hooks(): if _hook in sys.meta_path: sys.meta_path.remove(_hook) def detect_hooks(): """ Returns True if the import hooks are installed, False if not. """ return _hook in sys.meta_path # present = any([hasattr(hook, 'PY2FIXER') for hook in sys.meta_path]) # return present class hooks(object): """ Acts as a context manager. Use like this: >>> from zato.common.py23_.past import translation >>> with translation.hooks(): ... import mypy2module >>> import requests # py2/3 compatible anyway >>> # etc. """ def __enter__(self): self.hooks_were_installed = detect_hooks() install_hooks() return self def __exit__(self, *args): if not self.hooks_were_installed: remove_hooks() class suspend_hooks(object): """ Acts as a context manager. Use like this: >>> from zato.common.py23_.past import translation >>> translation.install_hooks() >>> import http.client >>> # ... >>> with translation.suspend_hooks(): >>> import requests # or others that support Py2/3 If the hooks were disabled before the context, they are not installed when the context is left. """ def __enter__(self): self.hooks_were_installed = detect_hooks() remove_hooks() return self def __exit__(self, *args): if self.hooks_were_installed: install_hooks() # alias autotranslate = install_hooks
19,464
Python
.py
437
35.585812
163
0.598216
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
10,599
__init__.py
zatosource_zato/code/zato-common/src/zato/common/py23_/past/utils/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ """ Copyright (c) 2013-2019 Python Charmers Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # ################################################################################################################################ # ################################################################################################################################ """ Various non-built-in utility functions and definitions for Py2 compatibility in Py3. For example: >>> # The old_div() function behaves like Python 2's / operator >>> # without "from __future__ import division" >>> from zato.common.py23_.past.utils import old_div >>> old_div(3, 2) # like 3/2 in Py2 0 >>> old_div(3, 2.0) # like 3/2.0 in Py2 1.5 """ import sys import numbers PY3 = sys.version_info[0] >= 3 PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') def with_metaclass(meta, *bases): """ Function from jinja2/_compat.py. License: BSD. Use it like this:: class BaseForm(object): pass class FormType(type): pass class Form(with_metaclass(FormType, BaseForm)): pass This requires a bit of explanation: the basic idea is to make a dummy metaclass for one level of class instantiation that replaces itself with the actual metaclass. Because of internal type checks we also need to make sure that we downgrade the custom metaclass for one level to something closer to type (that's why __call__ and __init__ comes back from type etc.). This has the advantage over six.with_metaclass of not introducing dummy classes into the final MRO. """ class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) def native(obj): """ On Py2, this is a no-op: native(obj) -> obj On Py3, returns the corresponding native Py3 types that are superclasses for forward-ported objects from Py2: >>> from zato.common.py23_.past.builtins import str, dict >>> native(str(b'ABC')) # Output on Py3 follows. On Py2, output is 'ABC' b'ABC' >>> type(native(str(b'ABC'))) bytes Existing native types on Py3 will be returned unchanged: >>> type(native(b'ABC')) bytes """ if hasattr(obj, '__native__'): return obj.__native__() else: return obj # An alias for future.utils.old_div(): def old_div(a, b): """ Equivalent to ``a / b`` on Python 2 without ``from __future__ import division``. TODO: generalize this to other objects (like arrays etc.) """ if isinstance(a, numbers.Integral) and isinstance(b, numbers.Integral): return a // b else: return a / b __all__ = ['PY3', 'PY2', 'PYPY', 'with_metaclass', 'native', 'old_div']
4,443
Python
.py
101
39.415842
130
0.603852
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)