Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 31 additions & 34 deletions salt/report_upload/srv/salt/_runners/foreman_report_upload.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Uploads reports from the Salt job cache to Foreman
'''

from __future__ import absolute_import, print_function, unicode_literals

LAST_UPLOADED = '/etc/salt/last_uploaded'
Expand All @@ -22,11 +25,11 @@
import base64

# Import python libs

import logging

log = logging.getLogger(__name__)


if sys.version_info.major == 3:
unicode = str

Expand All @@ -49,63 +52,57 @@ def upload(report):

if config[':proto'] == 'https':
ctx = ssl.create_default_context()
ctx.load_cert_chain(certfile=config[':ssl_cert'], keyfile=config[':ssl_key'])
ctx.load_cert_chain(certfile=config[':ssl_cert'],
keyfile=config[':ssl_key'])
if config[':ssl_ca']:
ctx.load_verify_locations(cafile=config[':ssl_ca'])
ctx.load_verify_locations(cafile=config[':ssl_ca'])
connection = HTTPSConnection(config[':host'],
port=config[':port'], context=ctx)
else:
connection = HTTPConnection(config[':host'],
port=config[':port'])
connection = HTTPConnection(config[':host'], port=config[':port'
])
if ':username' in config and ':password' in config:
token = base64.b64encode('{}:{}'.format(config[':username'],
config[':password']))
headers['Authorization'] = 'Basic {}'.format(token)
token = base64.b64encode('{}:{}'.format(config[':username'
], config[':password']).encode('utf-8'))
headers['Authorization'] = \
'Basic {}'.format(token.decode('utf-8'))

connection.request('POST', '/salt/api/v2/jobs/upload',
json.dumps(report), headers)
json.dumps(report), headers)
response = connection.getresponse()

if response.status == 200:
write_last_uploaded(report['job']['job_id'])
info_msg = 'Success {0}: {1}'.format(report['job']['job_id'], response.read())
info_msg = 'Success {0}: {1}'.format(report['job']['job_id'],
response.read())
log.info(info_msg)
else:
log.error("Unable to upload job - aborting report upload")
log.error('Unable to upload job - aborting report upload')
log.error(response.read())


def create_report(json_str):
msg = json.loads(json_str)

if msg['fun'] == 'state.highstate':
return {'job':
{
'result': {
msg['id']: msg['return'],
},
'function': 'state.highstate',
'job_id': msg['jid']
}
}
return {'job': {'result': {msg['id']: msg['return']},
'function': 'state.highstate', 'job_id': msg['jid']}}
elif msg['fun'] == 'state.template_str':
for key, entry in msg['return'].items():
if key.startswith('module_') and entry['__id__'] == 'state.highstate':
return {'job':
{
'result': {
msg['id']: next(iter(entry['changes'].values())),
},
'function': 'state.highstate',
'job_id': msg['jid']
}
}

for (key, entry) in msg['return'].items():
if key.startswith('module_') and entry['__id__'] \
== 'state.highstate':
return {'job': {'result': {msg['id'
]: next(iter(entry['changes'].values()))},
'function': 'state.highstate',
'job_id': msg['jid']}}

raise Exception('No state.highstate found')


def get_lock():
if os.path.isfile(LOCK_FILE):
raise Exception("Unable to obtain lock.")
raise Exception('Unable to obtain lock.')
else:
io.open(LOCK_FILE, 'w+').close()

Expand All @@ -121,14 +118,14 @@ def now(highstate):
highstate :
dictionary containing a highstate (generated by a Salt reactor)
'''

log.debug('Upload highstate to Foreman')

try:
report = create_report(base64.b64decode(highstate))
get_lock()
upload(report)
except Exception as exc:
except Exception, exc:
log.error('Exception encountered: %s', exc)
finally:
release_lock()