本文整理汇总了Python中pypuppetdb.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(hostname, to=None, num_days=7, cache_dir=None, dry_run=False):
"""
main entry point
:param hostname: PuppetDB hostname
:type hostname: string
:param to: list of addresses to send mail to
:type to: list
:param num_days: the number of days to report on, default 7
:type num_days: int
:param cache_dir: absolute path to where to cache data from PuppetDB
:type cache_dir: string
:param dry_run: whether to actually send, or just print what would be sent
:type dry_run: boolean
"""
pdb = connect(host=hostname)
# essentially figure out all these for yesterday, build the tables, serialize the result as JSON somewhere. then just keep the last ~7 days json files
date_data = {}
dates = [] # ordered
date_list = get_date_list(num_days)
localtz = tzlocal.get_localzone()
start_date = date_list[0]
end_date = date_list[-1] - datetime.timedelta(hours=23, minutes=59, seconds=59)
for query_date in date_list:
end = query_date
start = query_date - datetime.timedelta(days=1) + datetime.timedelta(seconds=1)
date_s = (query_date - datetime.timedelta(hours=1)).astimezone(localtz).strftime('%a %m/%d')
date_data[date_s] = get_data_for_timespan(hostname, pdb, start, end, cache_dir=cache_dir)
dates.append(date_s)
html = format_html(hostname, dates, date_data, start_date, end_date)
subject = 'daily puppet(db) run summary for {host}'.format(host=hostname)
send_mail(to, subject, html, dry_run=dry_run)
return True
示例2: get_host_list
def get_host_list(self):
db = connect(api_version=3, host=self.puppetdb_server, port=self.puppetdb_server_port)
nodes = db.nodes()
inv = { 'all': []}
for node in nodes:
inv['all'].append(node.name)
return inv
示例3: make_it_so
def make_it_so():
args = argparser()
db = pypuppetdb.connect(host=PUPPETDB_HOST, port=PUPPETDB_PORT)
if args.section == 'nodes':
nodes_query(db, args.query)
if args.section == 'facts':
fact_query(db, args.query)
示例4: get_host_list_based_on_environments
def get_host_list_based_on_environments(self):
db = connect(api_version=4, host=self.puppetdb_server, port=self.puppetdb_server_port)
json_data_toReturn = ''
inv = {}
for env in self.puppetdb_environments:
inv.update( { env: [] })
facts = db.facts('fqdn', environment=env)
for fact in facts:
inv[env].append(fact.value)
return inv
示例5: read_callback
def read_callback():
puppetdb = connect(
api_version=3,
host=PUPPETDB_HOST,
port=PUPPETDB_PORT,
ssl_verify=PUPPETDB_SSL,
ssl_key=PUPPETDB_KEY,
ssl_cert=PUPPETDB_CERT,
timeout=PUPPETDB_TIMEOUT,
)
prefix = "com.puppetlabs.puppetdb.query.population"
num_nodes = puppetdb.metric("{0}{1}".format(prefix, ":type=default,name=num-nodes"))
num_resources = puppetdb.metric("{0}{1}".format(prefix, ":type=default,name=num-resources"))
avg_resources_node = puppetdb.metric("{0}{1}".format(prefix, ":type=default,name=avg-resources-per-node"))
# Ftech nodes
nodes = puppetdb.nodes(unreported=UNREPORTED_TIME, with_status=True)
# Init stats
stats = {"changed": 0, "unchanged": 0, "failed": 0, "unreported": 0, "noop": 0}
for node in nodes:
if node.status == "unreported":
stats["unreported"] += 1
elif node.status == "changed":
stats["changed"] += 1
elif node.status == "failed":
stats["failed"] += 1
elif node.status == "noop":
stats["noop"] += 1
else:
stats["unchanged"] += 1
log_verbose("population: %s\n" % num_nodes["Value"])
dispatch_value(num_nodes["Value"], "population", "gauge")
log_verbose("unreported: %s\n" % stats["unreported"])
dispatch_value(stats["unreported"], "unreported", "gauge")
log_verbose("changed: %s\n" % stats["changed"])
dispatch_value(stats["changed"], "changed", "gauge")
log_verbose("failed: %s\n" % stats["failed"])
dispatch_value(stats["failed"], "failed", "gauge")
log_verbose("noop: %s\n" % stats["noop"])
dispatch_value(stats["noop"], "noop", "gauge")
log_verbose("unchanged: %s\n" % stats["unchanged"])
dispatch_value(stats["unchanged"], "unchanged", "gauge")
示例6: check_user
def check_user(username):
puppet_db = pypuppetdb.connect(host=settings.PUPPETDB_HOST,
port=settings.PUPPETDB_PORT,
ssl_verify=settings.PUPPETDB_SSL_VERIFY,
ssl_key=settings.PUPPETDB_KEY,
ssl_cert=settings.PUPPETDB_CERT)
try:
node = puppet_db.node(settings.PUPPETDB_NODE)
return next(node.resources(type_='User', title=username))
except ConnectionError:
return False
except StopIteration:
return None
示例7: get_puppetdb
def get_puppetdb():
global PUPPETDB
if PUPPETDB is None:
app = get_app()
puppetdb = connect(host=app.config['PUPPETDB_HOST'],
port=app.config['PUPPETDB_PORT'],
ssl_verify=app.config['PUPPETDB_SSL_VERIFY'],
ssl_key=app.config['PUPPETDB_KEY'],
ssl_cert=app.config['PUPPETDB_CERT'],
timeout=app.config['PUPPETDB_TIMEOUT'],)
PUPPETDB = puppetdb
return PUPPETDB
示例8: __init__
def __init__(self, hostname, port, api_version, output_dir,
nodefacts=None, query=None, environment=None):
self.db = connect(host=hostname,
port=port,
api_version=api_version,
timeout=20)
self.db.resources = self.db.resources
self.output_dir = output_dir
self.environment = environment
if not nodefacts:
self.nodefacts = self.get_nodefacts()
else:
self.nodefacts = nodefacts
self.query = query
示例9: __init__
def __init__(self, hostname, port, api_version,
query=None, environment=None,
ssl_key=None, ssl_cert=None,
timeout=20):
from pypuppetdb import connect
self.db = connect(host=hostname,
port=port,
ssl_key=ssl_key,
ssl_cert=ssl_cert,
api_version=api_version,
timeout=timeout)
self.db.resources = self.db.resources
self.environment = environment
if query is None:
query = {}
self.query = query
示例10: main
def main():
"""
Main function
"""
parser = argparse.ArgumentParser(prog="puppetdb_stencil")
parser.add_argument("resource_types", metavar="RESOURCE_TYPE", nargs="+")
parser.add_argument("--templates", "-t", metavar="TEMPLATE", nargs="*")
parser.add_argument("--debug", "-d", action="store_true")
parser.add_argument("--host", "-H", default="localhost")
parser.add_argument("--port", "-p", default="8080")
parser.add_argument("--localsite", "-l", default="true")
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARN)
database = pypuppetdb.connect(host=args.host, port=args.port)
for resource_type in args.resource_types:
templates = ["{0}.jinja2".format(resource_type)]
if args.templates:
templates += args.templates
print(render_resources(database, resource_type, args.localsite, templates))
示例11: main
def main():
options = cmd()
if options.verify == 'yes':
ssl_verify = True
elif options.verify == 'no':
ssl_verify = False
else:
ssl_verify = options.verify
p = pypuppetdb.connect(host=options.server, port=options.port,
ssl_verify=ssl_verify, ssl_key=options.clientkey,
ssl_cert=options.clientcert,
timeout=options.timeout)
node = get_node(options.hostname, p)
if not node.report_timestamp:
print("UNKNOWN - This machine hasn't checked in with us yet")
sys.exit(3)
critical_seconds = 60 * 60 * options.critical
warning_seconds = 60 * 60 * options.warning
(delta, delta_seconds) = time_elapsed(node.report_timestamp)
status = node_status(options.hostname, p)
if status is not None and status['failures'] > 0:
print(('CRITICAL - We have {0} failure(s). Last report was '
'{1} ago'.format(status['failures'], delta)))
sys.exit(2)
elif delta_seconds < warning_seconds:
print('OK - Last run happened {0} ago'.format(delta))
sys.exit(0)
elif warning_seconds <= delta_seconds < critical_seconds:
print('WARNING - Last run happened {0} ago'.format(delta))
sys.exit(1)
elif delta_seconds >= critical_seconds:
print('CRITICAL - Last run happened {0} ago'.format(delta))
sys.exit(2)
else:
print("UNKNOWN - Something went wrong determining this node's state")
sys.exit(3)
示例12: __init__
def __init__(self, refresh):
self.config = load_config()
if not self.config:
sys.exit('Error: Could not load any config files: {0}'
.format(', '.join(CONFIG_FILES)))
puppetdb_config = {
'host': self.config.get('host'),
'port': self.config.get('port'),
'timeout': self.config.get('timeout'),
'ssl_verify': self.config.get('ssl_verify'),
'ssl_key': self.config.get('ssl_key') or None,
'ssl_cert': self.config.get('ssl_cert') or None
}
self.puppetdb = connect(**puppetdb_config)
self.cache_file = self.config.get('cache_file')
self.cache_duration = self.config.get('cache_duration')
self.refresh = refresh
示例13: main
def main():
"""
Main function
"""
parser = argparse.ArgumentParser(prog='puppetdb_stencil')
parser.add_argument('resource_types', metavar='RESOURCE_TYPE', nargs='+')
parser.add_argument('--templates', '-t', metavar='TEMPLATE', nargs='*')
parser.add_argument('--debug', '-d', action='store_true')
parser.add_argument('--host', '-H', default='localhost')
parser.add_argument('--port', '-p', default='8080')
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARN)
database = pypuppetdb.connect(host=args.host, port=args.port)
for resource_type in args.resource_types:
templates = ['{0}.jinja2'.format(resource_type)]
if args.templates:
templates += args.templates
print(render_resources(database, resource_type, templates))
示例14: api2
def api2():
"""Set up a connection to PuppetDB with API version 2."""
puppetdb = connect(api_version=2)
return puppetdb
示例15: api3
def api3():
"""Set up a connection to PuppetDB with API version 3."""
puppetdb = connect(api_version=3)
return puppetdb