Skip to content

Instantly share code, notes, and snippets.

@scoates
Created August 14, 2015 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scoates/240294cea3a551ac8bfc to your computer and use it in GitHub Desktop.
Save scoates/240294cea3a551ac8bfc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
based on https://raw.githubusercontent.com/saltstack/salt/develop/tests/eventlisten.py
'''
# Import Python libs
from __future__ import print_function
import optparse
import os
from time import sleep
# Import Salt libs
import salt.utils.event
import salt.client
saltclient = salt.client.LocalClient()
def parse():
'''
Parse the script command line inputs
'''
parser = optparse.OptionParser()
parser.add_option(
'-s',
'--sock-dir',
dest='sock_dir',
default='/var/run/salt',
help=('Staticly define the directory holding the salt unix '
'sockets for communication'))
parser.add_option(
'-n',
'--node',
dest='node',
default='master',
help=('State if this listener will attach to a master or a '
'minion daemon, pass "master" or "minion"'))
options, args = parser.parse_args()
opts = {}
for k, v in options.__dict__.items():
if v is not None:
opts[k] = v
opts['sock_dir'] = os.path.join(opts['sock_dir'], opts['node'])
if 'minion' in options.node:
if args:
opts['id'] = args[0]
return opts
opts['id'] = options.node
return opts
def listen(sock_dir, node, id=None):
'''
Attach to the pub socket and grab messages
'''
event = salt.utils.event.SaltEvent(
node,
sock_dir,
id=id
)
while True:
ret = event.get_event(full=True)
if ret is None:
continue
if ret['tag'] != 'salt/auth':
continue
node_id = ret['data']['id']
print("Event: %s on %s" % (ret['tag'], node_id))
# see if a file for this node exists
node_file = os.path.join(sock_dir, 'pile', node_id)
if os.path.isfile(node_file):
# file exists; highstate it
print("highstating %s" % node_id)
# need to sleep here because the node might not be
# ready to highstate if this is a startup auth
# and sleeping isn't really a problem for performance
sleep(10)
saltclient.cmd_async(node_id, 'state.highstate')
os.remove(node_file)
else:
print("%s not found; not highstating" % node_file)
if __name__ == '__main__':
opts = parse()
listen(opts['sock_dir'], opts['node'], id=opts.get('id', ''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment