desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Return CORS headers for preflight requests'
| def options(self, *args, **kwargs):
| request_headers = self.request.headers.get('Access-Control-Request-Headers')
allowed_headers = request_headers.split(',')
self.set_header('Access-Control-Allow-Headers', ','.join(allowed_headers))
self.set_header('Access-Control-Expose-Headers', 'X-Auth-Token')
self.set_header('Access-Control-Allow-... |
'All logins are done over post, this is a parked enpoint
.. http:get:: /login
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/login
.. code-block:: http
GET /login HTTP/1.1
Host: localhost:8000
Accept: application/json
**Example response:**
.. code-block:: http
HTT... | def get(self):
| self.set_status(401)
self.set_header('WWW-Authenticate', 'Session')
ret = {'status': '401 Unauthorized', 'return': 'Please log in'}
self.write(self.serialize(ret))
|
':ref:`Authenticate <rest_tornado-auth>` against Salt\'s eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend configured for the user
:form username: username
:form password: password
:status 200: |200|
... | def post(self):
| try:
request_payload = self.deserialize(self.request.body)
if (not isinstance(request_payload, dict)):
self.send_error(400)
return
creds = {'username': request_payload['username'], 'password': request_payload['password'], 'eauth': request_payload['eauth']}
except ... |
'An enpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000
.. code-block:: http
GET / HTTP/1.1
Host: localhost:8000
Accept: application/json
**Example response:**... | def get(self):
| ret = {'clients': list(self.saltclients.keys()), 'return': 'Welcome'}
self.write(self.serialize(ret))
|
'Send one or more Salt commands (lowstates) in the request body
.. http:post:: /
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 401: |401|
:status 406: |406|
:term:`lowstate` data describing Salt command... | @tornado.web.asynchronous
def post(self):
| if (not self._verify_auth()):
self.redirect('/login')
return
self.disbatch()
|
'Disbatch all lowstates to the appropriate clients'
| @tornado.gen.coroutine
def disbatch(self):
| ret = []
for low in self.lowstate:
if (not self._verify_client(low)):
return
if ((self.token is not None) and ('token' not in low)):
low['token'] = self.token
if (not (('token' in low) or (('username' in low) and ('password' in low) and ('eauth' in low)))):
... |
'Dispatch local client commands'
| @tornado.gen.coroutine
def _disbatch_local(self, chunk):
| chunk_ret = {}
f_call = self._format_call_run_job_async(chunk)
try:
pub_data = (yield self.saltclients['local'](*f_call.get('args', ()), **f_call.get('kwargs', {})))
except EauthAuthenticationError:
raise tornado.gen.Return('Not authorized to run this job')
if ('jid' n... |
'Return a future which will complete once all returns are completed
(according to minions_remaining), or one of the passed in "finish_futures" completes'
| @tornado.gen.coroutine
def all_returns(self, jid, finish_futures=None, minions_remaining=None):
| if (finish_futures is None):
finish_futures = []
if (minions_remaining is None):
minions_remaining = []
ret_tag = tagify([jid, 'ret'], 'job')
chunk_ret = {}
while True:
ret_event = self.application.event_listener.get_event(self, tag=ret_tag)
f = (yield Any(([ret_event... |
'Return a future which will complete once jid (passed in) is no longer
running on tgt'
| @tornado.gen.coroutine
def job_not_running(self, jid, tgt, tgt_type, minions_remaining=None):
| if (minions_remaining is None):
minions_remaining = []
ping_pub_data = (yield self.saltclients['local'](tgt, 'saltutil.find_job', [jid], tgt_type=tgt_type))
ping_tag = tagify([ping_pub_data['jid'], 'ret'], 'job')
minion_running = False
while True:
try:
event = (yield self... |
'Disbatch local client_async commands'
| @tornado.gen.coroutine
def _disbatch_local_async(self, chunk):
| f_call = self._format_call_run_job_async(chunk)
pub_data = (yield self.saltclients['local_async'](*f_call.get('args', ()), **f_call.get('kwargs', {})))
raise tornado.gen.Return(pub_data)
|
'Disbatch runner client commands'
| @tornado.gen.coroutine
def _disbatch_runner(self, chunk):
| pub_data = self.saltclients['runner'](chunk)
tag = (pub_data['tag'] + '/ret')
try:
event = (yield self.application.event_listener.get_event(self, tag=tag))
raise tornado.gen.Return(event['data']['return'])
except TimeoutException:
raise tornado.gen.Return('Timeout waiting f... |
'Disbatch runner client_async commands'
| @tornado.gen.coroutine
def _disbatch_runner_async(self, chunk):
| pub_data = self.saltclients['runner'](chunk)
raise tornado.gen.Return(pub_data)
|
'A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/minions/ms-3
.. code-block... | @tornado.web.asynchronous
def get(self, mid=None):
| if (not self._verify_auth()):
self.redirect('/login')
return
self.lowstate = [{'client': 'local', 'tgt': (mid or '*'), 'fun': 'grains.items'}]
self.disbatch()
|
'Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 401: |401|
:status 406: |406|
:term:`lowstate` data describing Salt co... | @tornado.web.asynchronous
def post(self):
| if (not self._verify_auth()):
self.redirect('/login')
return
for low in self.lowstate:
if ('client' not in low):
low['client'] = 'local_async'
continue
if (low.get('client') != 'local_async'):
self.set_status(400)
self.write("We ... |
'A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
List jobs or show a single job from the job cache.
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs
.. code-block:: ... | @tornado.web.asynchronous
def get(self, jid=None):
| if (not self._verify_auth()):
self.redirect('/login')
return
if jid:
self.lowstate = [{'fun': 'jobs.list_job', 'jid': jid, 'client': 'runner'}]
else:
self.lowstate = [{'fun': 'jobs.list_jobs', 'client': 'runner'}]
self.disbatch()
|
'Run commands bypassing the :ref:`normal session handling
<rest_cherrypy-auth>`
.. http:post:: /run
This entry point is primarily for "one-off" commands. Each request
must pass full Salt authentication credentials. Otherwise this URL
is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`.
:term:`lowstate` da... | @tornado.web.asynchronous
def post(self):
| self.disbatch()
|
'An HTTP stream of the Salt master event bus
This stream is formatted per the Server Sent Events (SSE) spec. Each
event is formatted as JSON.
.. http:get:: /events
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -NsS localhost:8000/events
.. code-block:: http
GET ... | @tornado.gen.coroutine
def get(self):
| if (not self._verify_auth()):
self.redirect('/login')
return
self.set_header('Content-Type', 'text/event-stream')
self.set_header('Cache-Control', 'no-cache')
self.set_header('Connection', 'keep-alive')
self.write(u'retry: {0}\n'.format(400))
self.flush()
while True:
... |
'Fire an event in Salt with a custom event tag and data
.. http:post:: /hook
:status 200: |200|
:status 401: |401|
:status 406: |406|
:status 413: request body is too large
**Example request:**
.. code-block:: bash
curl -sS localhost:8000/hook -d foo=\'Foo!\' -d bar=\'Bar!\'
.. code-block:: http
POST /hook HTTP/1.1
Hos... | def post(self, tag_suffix=None):
| disable_auth = self.application.mod_opts.get('webhook_disable_auth')
if ((not disable_auth) and (not self._verify_auth())):
self.redirect('/login')
return
tag = 'salt/netapi/hook'
if tag_suffix:
tag += tag_suffix
self.event = salt.utils.event.get_event('master', self.applicat... |
'handler is expected to be the server side end of a websocket
connection.'
| def __init__(self, handler):
| self.handler = handler
self.jobs = {}
self.minions = {}
|
'Publishes minions as a list of dicts.'
| def publish_minions(self):
| logger.debug('in publish minions')
minions = {}
logger.debug('starting loop')
for (minion, minion_info) in six.iteritems(self.minions):
logger.debug(minion)
curr_minion = {}
curr_minion.update(minion_info)
curr_minion.update({'id': minion})
minions[minion... |
'Publishes the data to the event stream.'
| def publish(self, key, data):
| publish_data = {key: data}
pub = u'{0}\n\n'.format(json.dumps(publish_data))
self.handler.write_message(pub)
|
'Associate grains data with a minion and publish minion update'
| def process_minion_update(self, event_data):
| tag = event_data['tag']
event_info = event_data['data']
(_, _, _, _, mid) = tag.split('/')
if (not self.minions.get(mid, None)):
self.minions[mid] = {}
minion = self.minions[mid]
minion.update({'grains': event_info['return']})
logger.debug('In process minion grains update... |
'Process a /ret event returned by Salt for a particular minion.
These events contain the returned results from a particular execution.'
| def process_ret_job_event(self, event_data):
| tag = event_data['tag']
event_info = event_data['data']
(_, _, jid, _, mid) = tag.split('/')
job = self.jobs.setdefault(jid, {})
minion = job.setdefault('minions', {}).setdefault(mid, {})
minion.update({'return': event_info['return']})
minion.update({'retcode': event_info['retcode']})
mi... |
'Creates a new job with properties from the event data
like jid, function, args, timestamp.
Also sets the initial state to started.
Minions that are participating in this job are also noted.'
| def process_new_job_event(self, event_data):
| job = None
tag = event_data['tag']
event_info = event_data['data']
minions = {}
for mid in event_info['minions']:
minions[mid] = {'success': False}
job = {'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, 'fun': event_info['fun'], 'tgt': event_info['tgt'],... |
'Tag: salt/key
Data:
{\'_stamp\': \'2014-05-20T22:45:04.345583\',
\'act\': \'delete\',
\'id\': \'compute.home\',
\'result\': True}'
| def process_key_event(self, event_data):
| tag = event_data['tag']
event_info = event_data['data']
if (event_info['act'] == 'delete'):
self.minions.pop(event_info['id'], None)
elif (event_info['act'] == 'accept'):
self.minions.setdefault(event_info['id'], {})
self.publish_minions()
|
'Check if any minions have connected or dropped.
Send a message to the client if they have.'
| def process_presence_events(self, salt_data, token, opts):
| logger.debug('In presence')
changed = False
if set(salt_data['data'].get('lost', [])):
dropped_minions = set(salt_data['data'].get('lost', []))
else:
dropped_minions = (set(self.minions) - set(salt_data['data'].get('present', [])))
for minion in dropped_minions:
changed = ... |
'Process events and publish data'
| def process(self, salt_data, token, opts):
| logger.debug('In process {0}'.format(threading.current_thread()))
logger.debug(salt_data['tag'])
logger.debug(salt_data)
parts = salt_data['tag'].split('/')
if (len(parts) < 2):
return
if (parts[1] == 'job'):
logger.debug('In job part 1')
if (parts[3] == 'n... |
'Check the token, returns a 401 if the token is invalid.
Else open the websocket connection'
| def get(self, token):
| logger.debug('In the websocket get method')
self.token = token
if (not self.application.auth.get_tok(token)):
logger.debug('Refusing websocket connection, bad token!')
self.send_error(401)
return
super(AllEventsHandler, self).get(token)
|
'Return a websocket connection to Salt
representing Salt\'s "real time" event stream.'
| def open(self, token):
| self.connected = False
|
'Listens for a "websocket client ready" message.
Once that message is received an asynchronous job
is stated that yields messages to the client.
These messages make up salt\'s
"real time" event stream.'
| @tornado.gen.coroutine
def on_message(self, message):
| logger.debug('Got websocket message {0}'.format(message))
if (message == 'websocket client ready'):
if self.connected:
logger.debug('Websocket already connected, returning')
return
self.connected = True
while True:
try:
... |
'Cleanup.'
| def on_close(self, *args, **kwargs):
| logger.debug('In the websocket close method')
self.close()
|
'If cors is enabled, check that the origin is allowed'
| def check_origin(self, origin):
| mod_opts = self.application.mod_opts
if mod_opts.get('cors_origin'):
return bool(_check_cors_origin(origin, mod_opts['cors_origin']))
else:
return super(AllEventsHandler, self).check_origin(origin)
|
'Listens for a "websocket client ready" message.
Once that message is received an asynchronous job
is stated that yields messages to the client.
These messages make up salt\'s
"real time" event stream.'
| @tornado.gen.coroutine
def on_message(self, message):
| logger.debug('Got websocket message {0}'.format(message))
if (message == 'websocket client ready'):
if self.connected:
logger.debug('Websocket already connected, returning')
return
self.connected = True
evt_processor = event_processor.SaltI... |
'Return the primary name associate with the load, if an empty string
is returned then the load does not match the function'
| def load_name(self, load):
| if ('eauth' not in load):
return ''
fstr = '{0}.auth'.format(load['eauth'])
if (fstr not in self.auth):
return ''
try:
pname_arg = salt.utils.arg_lookup(self.auth[fstr])['args'][0]
return load[pname_arg]
except IndexError:
return ''
|
'Return the token and set the cache data for use
Do not call this directly! Use the time_auth method to overcome timing
attacks'
| def __auth_call(self, load):
| if ('eauth' not in load):
return False
fstr = '{0}.auth'.format(load['eauth'])
if (fstr not in self.auth):
return False
fcall = salt.utils.format_call(self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS)
try:
if ('kwargs' in fcall):
return self.auth[f... |
'Make sure that all failures happen in the same amount of time'
| def time_auth(self, load):
| start = time.time()
ret = self.__auth_call(load)
if ret:
return ret
f_time = (time.time() - start)
if (f_time > self.max_fail):
self.max_fail = f_time
deviation = (self.max_fail / 4)
r_time = random.SystemRandom().uniform((self.max_fail - deviation), (self.max_fail + deviatio... |
'Returns ACL for a specific user.
Returns None if eauth doesn\'t provide any for the user. I. e. None means: use acl declared
in master config.'
| def __get_acl(self, load):
| if ('eauth' not in load):
return None
mod = self.opts['eauth_acl_module']
if (not mod):
mod = load['eauth']
fstr = '{0}.acl'.format(mod)
if (fstr not in self.auth):
return None
fcall = salt.utils.format_call(self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS... |
'Allows eauth module to modify the access list right before it\'ll be applied to the request.
For example ldap auth module expands entries'
| def __process_acl(self, load, auth_list):
| if ('eauth' not in load):
return auth_list
fstr = '{0}.process_acl'.format(load['eauth'])
if (fstr not in self.auth):
return auth_list
try:
return self.auth[fstr](auth_list, self.opts)
except Exception as e:
log.debug('Authentication module threw {0}'.format(... |
'Read in a load and return the groups a user is a member of
by asking the appropriate provider'
| def get_groups(self, load):
| if ('eauth' not in load):
return False
fstr = '{0}.groups'.format(load['eauth'])
if (fstr not in self.auth):
return False
fcall = salt.utils.format_call(self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS)
try:
return self.auth[fstr](*fcall['args'], **fcall['kwar... |
'Return bool if requesting user is allowed to set custom expire'
| def _allow_custom_expire(self, load):
| expire_override = self.opts.get('token_expire_user_override', False)
if (expire_override is True):
return True
if isinstance(expire_override, collections.Mapping):
expire_whitelist = expire_override.get(load['eauth'], [])
if isinstance(expire_whitelist, collections.Iterable):
... |
'Run time_auth and create a token. Return False or the token'
| def mk_token(self, load):
| if (not self.authenticate_eauth(load)):
return {}
fstr = '{0}.auth'.format(load['eauth'])
hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5'))
tok = str(hash_type(os.urandom(512)).hexdigest())
t_path = os.path.join(self.opts['token_dir'], tok)
while os.path.isfile(t_path):
... |
'Return the name associated with the token, or False if the token is
not valid'
| def get_tok(self, tok):
| t_path = os.path.join(self.opts['token_dir'], tok)
if (not os.path.isfile(t_path)):
return {}
try:
with salt.utils.files.fopen(t_path, 'rb') as fp_:
tdata = self.serial.loads(fp_.read())
except (IOError, OSError):
log.warning('Authentication failure: can not ... |
'Authenticate a user by the token specified in load.
Return the token object or False if auth failed.'
| def authenticate_token(self, load):
| token = self.get_tok(load['token'])
if ((not token) or (token['eauth'] not in self.opts['external_auth'])):
log.warning('Authentication failure of type "token" occurred.')
return False
return token
|
'Authenticate a user by the external auth module specified in load.
Return True on success or False on failure.'
| def authenticate_eauth(self, load):
| if ('eauth' not in load):
log.warning('Authentication failure of type "eauth" occurred.')
return False
if (load['eauth'] not in self.opts['external_auth']):
log.warning('Authentication failure of type "eauth" occurred.')
return False
if (not self... |
'Authenticate a user by the key passed in load.
Return the effective user id (name) if it\'s differ from the specified one (for sudo).
If the effective user id is the same as passed one return True on success or False on
failure.'
| def authenticate_key(self, load, key):
| auth_key = load.pop('key')
if (not auth_key):
log.warning('Authentication failure of type "user" occurred.')
return False
if ('user' in load):
auth_user = AuthUser(load['user'])
if auth_user.is_sudo():
if (auth_key != key[self.opts.get('user', 'root... |
'Retrieve access list for the user specified in load.
The list is built by eauth module or from master eauth configuration.
Return None if current configuration doesn\'t provide any ACL for the user. Return an empty
list if the user has no rights to execute anything on this master and returns non-empty list
if user is ... | def get_auth_list(self, load):
| auth_list = self.__get_acl(load)
if (auth_list is not None):
return auth_list
if (load['eauth'] not in self.opts['external_auth']):
log.warning('Authorization failure occurred.')
return None
name = self.load_name(load)
groups = self.get_groups(load)
eauth_config = s... |
'Gather and create the authorization data sets
We\'re looking at several constructs here.
Standard eauth: allow jsmith to auth via pam, and execute any command
on server web1
external_auth:
pam:
jsmith:
- web1:
Django eauth: Import the django library, dynamically load the Django
model called \'model\'. That model retu... | @property
def auth_data(self):
| auth_data = self.opts['external_auth']
merge_lists = self.opts['pillar_merge_lists']
if (('django' in auth_data) and ('^model' in auth_data['django'])):
auth_from_django = salt.auth.django.retrieve_auth_entries()
auth_data = salt.utils.dictupdate.merge(auth_data, auth_from_django, strategy='... |
'Determine if token auth is valid and yield the adata'
| def token(self, adata, load):
| try:
token = self.loadauth.get_tok(load['token'])
except Exception as exc:
log.error('Exception occurred when generating auth token: {0}'.format(exc))
(yield {})
if (not token):
log.warning('Authentication failure of type "token" occurred.')
... |
'Determine if the given eauth is valid and yield the adata'
| def eauth(self, adata, load):
| for sub_auth in [adata]:
if (load['eauth'] not in sub_auth):
continue
try:
name = self.loadauth.load_name(load)
if (not ((name in sub_auth[load['eauth']]) | ('*' in sub_auth[load['eauth']]))):
continue
if (not self.loadauth.time_auth(lo... |
'Read in the access system to determine if the validated user has
requested rights'
| def rights_check(self, form, sub_auth, name, load, eauth=None):
| if load.get('eauth'):
sub_auth = sub_auth[load['eauth']]
good = self.ckminions.any_auth(form, (sub_auth[name] if (name in sub_auth) else sub_auth['*']), load.get('fun', None), load.get('arg', None), load.get('tgt', None), load.get('tgt_type', 'glob'))
if (not good):
if (load.get('fun', '') !... |
'Determine what type of authentication is being requested and pass
authorization
Note: this will check that the user has at least one right that will let
him execute "load", this does not deal with conflicting rules'
| def rights(self, form, load):
| adata = self.auth_data
good = False
if load.get('token', False):
for sub_auth in self.token(self.auth_data, load):
if sub_auth:
if self.rights_check(form, self.auth_data[sub_auth['token']['eauth']], sub_auth['token']['name'], load, sub_auth['token']['eauth']):
... |
'Execute the CLI options to fill in the extra data needed for the
defined eauth system'
| def cli(self, eauth):
| ret = {}
if (not eauth):
print('External authentication system has not been specified')
return ret
fstr = '{0}.auth'.format(eauth)
if (fstr not in self.auth):
print('The specified external authentication system "{0}" is not available'.for... |
'Create the token from the CLI and request the correct data to
authenticate via the passed authentication mechanism'
| def token_cli(self, eauth, load):
| load['cmd'] = 'mk_token'
load['eauth'] = eauth
tdata = self._send_token_request(load)
if ('token' not in tdata):
return tdata
try:
with salt.utils.files.set_umask(127):
with salt.utils.files.fopen(self.opts['token_file'], 'w+') as fp_:
fp_.write(tdata['tok... |
'Request a token from the master'
| def mk_token(self, load):
| load['cmd'] = 'mk_token'
tdata = self._send_token_request(load)
return tdata
|
'Request a token from the master'
| def get_token(self, token):
| load = {}
load['token'] = token
load['cmd'] = 'get_token'
tdata = self._send_token_request(load)
return tdata
|
'Instantiate an AuthUser object.
Takes a user to reprsent, as a string.'
| def __init__(self, user):
| self.user = user
|
'Determines if the user is running with sudo
Returns True if the user is running with sudo and False if the
user is not running with sudo'
| def is_sudo(self):
| return self.user.startswith('sudo_')
|
'Determines if the user is the same user as the one running
this process
Returns True if the user is the same user as the one running
this process and False if not.'
| def is_running_user(self):
| return (self.user == salt.utils.get_user())
|
'Returns the username of the sudoer, i.e. self.user without the
\'sudo_\' prefix.'
| def sudo_name(self):
| return self.user.split('_', 1)[(-1)]
|
'Bind to an LDAP directory using passed credentials.'
| def __init__(self, uri, server, port, tls, no_verify, binddn, bindpw, anonymous, accountattributename, activedirectory=False):
| self.uri = uri
self.server = server
self.port = port
self.tls = tls
schema = ('ldaps' if tls else 'ldap')
self.binddn = binddn
self.bindpw = bindpw
if (not HAS_LDAP):
raise CommandExecutionError('LDAP connection could not be made, the python-ldap module ... |
'Create a new Tornado IPC server
:param str/int socket_path: Path on the filesystem for the
socket to bind to. This socket does
not need to exist prior to calling
this method, but parent directories
should.
It may also be of type \'int\', in
which case it is used as the port
for a tcp localhost connection.
:param IOLoo... | def __init__(self, socket_path, io_loop=None, payload_handler=None):
| self.socket_path = socket_path
self._started = False
self.payload_handler = payload_handler
self.sock = None
self.io_loop = (io_loop or IOLoop.current())
self._closing = False
|
'Perform the work necessary to start up a Tornado IPC server
Blocks until socket is established'
| def start(self):
| log.trace('IPCServer: binding to socket: {0}'.format(self.socket_path))
if isinstance(self.socket_path, int):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setblocking(0)
self.so... |
'Override this to handle the streams as they arrive
:param IOStream stream: An IOStream for processing
See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream
for additional details.'
| @tornado.gen.coroutine
def handle_stream(self, stream):
| @tornado.gen.coroutine
def _null(msg):
raise tornado.gen.Return(None)
def write_callback(stream, header):
if header.get('mid'):
@tornado.gen.coroutine
def return_message(msg):
pack = salt.transport.frame.frame_msg_ipc(msg, header={'mid': header['mid']}... |
'Routines to handle any cleanup before the instance shuts down.
Sockets and filehandles should be closed explicitly, to prevent
leaks.'
| def close(self):
| if self._closing:
return
self._closing = True
if hasattr(self.sock, 'close'):
self.sock.close()
|
'Create a new IPC client
IPC clients cannot bind to ports, but must connect to
existing IPC servers. Clients can then send messages
to the server.'
| def __singleton_init__(self, socket_path, io_loop=None):
| self.io_loop = (io_loop or tornado.ioloop.IOLoop.current())
self.socket_path = socket_path
self._closing = False
self.stream = None
if six.PY2:
encoding = None
else:
encoding = 'utf-8'
self.unpacker = msgpack.Unpacker(encoding=encoding)
|
'Connect to the IPC socket'
| def connect(self, callback=None, timeout=None):
| if (hasattr(self, '_connecting_future') and (not self._connecting_future.done())):
future = self._connecting_future
else:
if hasattr(self, '_connecting_future'):
self._connecting_future.exc_info()
future = tornado.concurrent.Future()
self._connecting_future = future
... |
'Connect to a running IPCServer'
| @tornado.gen.coroutine
def _connect(self, timeout=None):
| if isinstance(self.socket_path, int):
sock_type = socket.AF_INET
sock_addr = ('127.0.0.1', self.socket_path)
else:
sock_type = socket.AF_UNIX
sock_addr = self.socket_path
self.stream = None
if (timeout is not None):
timeout_at = (time.time() + timeout)
while T... |
'Routines to handle any cleanup before the instance shuts down.
Sockets and filehandles should be closed explicitly, to prevent
leaks.'
| def close(self):
| if self._closing:
return
self._closing = True
if ((self.stream is not None) and (not self.stream.closed())):
self.stream.close()
if (self.io_loop in IPCClient.instance_map):
loop_instance_map = IPCClient.instance_map[self.io_loop]
key = str(self.socket_path)
if (k... |
'Send a message to an IPC socket
If the socket is not currently connected, a connection will be established.
:param dict msg: The message to be sent
:param int timeout: Timeout when sending message (Currently unimplemented)'
| @tornado.gen.coroutine
def send(self, msg, timeout=None, tries=None):
| if (not self.connected()):
(yield self.connect())
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
(yield self.stream.write(pack))
|
'Create a new Tornado IPC server
:param dict opts: Salt options
:param str/int socket_path: Path on the filesystem for the
socket to bind to. This socket does
not need to exist prior to calling
this method, but parent directories
should.
It may also be of type \'int\', in
which case it is used as the port
for a tcp loc... | def __init__(self, opts, socket_path, io_loop=None):
| self.opts = opts
self.socket_path = socket_path
self._started = False
self.sock = None
self.io_loop = (io_loop or IOLoop.current())
self._closing = False
self.streams = set()
|
'Perform the work necessary to start up a Tornado IPC server
Blocks until socket is established'
| def start(self):
| log.trace('IPCMessagePublisher: binding to socket: {0}'.format(self.socket_path))
if isinstance(self.socket_path, int):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setblocking(0)
... |
'Send message to all connected sockets'
| def publish(self, msg):
| if (not len(self.streams)):
return
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
for stream in self.streams:
self.io_loop.spawn_callback(self._write, stream, pack)
|
'Routines to handle any cleanup before the instance shuts down.
Sockets and filehandles should be closed explicitly, to prevent
leaks.'
| def close(self):
| if self._closing:
return
self._closing = True
for stream in self.streams:
stream.close()
self.streams.clear()
if hasattr(self.sock, 'close'):
self.sock.close()
|
'Read a message from an IPC socket
The socket must already be connected.
The associated IO Loop must NOT be running.
:param int timeout: Timeout when receiving message
:return: message data if successful. None if timed out. Will raise an
exception for all other error conditions.'
| def read_sync(self, timeout=None):
| if self.saved_data:
return self.saved_data.pop(0)
self._sync_ioloop_running = True
self._read_sync_future = self._read_sync(timeout)
self.io_loop.start()
self._sync_ioloop_running = False
ret_future = self._read_sync_future
self._read_sync_future = None
return ret_future.result()... |
'Asynchronously read messages and invoke a callback when they are ready.
:param callback: A callback with the received data'
| @tornado.gen.coroutine
def read_async(self, callback):
| while (not self.connected()):
try:
(yield self.connect(timeout=5))
except tornado.iostream.StreamClosedError:
log.trace('Subscriber closed stream on IPC {0} before connect'.format(self.socket_path))
(yield tornado.gen.sleep(1))
except ... |
'Routines to handle any cleanup before the instance shuts down.
Sockets and filehandles should be closed explicitly, to prevent
leaks.'
| def close(self):
| if (not self._closing):
IPCClient.close(self)
if (self._read_sync_future is not None):
self._read_sync_future.exc_info()
if (self._read_stream_future is not None):
self._read_stream_future.exc_info()
|
'Prepare the stack objects'
| def __prep_stack(self):
| global jobber_stack
if (not self.stack):
if jobber_stack:
self.stack = jobber_stack
else:
self.stack = jobber_stack = self._setup_stack(ryn=self.ryn)
log.debug('RAETReqChannel Using Jobber Stack at = {0}\n'.format(self.stack.ha))
|
'Setup and return the LaneStack and Yard used by by channel when global
not already setup such as in salt-call to communicate to-from the minion'
| def _setup_stack(self, ryn='manor'):
| role = self.opts.get('id')
if (not role):
emsg = "Missing role('id') required to setup RAETReqChannel."
log.error((emsg + '\n'))
raise ValueError(emsg)
kind = self.opts.get('__role')
if (kind not in kinds.APPL_KINDS):
emsg = "Invalid application kind ... |
'We don\'t need to do the crypted_transfer_decode_dictentry routine for
raet, just wrap send.'
| def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
| return self.send(load, tries, timeout)
|
'Send a message load and wait for a relative reply
One shot wonder'
| def send(self, load, tries=3, timeout=60, raw=False):
| self.__prep_stack()
tried = 1
start = time.time()
track = nacling.uuid(18)
src = (None, self.stack.local.name, track)
self.route = {'src': src, 'dst': self.dst}
msg = {'route': self.route, 'load': load}
self.stack.transmit(msg, self.stack.nameRemotes[self.ryn].uid)
while (track not i... |
'Do anything necessary pre-fork. Since this is on the master side this will
primarily be bind and listen (or the equivalent for your network library)'
| def pre_fork(self, process_manager):
| pass
|
'Do anything you need post-fork. This should handle all incoming payloads
and call payload_handler. You will also be passed io_loop, for all of your
async needs'
| def post_fork(self, payload_handler, io_loop):
| pass
|
'Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing'
| def pre_fork(self, process_manager):
| pass
|
'Publish "load" to minions'
| def publish(self, load):
| raise NotImplementedError()
|
'Send "load" to the master.'
| def send(self, load, tries=3, timeout=60, raw=False):
| raise NotImplementedError()
|
'Send "load" to the master in a way that the load is only readable by
the minion and the master (not other minions etc.)'
| def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
| raise NotImplementedError()
|
'Send load across IPC push'
| def send(self, load, tries=3, timeout=60):
| raise NotImplementedError()
|
'Send "load" to the master.'
| def send(self, load, tries=3, timeout=60, raw=False):
| raise NotImplementedError()
|
'Send "load" to the master in a way that the load is only readable by
the minion and the master (not other minions etc.)'
| def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
| raise NotImplementedError()
|
'Return a future which completes when connected to the remote publisher'
| def connect(self):
| raise NotImplementedError()
|
'When jobs are received pass them (decoded) to callback'
| def on_recv(self, callback):
| raise NotImplementedError()
|
'If we have additional IPC transports other than UxD and TCP, add them here'
| @staticmethod
def factory(opts, **kwargs):
| import salt.transport.ipc
return salt.transport.ipc.IPCMessageClient(opts, **kwargs)
|
'If we have additional IPC transports other than UXD and TCP, add them here'
| @staticmethod
def factory(opts, **kwargs):
| import salt.transport.ipc
return salt.transport.ipc.IPCMessageServer(opts, **kwargs)
|
'Only create one instance of channel per __key()'
| def __new__(cls, opts, **kwargs):
| io_loop = (kwargs.get('io_loop') or tornado.ioloop.IOLoop.current())
if (io_loop not in cls.instance_map):
cls.instance_map[io_loop] = weakref.WeakValueDictionary()
loop_instance_map = cls.instance_map[io_loop]
key = cls.__key(opts, **kwargs)
obj = loop_instance_map.get(key)
if (obj is N... |
'In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call'
| @tornado.gen.coroutine
def _crypted_transfer(self, load, tries=3, timeout=60):
| @tornado.gen.coroutine
def _do_transfer():
data = (yield self.message_client.send(self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout))
if data:
data = self.auth.crypticle.loads(data)
if six.PY3:
data = salt.transport.frame.decode_embedded... |
'Send a request, return a future which will complete when we send the message'
| @tornado.gen.coroutine
def send(self, load, tries=3, timeout=60, raw=False):
| try:
if (self.crypt == 'clear'):
ret = (yield self._uncrypted_transfer(load, tries=tries, timeout=timeout))
else:
ret = (yield self._crypted_transfer(load, tries=tries, timeout=timeout))
except tornado.iostream.StreamClosedError:
raise SaltClientError('Connection ... |
'Send the minion id to the master so that the master may better
track the connection state of the minion.
In case of authentication errors, try to renegotiate authentication
and retry the method.'
| @tornado.gen.coroutine
def send_id(self, tok, force_auth):
| load = {'id': self.opts['id'], 'tok': tok}
@tornado.gen.coroutine
def _do_transfer():
msg = self._package_load(self.auth.crypticle.dumps(load))
package = salt.transport.frame.frame_msg(msg, header=None)
(yield self.message_client.write_to_stream(package))
raise tornado.gen.Re... |
'Register an on_recv callback'
| def on_recv(self, callback):
| if (callback is None):
return self.message_client.on_recv(callback)
@tornado.gen.coroutine
def wrap_callback(body):
if (not isinstance(body, dict)):
body = msgpack.loads(body)
if six.PY3:
body = salt.transport.frame.decode_embedded_strs(body)
r... |
'Pre-fork we need to create the zmq router device'
| def pre_fork(self, process_manager):
| salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add_process(LoadBalancerServer, args=(self.opts, self.socket_queue))
elif (not salt.utils.platform.is_windows()):
self._socke... |
'After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads'
| def post_fork(self, payload_handler, io_loop):
| self.payload_handler = payload_handler
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
if USE_LOAD_BALANCER:
self.req_server = LoadBalancerWorker(self.socket_queue, self.handle_message, io_loop=self.io_loop, ssl_options=self.opts.get('ssl'))
else:
if salt.utils.pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.