/usr/lib/python2.7/dist-packages/nss_cache/sources/consulsource.py is in nsscache 0.32-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | """An implementation of a consul data source for nsscache."""
__author__ = 'hexedpackets@gmail.com (William Huba)'
import base64
import collections
import logging
import json
from nss_cache.maps import group
from nss_cache.maps import passwd
from nss_cache.sources import httpsource
def RegisterImplementation(registration_callback):
registration_callback(ConsulFilesSource)
class ConsulFilesSource(httpsource.HttpFilesSource):
"""Source for data fetched via Consul."""
# Consul defaults
DATACENTER = 'dc1'
TOKEN = ''
# for registration
name = 'consul'
def _SetDefaults(self, configuration):
"""Set defaults if necessary."""
super(ConsulFilesSource, self)._SetDefaults(configuration)
if 'token' not in configuration:
configuration['token'] = self.TOKEN
if 'datacenter' not in configuration:
configuration['datacenter'] = self.DATACENTER
for url in ['passwd_url', 'group_url']:
configuration[url] = '{}?recurse&token={}&dc={}'.format(
configuration[url], configuration['token'], configuration['datacenter'])
def GetPasswdMap(self, since=None):
"""Return the passwd map from this source.
Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.
Returns:
instance of passwd.PasswdMap
"""
return PasswdUpdateGetter().GetUpdates(self, self.conf['passwd_url'], since)
def GetGroupMap(self, since=None):
"""Return the group map from this source.
Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.
Returns:
instance of group.GroupMap
"""
return GroupUpdateGetter().GetUpdates(self, self.conf['group_url'], since)
class PasswdUpdateGetter(httpsource.UpdateGetter):
"""Get passwd updates."""
def GetParser(self):
"""Returns a MapParser to parse FilesPasswd cache."""
return ConsulPasswdMapParser()
def CreateMap(self):
"""Returns a new PasswdMap instance to have PasswdMapEntries added to it."""
return passwd.PasswdMap()
class GroupUpdateGetter(httpsource.UpdateGetter):
"""Get group updates."""
def GetParser(self):
"""Returns a MapParser to parse FilesGroup cache."""
return ConsulGroupMapParser()
def CreateMap(self):
"""Returns a new GroupMap instance to have GroupMapEntries added to it."""
return group.GroupMap()
class ConsulMapParser(object):
"""A base class for parsing nss_files module cache."""
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def GetMap(self, cache_info, data):
"""Returns a map from a cache.
Args:
cache_info: file like object containing the cache.
data: a Map to populate.
Returns:
A child of Map containing the cache data.
"""
entries = collections.defaultdict(dict)
for line in json.loads(cache_info.read()):
key = line.get('Key', '').split('/')
value = line.get('Value', '')
if not value or not key:
continue
value = base64.b64decode(value)
name = str(key[-2])
entry_piece = key[-1]
entries[name][entry_piece] = value
for name, entry in entries.iteritems():
map_entry = self._ReadEntry(name, entry)
if map_entry is None:
self.log.warn('Could not create entry from line %r in cache, skipping',
entry)
continue
if not data.Add(map_entry):
self.log.warn('Could not add entry %r read from line %r in cache',
map_entry, entry)
return data
class ConsulPasswdMapParser(ConsulMapParser):
"""Class for parsing nss_files module passwd cache."""
def _ReadEntry(self, name, entry):
"""Return a PasswdMapEntry from a record in the target cache."""
map_entry = passwd.PasswdMapEntry()
# maps expect strict typing, so convert to int as appropriate.
map_entry.name = name
map_entry.passwd = entry.get('passwd', 'x')
map_entry.uid = int(entry['uid'])
map_entry.gid = int(entry['gid'])
map_entry.gecos = entry.get('comment', '')
map_entry.dir = entry.get('home', '/home/{}'.format(name))
map_entry.shell = entry.get('shell', '/bin/bash')
return map_entry
class ConsulGroupMapParser(ConsulMapParser):
"""Class for parsing a nss_files module group cache."""
def _ReadEntry(self, name, entry):
"""Return a GroupMapEntry from a record in the target cache."""
map_entry = group.GroupMapEntry()
# map entries expect strict typing, so convert as appropriate
map_entry.name = name
map_entry.passwd = entry.get('passwd', 'x')
map_entry.gid = int(entry['gid'])
try:
members = entry.get('members', '').split('\n')
except (ValueError, TypeError):
members = ['']
map_entry.members = members
return map_entry
|