repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/states/grafana_dashboard.py | _auto_adjust_panel_spans | def _auto_adjust_panel_spans(dashboard):
'''Adjust panel spans to take up the available width.
For each group of panels that would be laid out on the same level, scale up
the unspecified panel spans to fill up the level.
'''
for row in dashboard.get('rows', []):
levels = []
current_level = []
levels.append(current_level)
for panel in row.get('panels', []):
current_level_span = sum(panel.get('span', _DEFAULT_PANEL_SPAN)
for panel in current_level)
span = panel.get('span', _DEFAULT_PANEL_SPAN)
if current_level_span + span > _FULL_LEVEL_SPAN:
current_level = [panel]
levels.append(current_level)
else:
current_level.append(panel)
for level in levels:
specified_panels = [panel for panel in level if 'span' in panel]
unspecified_panels = [panel for panel in level
if 'span' not in panel]
if not unspecified_panels:
continue
specified_span = sum(panel['span'] for panel in specified_panels)
available_span = _FULL_LEVEL_SPAN - specified_span
auto_span = float(available_span) / len(unspecified_panels)
for panel in unspecified_panels:
panel['span'] = auto_span | python | def _auto_adjust_panel_spans(dashboard):
'''Adjust panel spans to take up the available width.
For each group of panels that would be laid out on the same level, scale up
the unspecified panel spans to fill up the level.
'''
for row in dashboard.get('rows', []):
levels = []
current_level = []
levels.append(current_level)
for panel in row.get('panels', []):
current_level_span = sum(panel.get('span', _DEFAULT_PANEL_SPAN)
for panel in current_level)
span = panel.get('span', _DEFAULT_PANEL_SPAN)
if current_level_span + span > _FULL_LEVEL_SPAN:
current_level = [panel]
levels.append(current_level)
else:
current_level.append(panel)
for level in levels:
specified_panels = [panel for panel in level if 'span' in panel]
unspecified_panels = [panel for panel in level
if 'span' not in panel]
if not unspecified_panels:
continue
specified_span = sum(panel['span'] for panel in specified_panels)
available_span = _FULL_LEVEL_SPAN - specified_span
auto_span = float(available_span) / len(unspecified_panels)
for panel in unspecified_panels:
panel['span'] = auto_span | [
"def",
"_auto_adjust_panel_spans",
"(",
"dashboard",
")",
":",
"for",
"row",
"in",
"dashboard",
".",
"get",
"(",
"'rows'",
",",
"[",
"]",
")",
":",
"levels",
"=",
"[",
"]",
"current_level",
"=",
"[",
"]",
"levels",
".",
"append",
"(",
"current_level",
... | Adjust panel spans to take up the available width.
For each group of panels that would be laid out on the same level, scale up
the unspecified panel spans to fill up the level. | [
"Adjust",
"panel",
"spans",
"to",
"take",
"up",
"the",
"available",
"width",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L331-L362 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _ensure_pinned_rows | def _ensure_pinned_rows(dashboard):
'''Pin rows to the top of the dashboard.'''
pinned_row_titles = __salt__['pillar.get'](_PINNED_ROWS_PILLAR)
if not pinned_row_titles:
return
pinned_row_titles_lower = []
for title in pinned_row_titles:
pinned_row_titles_lower.append(title.lower())
rows = dashboard.get('rows', [])
pinned_rows = []
for i, row in enumerate(rows):
if row.get('title', '').lower() in pinned_row_titles_lower:
del rows[i]
pinned_rows.append(row)
rows = pinned_rows + rows | python | def _ensure_pinned_rows(dashboard):
'''Pin rows to the top of the dashboard.'''
pinned_row_titles = __salt__['pillar.get'](_PINNED_ROWS_PILLAR)
if not pinned_row_titles:
return
pinned_row_titles_lower = []
for title in pinned_row_titles:
pinned_row_titles_lower.append(title.lower())
rows = dashboard.get('rows', [])
pinned_rows = []
for i, row in enumerate(rows):
if row.get('title', '').lower() in pinned_row_titles_lower:
del rows[i]
pinned_rows.append(row)
rows = pinned_rows + rows | [
"def",
"_ensure_pinned_rows",
"(",
"dashboard",
")",
":",
"pinned_row_titles",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"_PINNED_ROWS_PILLAR",
")",
"if",
"not",
"pinned_row_titles",
":",
"return",
"pinned_row_titles_lower",
"=",
"[",
"]",
"for",
"title",
"i... | Pin rows to the top of the dashboard. | [
"Pin",
"rows",
"to",
"the",
"top",
"of",
"the",
"dashboard",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L365-L380 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _ensure_panel_ids | def _ensure_panel_ids(dashboard):
'''Assign panels auto-incrementing IDs.'''
panel_id = 1
for row in dashboard.get('rows', []):
for panel in row.get('panels', []):
panel['id'] = panel_id
panel_id += 1 | python | def _ensure_panel_ids(dashboard):
'''Assign panels auto-incrementing IDs.'''
panel_id = 1
for row in dashboard.get('rows', []):
for panel in row.get('panels', []):
panel['id'] = panel_id
panel_id += 1 | [
"def",
"_ensure_panel_ids",
"(",
"dashboard",
")",
":",
"panel_id",
"=",
"1",
"for",
"row",
"in",
"dashboard",
".",
"get",
"(",
"'rows'",
",",
"[",
"]",
")",
":",
"for",
"panel",
"in",
"row",
".",
"get",
"(",
"'panels'",
",",
"[",
"]",
")",
":",
... | Assign panels auto-incrementing IDs. | [
"Assign",
"panels",
"auto",
"-",
"incrementing",
"IDs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L383-L389 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _ensure_annotations | def _ensure_annotations(dashboard):
'''Explode annotation_tags into annotations.'''
if 'annotation_tags' not in dashboard:
return
tags = dashboard['annotation_tags']
annotations = {
'enable': True,
'list': [],
}
for tag in tags:
annotations['list'].append({
'datasource': "graphite",
'enable': False,
'iconColor': "#C0C6BE",
'iconSize': 13,
'lineColor': "rgba(255, 96, 96, 0.592157)",
'name': tag,
'showLine': True,
'tags': tag,
})
del dashboard['annotation_tags']
dashboard['annotations'] = annotations | python | def _ensure_annotations(dashboard):
'''Explode annotation_tags into annotations.'''
if 'annotation_tags' not in dashboard:
return
tags = dashboard['annotation_tags']
annotations = {
'enable': True,
'list': [],
}
for tag in tags:
annotations['list'].append({
'datasource': "graphite",
'enable': False,
'iconColor': "#C0C6BE",
'iconSize': 13,
'lineColor': "rgba(255, 96, 96, 0.592157)",
'name': tag,
'showLine': True,
'tags': tag,
})
del dashboard['annotation_tags']
dashboard['annotations'] = annotations | [
"def",
"_ensure_annotations",
"(",
"dashboard",
")",
":",
"if",
"'annotation_tags'",
"not",
"in",
"dashboard",
":",
"return",
"tags",
"=",
"dashboard",
"[",
"'annotation_tags'",
"]",
"annotations",
"=",
"{",
"'enable'",
":",
"True",
",",
"'list'",
":",
"[",
... | Explode annotation_tags into annotations. | [
"Explode",
"annotation_tags",
"into",
"annotations",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L392-L413 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _get | def _get(url, profile):
'''Get a specific dashboard.'''
request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'),
url)
response = requests.get(
request_url,
headers={
"Accept": "application/json",
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
timeout=profile.get('grafana_timeout', 3),
)
data = response.json()
if data.get('message') == 'Not found':
return None
if 'dashboard' not in data:
return None
return data['dashboard'] | python | def _get(url, profile):
'''Get a specific dashboard.'''
request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'),
url)
response = requests.get(
request_url,
headers={
"Accept": "application/json",
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
timeout=profile.get('grafana_timeout', 3),
)
data = response.json()
if data.get('message') == 'Not found':
return None
if 'dashboard' not in data:
return None
return data['dashboard'] | [
"def",
"_get",
"(",
"url",
",",
"profile",
")",
":",
"request_url",
"=",
"\"{0}/api/dashboards/{1}\"",
".",
"format",
"(",
"profile",
".",
"get",
"(",
"'grafana_url'",
")",
",",
"url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"request_url",
",",
... | Get a specific dashboard. | [
"Get",
"a",
"specific",
"dashboard",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L416-L433 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _delete | def _delete(url, profile):
'''Delete a specific dashboard.'''
request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'),
url)
response = requests.delete(
request_url,
headers={
"Accept": "application/json",
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
timeout=profile.get('grafana_timeout'),
)
data = response.json()
return data | python | def _delete(url, profile):
'''Delete a specific dashboard.'''
request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'),
url)
response = requests.delete(
request_url,
headers={
"Accept": "application/json",
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
timeout=profile.get('grafana_timeout'),
)
data = response.json()
return data | [
"def",
"_delete",
"(",
"url",
",",
"profile",
")",
":",
"request_url",
"=",
"\"{0}/api/dashboards/{1}\"",
".",
"format",
"(",
"profile",
".",
"get",
"(",
"'grafana_url'",
")",
",",
"url",
")",
"response",
"=",
"requests",
".",
"delete",
"(",
"request_url",
... | Delete a specific dashboard. | [
"Delete",
"a",
"specific",
"dashboard",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L436-L449 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _update | def _update(dashboard, profile):
'''Update a specific dashboard.'''
payload = {
'dashboard': dashboard,
'overwrite': True
}
request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url'))
response = requests.post(
request_url,
headers={
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
json=payload
)
return response.json() | python | def _update(dashboard, profile):
'''Update a specific dashboard.'''
payload = {
'dashboard': dashboard,
'overwrite': True
}
request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url'))
response = requests.post(
request_url,
headers={
"Authorization": "Bearer {0}".format(profile.get('grafana_token'))
},
json=payload
)
return response.json() | [
"def",
"_update",
"(",
"dashboard",
",",
"profile",
")",
":",
"payload",
"=",
"{",
"'dashboard'",
":",
"dashboard",
",",
"'overwrite'",
":",
"True",
"}",
"request_url",
"=",
"\"{0}/api/dashboards/db\"",
".",
"format",
"(",
"profile",
".",
"get",
"(",
"'grafa... | Update a specific dashboard. | [
"Update",
"a",
"specific",
"dashboard",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L452-L466 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _dashboard_diff | def _dashboard_diff(_new_dashboard, _old_dashboard):
'''Return a dictionary of changes between dashboards.'''
diff = {}
# Dashboard diff
new_dashboard = copy.deepcopy(_new_dashboard)
old_dashboard = copy.deepcopy(_old_dashboard)
dashboard_diff = DictDiffer(new_dashboard, old_dashboard)
diff['dashboard'] = _stripped({
'changed': list(dashboard_diff.changed()) or None,
'added': list(dashboard_diff.added()) or None,
'removed': list(dashboard_diff.removed()) or None,
})
# Row diff
new_rows = new_dashboard.get('rows', [])
old_rows = old_dashboard.get('rows', [])
new_rows_by_title = {}
old_rows_by_title = {}
for row in new_rows:
if 'title' in row:
new_rows_by_title[row['title']] = row
for row in old_rows:
if 'title' in row:
old_rows_by_title[row['title']] = row
rows_diff = DictDiffer(new_rows_by_title, old_rows_by_title)
diff['rows'] = _stripped({
'added': list(rows_diff.added()) or None,
'removed': list(rows_diff.removed()) or None,
})
for changed_row_title in rows_diff.changed():
old_row = old_rows_by_title[changed_row_title]
new_row = new_rows_by_title[changed_row_title]
row_diff = DictDiffer(new_row, old_row)
diff['rows'].setdefault('changed', {})
diff['rows']['changed'][changed_row_title] = _stripped({
'changed': list(row_diff.changed()) or None,
'added': list(row_diff.added()) or None,
'removed': list(row_diff.removed()) or None,
})
# Panel diff
old_panels_by_id = {}
new_panels_by_id = {}
for row in old_dashboard.get('rows', []):
for panel in row.get('panels', []):
if 'id' in panel:
old_panels_by_id[panel['id']] = panel
for row in new_dashboard.get('rows', []):
for panel in row.get('panels', []):
if 'id' in panel:
new_panels_by_id[panel['id']] = panel
panels_diff = DictDiffer(new_panels_by_id, old_panels_by_id)
diff['panels'] = _stripped({
'added': list(panels_diff.added()) or None,
'removed': list(panels_diff.removed()) or None,
})
for changed_panel_id in panels_diff.changed():
old_panel = old_panels_by_id[changed_panel_id]
new_panel = new_panels_by_id[changed_panel_id]
panels_diff = DictDiffer(new_panel, old_panel)
diff['panels'].setdefault('changed', {})
diff['panels']['changed'][changed_panel_id] = _stripped({
'changed': list(panels_diff.changed()) or None,
'added': list(panels_diff.added()) or None,
'removed': list(panels_diff.removed()) or None,
})
return diff | python | def _dashboard_diff(_new_dashboard, _old_dashboard):
'''Return a dictionary of changes between dashboards.'''
diff = {}
# Dashboard diff
new_dashboard = copy.deepcopy(_new_dashboard)
old_dashboard = copy.deepcopy(_old_dashboard)
dashboard_diff = DictDiffer(new_dashboard, old_dashboard)
diff['dashboard'] = _stripped({
'changed': list(dashboard_diff.changed()) or None,
'added': list(dashboard_diff.added()) or None,
'removed': list(dashboard_diff.removed()) or None,
})
# Row diff
new_rows = new_dashboard.get('rows', [])
old_rows = old_dashboard.get('rows', [])
new_rows_by_title = {}
old_rows_by_title = {}
for row in new_rows:
if 'title' in row:
new_rows_by_title[row['title']] = row
for row in old_rows:
if 'title' in row:
old_rows_by_title[row['title']] = row
rows_diff = DictDiffer(new_rows_by_title, old_rows_by_title)
diff['rows'] = _stripped({
'added': list(rows_diff.added()) or None,
'removed': list(rows_diff.removed()) or None,
})
for changed_row_title in rows_diff.changed():
old_row = old_rows_by_title[changed_row_title]
new_row = new_rows_by_title[changed_row_title]
row_diff = DictDiffer(new_row, old_row)
diff['rows'].setdefault('changed', {})
diff['rows']['changed'][changed_row_title] = _stripped({
'changed': list(row_diff.changed()) or None,
'added': list(row_diff.added()) or None,
'removed': list(row_diff.removed()) or None,
})
# Panel diff
old_panels_by_id = {}
new_panels_by_id = {}
for row in old_dashboard.get('rows', []):
for panel in row.get('panels', []):
if 'id' in panel:
old_panels_by_id[panel['id']] = panel
for row in new_dashboard.get('rows', []):
for panel in row.get('panels', []):
if 'id' in panel:
new_panels_by_id[panel['id']] = panel
panels_diff = DictDiffer(new_panels_by_id, old_panels_by_id)
diff['panels'] = _stripped({
'added': list(panels_diff.added()) or None,
'removed': list(panels_diff.removed()) or None,
})
for changed_panel_id in panels_diff.changed():
old_panel = old_panels_by_id[changed_panel_id]
new_panel = new_panels_by_id[changed_panel_id]
panels_diff = DictDiffer(new_panel, old_panel)
diff['panels'].setdefault('changed', {})
diff['panels']['changed'][changed_panel_id] = _stripped({
'changed': list(panels_diff.changed()) or None,
'added': list(panels_diff.added()) or None,
'removed': list(panels_diff.removed()) or None,
})
return diff | [
"def",
"_dashboard_diff",
"(",
"_new_dashboard",
",",
"_old_dashboard",
")",
":",
"diff",
"=",
"{",
"}",
"# Dashboard diff",
"new_dashboard",
"=",
"copy",
".",
"deepcopy",
"(",
"_new_dashboard",
")",
"old_dashboard",
"=",
"copy",
".",
"deepcopy",
"(",
"_old_dash... | Return a dictionary of changes between dashboards. | [
"Return",
"a",
"dictionary",
"of",
"changes",
"between",
"dashboards",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L469-L537 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _stripped | def _stripped(d):
'''Strip falsey entries.'''
ret = {}
for k, v in six.iteritems(d):
if v:
ret[k] = v
return ret | python | def _stripped(d):
'''Strip falsey entries.'''
ret = {}
for k, v in six.iteritems(d):
if v:
ret[k] = v
return ret | [
"def",
"_stripped",
"(",
"d",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"d",
")",
":",
"if",
"v",
":",
"ret",
"[",
"k",
"]",
"=",
"v",
"return",
"ret"
] | Strip falsey entries. | [
"Strip",
"falsey",
"entries",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L540-L546 | train |
saltstack/salt | salt/modules/telemetry.py | _retrieve_channel_id | def _retrieve_channel_id(email, profile='telemetry'):
'''
Given an email address, checks the local
cache if corresponding email address: channel_id
mapping exists
email
Email escalation policy
profile
A dict of telemetry config information.
'''
key = "telemetry.channels"
auth = _auth(profile=profile)
if key not in __context__:
get_url = _get_telemetry_base(profile) + "/notification-channels?_type=EmailNotificationChannel"
response = requests.get(get_url, headers=auth)
if response.status_code == 200:
cache_result = {}
for index, alert in enumerate(response.json()):
cache_result[alert.get('email')] = alert.get('_id', 'false')
__context__[key] = cache_result
return __context__[key].get(email, False) | python | def _retrieve_channel_id(email, profile='telemetry'):
'''
Given an email address, checks the local
cache if corresponding email address: channel_id
mapping exists
email
Email escalation policy
profile
A dict of telemetry config information.
'''
key = "telemetry.channels"
auth = _auth(profile=profile)
if key not in __context__:
get_url = _get_telemetry_base(profile) + "/notification-channels?_type=EmailNotificationChannel"
response = requests.get(get_url, headers=auth)
if response.status_code == 200:
cache_result = {}
for index, alert in enumerate(response.json()):
cache_result[alert.get('email')] = alert.get('_id', 'false')
__context__[key] = cache_result
return __context__[key].get(email, False) | [
"def",
"_retrieve_channel_id",
"(",
"email",
",",
"profile",
"=",
"'telemetry'",
")",
":",
"key",
"=",
"\"telemetry.channels\"",
"auth",
"=",
"_auth",
"(",
"profile",
"=",
"profile",
")",
"if",
"key",
"not",
"in",
"__context__",
":",
"get_url",
"=",
"_get_te... | Given an email address, checks the local
cache if corresponding email address: channel_id
mapping exists
email
Email escalation policy
profile
A dict of telemetry config information. | [
"Given",
"an",
"email",
"address",
"checks",
"the",
"local",
"cache",
"if",
"corresponding",
"email",
"address",
":",
"channel_id",
"mapping",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L91-L116 | train |
saltstack/salt | salt/modules/telemetry.py | get_alert_config | def get_alert_config(deployment_id, metric_name=None, api_key=None, profile="telemetry"):
'''
Get all alert definitions associated with a given deployment or if metric_name
is specified, obtain the specific alert config
Returns dictionary or list of dictionaries.
CLI Example:
salt myminion telemetry.get_alert_config rs-ds033197 currentConnections profile=telemetry
salt myminion telemetry.get_alert_config rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
alert = False
key = "telemetry.{0}.alerts".format(deployment_id)
if key not in __context__:
try:
get_url = _get_telemetry_base(profile) + "/alerts?deployment={0}".format(deployment_id)
response = requests.get(get_url, headers=auth)
except requests.exceptions.RequestException as e:
log.error(six.text_type(e))
return False
http_result = {}
if response.status_code == 200:
for alert in response.json():
http_result[alert.get('condition', {}).get('metric')] = alert
__context__[key] = http_result
if not __context__.get(key):
return []
alerts = __context__[key].values()
if metric_name:
return __context__[key].get(metric_name)
return [alert['_id'] for alert in alerts if '_id' in alert] | python | def get_alert_config(deployment_id, metric_name=None, api_key=None, profile="telemetry"):
'''
Get all alert definitions associated with a given deployment or if metric_name
is specified, obtain the specific alert config
Returns dictionary or list of dictionaries.
CLI Example:
salt myminion telemetry.get_alert_config rs-ds033197 currentConnections profile=telemetry
salt myminion telemetry.get_alert_config rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
alert = False
key = "telemetry.{0}.alerts".format(deployment_id)
if key not in __context__:
try:
get_url = _get_telemetry_base(profile) + "/alerts?deployment={0}".format(deployment_id)
response = requests.get(get_url, headers=auth)
except requests.exceptions.RequestException as e:
log.error(six.text_type(e))
return False
http_result = {}
if response.status_code == 200:
for alert in response.json():
http_result[alert.get('condition', {}).get('metric')] = alert
__context__[key] = http_result
if not __context__.get(key):
return []
alerts = __context__[key].values()
if metric_name:
return __context__[key].get(metric_name)
return [alert['_id'] for alert in alerts if '_id' in alert] | [
"def",
"get_alert_config",
"(",
"deployment_id",
",",
"metric_name",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"profile",
"=",
"\"telemetry\"",
")",
":",
"auth",
"=",
"_auth",
"(",
"profile",
"=",
"profile",
")",
"alert",
"=",
"False",
"key",
"=",
"... | Get all alert definitions associated with a given deployment or if metric_name
is specified, obtain the specific alert config
Returns dictionary or list of dictionaries.
CLI Example:
salt myminion telemetry.get_alert_config rs-ds033197 currentConnections profile=telemetry
salt myminion telemetry.get_alert_config rs-ds033197 profile=telemetry | [
"Get",
"all",
"alert",
"definitions",
"associated",
"with",
"a",
"given",
"deployment",
"or",
"if",
"metric_name",
"is",
"specified",
"obtain",
"the",
"specific",
"alert",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L119-L159 | train |
saltstack/salt | salt/modules/telemetry.py | get_notification_channel_id | def get_notification_channel_id(notify_channel, profile="telemetry"):
'''
Given an email address, creates a notification-channels
if one is not found and also returns the corresponding
notification channel id.
notify_channel
Email escalation policy
profile
A dict of telemetry config information.
CLI Example:
salt myminion telemetry.get_notification_channel_id userx@company.com profile=telemetry
'''
# This helper is used to procure the channel ids
# used to notify when the alarm threshold is violated
auth = _auth(profile=profile)
notification_channel_id = _retrieve_channel_id(notify_channel)
if not notification_channel_id:
log.info("%s channel does not exist, creating.", notify_channel)
# create the notification channel and cache the id
post_url = _get_telemetry_base(profile) + "/notification-channels"
data = {
"_type": "EmailNotificationChannel",
"name": notify_channel[:notify_channel.find('@')] + 'EscalationPolicy',
"email": notify_channel
}
response = requests.post(post_url, data=salt.utils.json.dumps(data), headers=auth)
if response.status_code == 200:
log.info("Successfully created EscalationPolicy %s with EmailNotificationChannel %s",
data.get('name'), notify_channel)
notification_channel_id = response.json().get('_id')
__context__["telemetry.channels"][notify_channel] = notification_channel_id
else:
raise Exception("Failed to created notification channel {0}".format(notify_channel))
return notification_channel_id | python | def get_notification_channel_id(notify_channel, profile="telemetry"):
'''
Given an email address, creates a notification-channels
if one is not found and also returns the corresponding
notification channel id.
notify_channel
Email escalation policy
profile
A dict of telemetry config information.
CLI Example:
salt myminion telemetry.get_notification_channel_id userx@company.com profile=telemetry
'''
# This helper is used to procure the channel ids
# used to notify when the alarm threshold is violated
auth = _auth(profile=profile)
notification_channel_id = _retrieve_channel_id(notify_channel)
if not notification_channel_id:
log.info("%s channel does not exist, creating.", notify_channel)
# create the notification channel and cache the id
post_url = _get_telemetry_base(profile) + "/notification-channels"
data = {
"_type": "EmailNotificationChannel",
"name": notify_channel[:notify_channel.find('@')] + 'EscalationPolicy',
"email": notify_channel
}
response = requests.post(post_url, data=salt.utils.json.dumps(data), headers=auth)
if response.status_code == 200:
log.info("Successfully created EscalationPolicy %s with EmailNotificationChannel %s",
data.get('name'), notify_channel)
notification_channel_id = response.json().get('_id')
__context__["telemetry.channels"][notify_channel] = notification_channel_id
else:
raise Exception("Failed to created notification channel {0}".format(notify_channel))
return notification_channel_id | [
"def",
"get_notification_channel_id",
"(",
"notify_channel",
",",
"profile",
"=",
"\"telemetry\"",
")",
":",
"# This helper is used to procure the channel ids",
"# used to notify when the alarm threshold is violated",
"auth",
"=",
"_auth",
"(",
"profile",
"=",
"profile",
")",
... | Given an email address, creates a notification-channels
if one is not found and also returns the corresponding
notification channel id.
notify_channel
Email escalation policy
profile
A dict of telemetry config information.
CLI Example:
salt myminion telemetry.get_notification_channel_id userx@company.com profile=telemetry | [
"Given",
"an",
"email",
"address",
"creates",
"a",
"notification",
"-",
"channels",
"if",
"one",
"is",
"not",
"found",
"and",
"also",
"returns",
"the",
"corresponding",
"notification",
"channel",
"id",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L162-L203 | train |
saltstack/salt | salt/modules/telemetry.py | get_alarms | def get_alarms(deployment_id, profile="telemetry"):
'''
get all the alarms set up against the current deployment
Returns dictionary of alarm information
CLI Example:
salt myminion telemetry.get_alarms rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
try:
response = requests.get(_get_telemetry_base(profile) + "/alerts?deployment={0}".format(deployment_id), headers=auth)
except requests.exceptions.RequestException as e:
log.error(six.text_type(e))
return False
if response.status_code == 200:
alarms = response.json()
if alarms:
return alarms
return 'No alarms defined for deployment: {0}'.format(deployment_id)
else:
# Non 200 response, sent back the error response'
return {'err_code': response.status_code, 'err_msg': salt.utils.json.loads(response.text).get('err', '')} | python | def get_alarms(deployment_id, profile="telemetry"):
'''
get all the alarms set up against the current deployment
Returns dictionary of alarm information
CLI Example:
salt myminion telemetry.get_alarms rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
try:
response = requests.get(_get_telemetry_base(profile) + "/alerts?deployment={0}".format(deployment_id), headers=auth)
except requests.exceptions.RequestException as e:
log.error(six.text_type(e))
return False
if response.status_code == 200:
alarms = response.json()
if alarms:
return alarms
return 'No alarms defined for deployment: {0}'.format(deployment_id)
else:
# Non 200 response, sent back the error response'
return {'err_code': response.status_code, 'err_msg': salt.utils.json.loads(response.text).get('err', '')} | [
"def",
"get_alarms",
"(",
"deployment_id",
",",
"profile",
"=",
"\"telemetry\"",
")",
":",
"auth",
"=",
"_auth",
"(",
"profile",
"=",
"profile",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"_get_telemetry_base",
"(",
"profile",
")",
"+",... | get all the alarms set up against the current deployment
Returns dictionary of alarm information
CLI Example:
salt myminion telemetry.get_alarms rs-ds033197 profile=telemetry | [
"get",
"all",
"the",
"alarms",
"set",
"up",
"against",
"the",
"current",
"deployment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L206-L234 | train |
saltstack/salt | salt/modules/telemetry.py | create_alarm | def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
'''
create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry
'''
auth = _auth(api_key, profile)
request_uri = _get_telemetry_base(profile) + "/alerts"
key = "telemetry.{0}.alerts".format(deployment_id)
# set the notification channels if not already set
post_body = {
"deployment": deployment_id,
"filter": data.get('filter'),
"notificationChannel": get_notification_channel_id(data.get('escalate_to')).split(),
"condition": {
"metric": metric_name,
"max": data.get('max'),
"min": data.get('min')
}
}
try:
response = requests.post(request_uri, data=salt.utils.json.dumps(post_body), headers=auth)
except requests.exceptions.RequestException as e:
# TODO: May be we should retry?
log.error(six.text_type(e))
if response.status_code >= 200 and response.status_code < 300:
# update cache
log.info('Created alarm on metric: %s in deployment: %s', metric_name, deployment_id)
log.debug('Updating cache for metric %s in deployment %s: %s',
metric_name, deployment_id, response.json())
_update_cache(deployment_id, metric_name, response.json())
else:
log.error(
'Failed to create alarm on metric: %s in '
'deployment %s: payload: %s',
metric_name, deployment_id, salt.utils.json.dumps(post_body)
)
return response.status_code >= 200 and response.status_code < 300, response.json() | python | def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
'''
create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry
'''
auth = _auth(api_key, profile)
request_uri = _get_telemetry_base(profile) + "/alerts"
key = "telemetry.{0}.alerts".format(deployment_id)
# set the notification channels if not already set
post_body = {
"deployment": deployment_id,
"filter": data.get('filter'),
"notificationChannel": get_notification_channel_id(data.get('escalate_to')).split(),
"condition": {
"metric": metric_name,
"max": data.get('max'),
"min": data.get('min')
}
}
try:
response = requests.post(request_uri, data=salt.utils.json.dumps(post_body), headers=auth)
except requests.exceptions.RequestException as e:
# TODO: May be we should retry?
log.error(six.text_type(e))
if response.status_code >= 200 and response.status_code < 300:
# update cache
log.info('Created alarm on metric: %s in deployment: %s', metric_name, deployment_id)
log.debug('Updating cache for metric %s in deployment %s: %s',
metric_name, deployment_id, response.json())
_update_cache(deployment_id, metric_name, response.json())
else:
log.error(
'Failed to create alarm on metric: %s in '
'deployment %s: payload: %s',
metric_name, deployment_id, salt.utils.json.dumps(post_body)
)
return response.status_code >= 200 and response.status_code < 300, response.json() | [
"def",
"create_alarm",
"(",
"deployment_id",
",",
"metric_name",
",",
"data",
",",
"api_key",
"=",
"None",
",",
"profile",
"=",
"\"telemetry\"",
")",
":",
"auth",
"=",
"_auth",
"(",
"api_key",
",",
"profile",
")",
"request_uri",
"=",
"_get_telemetry_base",
"... | create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry | [
"create",
"an",
"telemetry",
"alarms",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L237-L287 | train |
saltstack/salt | salt/modules/telemetry.py | update_alarm | def update_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
'''
update an telemetry alarms. data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.update_alarm rs-ds033197 {} profile=telemetry
'''
auth = _auth(api_key, profile)
alert = get_alert_config(deployment_id, metric_name, api_key, profile)
if not alert:
return False, "No entity found matching deployment {0} and alarms {1}".format(deployment_id, metric_name)
request_uri = _get_telemetry_base(profile) + '/alerts/' + alert['_id']
# set the notification channels if not already set
post_body = {
"deployment": deployment_id,
"filter": data.get('filter'),
"notificationChannel": get_notification_channel_id(data.get('escalate_to')).split(),
"condition": {
"metric": metric_name,
"max": data.get('max'),
"min": data.get('min')
}
}
try:
response = requests.put(request_uri, data=salt.utils.json.dumps(post_body), headers=auth)
except requests.exceptions.RequestException as e:
log.error('Update failed: %s', e)
return False, six.text_type(e)
if response.status_code >= 200 and response.status_code < 300:
# Also update cache
log.debug('Updating cache for metric %s in deployment %s: %s',
metric_name, deployment_id, response.json())
_update_cache(deployment_id, metric_name, response.json())
log.info('Updated alarm on metric: %s in deployment: %s', metric_name, deployment_id)
return True, response.json()
err_msg = six.text_type( # future lint: disable=blacklisted-function
'Failed to create alarm on metric: {0} in deployment: {1} '
'payload: {2}').format(
salt.utils.stringutils.to_unicode(metric_name),
salt.utils.stringutils.to_unicode(deployment_id),
salt.utils.json.dumps(post_body)
)
log.error(err_msg)
return False, err_msg | python | def update_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
'''
update an telemetry alarms. data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.update_alarm rs-ds033197 {} profile=telemetry
'''
auth = _auth(api_key, profile)
alert = get_alert_config(deployment_id, metric_name, api_key, profile)
if not alert:
return False, "No entity found matching deployment {0} and alarms {1}".format(deployment_id, metric_name)
request_uri = _get_telemetry_base(profile) + '/alerts/' + alert['_id']
# set the notification channels if not already set
post_body = {
"deployment": deployment_id,
"filter": data.get('filter'),
"notificationChannel": get_notification_channel_id(data.get('escalate_to')).split(),
"condition": {
"metric": metric_name,
"max": data.get('max'),
"min": data.get('min')
}
}
try:
response = requests.put(request_uri, data=salt.utils.json.dumps(post_body), headers=auth)
except requests.exceptions.RequestException as e:
log.error('Update failed: %s', e)
return False, six.text_type(e)
if response.status_code >= 200 and response.status_code < 300:
# Also update cache
log.debug('Updating cache for metric %s in deployment %s: %s',
metric_name, deployment_id, response.json())
_update_cache(deployment_id, metric_name, response.json())
log.info('Updated alarm on metric: %s in deployment: %s', metric_name, deployment_id)
return True, response.json()
err_msg = six.text_type( # future lint: disable=blacklisted-function
'Failed to create alarm on metric: {0} in deployment: {1} '
'payload: {2}').format(
salt.utils.stringutils.to_unicode(metric_name),
salt.utils.stringutils.to_unicode(deployment_id),
salt.utils.json.dumps(post_body)
)
log.error(err_msg)
return False, err_msg | [
"def",
"update_alarm",
"(",
"deployment_id",
",",
"metric_name",
",",
"data",
",",
"api_key",
"=",
"None",
",",
"profile",
"=",
"\"telemetry\"",
")",
":",
"auth",
"=",
"_auth",
"(",
"api_key",
",",
"profile",
")",
"alert",
"=",
"get_alert_config",
"(",
"de... | update an telemetry alarms. data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.update_alarm rs-ds033197 {} profile=telemetry | [
"update",
"an",
"telemetry",
"alarms",
".",
"data",
"is",
"a",
"dict",
"of",
"alert",
"configuration",
"data",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L290-L343 | train |
saltstack/salt | salt/modules/telemetry.py | delete_alarms | def delete_alarms(deployment_id, alert_id=None, metric_name=None, api_key=None, profile='telemetry'):
'''delete an alert specified by alert_id or if not specified blows away all the alerts
in the current deployment.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.delete_alarms rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
if alert_id is None:
# Delete all the alarms associated with this deployment
alert_ids = get_alert_config(deployment_id, api_key=api_key, profile=profile)
else:
alert_ids = [alert_id]
if not alert_ids:
return False, "failed to find alert associated with deployment: {0}".format(deployment_id)
failed_to_delete = []
for id in alert_ids:
delete_url = _get_telemetry_base(profile) + "/alerts/{0}".format(id)
try:
response = requests.delete(delete_url, headers=auth)
if metric_name:
log.debug("updating cache and delete %s key from %s",
metric_name, deployment_id)
_update_cache(deployment_id, metric_name, None)
except requests.exceptions.RequestException as e:
log.error('Delete failed: %s', e)
if response.status_code != 200:
failed_to_delete.append(id)
if failed_to_delete:
return False, "Failed to delete {0} alarms in deployment: {1}" .format(', '.join(failed_to_delete), deployment_id)
return True, "Successfully deleted {0} alerts in deployment: {1}".format(', '.join(alert_ids), deployment_id) | python | def delete_alarms(deployment_id, alert_id=None, metric_name=None, api_key=None, profile='telemetry'):
'''delete an alert specified by alert_id or if not specified blows away all the alerts
in the current deployment.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.delete_alarms rs-ds033197 profile=telemetry
'''
auth = _auth(profile=profile)
if alert_id is None:
# Delete all the alarms associated with this deployment
alert_ids = get_alert_config(deployment_id, api_key=api_key, profile=profile)
else:
alert_ids = [alert_id]
if not alert_ids:
return False, "failed to find alert associated with deployment: {0}".format(deployment_id)
failed_to_delete = []
for id in alert_ids:
delete_url = _get_telemetry_base(profile) + "/alerts/{0}".format(id)
try:
response = requests.delete(delete_url, headers=auth)
if metric_name:
log.debug("updating cache and delete %s key from %s",
metric_name, deployment_id)
_update_cache(deployment_id, metric_name, None)
except requests.exceptions.RequestException as e:
log.error('Delete failed: %s', e)
if response.status_code != 200:
failed_to_delete.append(id)
if failed_to_delete:
return False, "Failed to delete {0} alarms in deployment: {1}" .format(', '.join(failed_to_delete), deployment_id)
return True, "Successfully deleted {0} alerts in deployment: {1}".format(', '.join(alert_ids), deployment_id) | [
"def",
"delete_alarms",
"(",
"deployment_id",
",",
"alert_id",
"=",
"None",
",",
"metric_name",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"profile",
"=",
"'telemetry'",
")",
":",
"auth",
"=",
"_auth",
"(",
"profile",
"=",
"profile",
")",
"if",
"aler... | delete an alert specified by alert_id or if not specified blows away all the alerts
in the current deployment.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.delete_alarms rs-ds033197 profile=telemetry | [
"delete",
"an",
"alert",
"specified",
"by",
"alert_id",
"or",
"if",
"not",
"specified",
"blows",
"away",
"all",
"the",
"alerts",
"in",
"the",
"current",
"deployment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/telemetry.py#L346-L388 | train |
saltstack/salt | salt/utils/http.py | __decompressContent | def __decompressContent(coding, pgctnt):
'''
Decompress returned HTTP content depending on the specified encoding.
Currently supports identity/none, deflate, and gzip, which should
cover 99%+ of the content on the internet.
'''
log.trace("Decompressing %s byte content with compression type: %s", len(pgctnt), coding)
if coding == 'deflate':
pgctnt = zlib.decompress(pgctnt, -zlib.MAX_WBITS)
elif coding == 'gzip':
buf = io.BytesIO(pgctnt)
f = gzip.GzipFile(fileobj=buf)
pgctnt = f.read()
elif coding == "sdch":
raise ValueError("SDCH compression is not currently supported")
elif coding == "br":
raise ValueError("Brotli compression is not currently supported")
elif coding == "compress":
raise ValueError("LZW compression is not currently supported")
elif coding == 'identity':
pass
log.trace("Content size after decompression: %s", len(pgctnt))
return pgctnt | python | def __decompressContent(coding, pgctnt):
'''
Decompress returned HTTP content depending on the specified encoding.
Currently supports identity/none, deflate, and gzip, which should
cover 99%+ of the content on the internet.
'''
log.trace("Decompressing %s byte content with compression type: %s", len(pgctnt), coding)
if coding == 'deflate':
pgctnt = zlib.decompress(pgctnt, -zlib.MAX_WBITS)
elif coding == 'gzip':
buf = io.BytesIO(pgctnt)
f = gzip.GzipFile(fileobj=buf)
pgctnt = f.read()
elif coding == "sdch":
raise ValueError("SDCH compression is not currently supported")
elif coding == "br":
raise ValueError("Brotli compression is not currently supported")
elif coding == "compress":
raise ValueError("LZW compression is not currently supported")
elif coding == 'identity':
pass
log.trace("Content size after decompression: %s", len(pgctnt))
return pgctnt | [
"def",
"__decompressContent",
"(",
"coding",
",",
"pgctnt",
")",
":",
"log",
".",
"trace",
"(",
"\"Decompressing %s byte content with compression type: %s\"",
",",
"len",
"(",
"pgctnt",
")",
",",
"coding",
")",
"if",
"coding",
"==",
"'deflate'",
":",
"pgctnt",
"... | Decompress returned HTTP content depending on the specified encoding.
Currently supports identity/none, deflate, and gzip, which should
cover 99%+ of the content on the internet. | [
"Decompress",
"returned",
"HTTP",
"content",
"depending",
"on",
"the",
"specified",
"encoding",
".",
"Currently",
"supports",
"identity",
"/",
"none",
"deflate",
"and",
"gzip",
"which",
"should",
"cover",
"99%",
"+",
"of",
"the",
"content",
"on",
"the",
"inter... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L101-L129 | train |
saltstack/salt | salt/utils/http.py | query | def query(url,
method='GET',
params=None,
data=None,
data_file=None,
header_dict=None,
header_list=None,
header_file=None,
username=None,
password=None,
auth=None,
decode=False,
decode_type='auto',
status=False,
headers=False,
text=False,
cookies=None,
cookie_jar=None,
cookie_format='lwp',
persist_session=False,
session_cookie_jar=None,
data_render=False,
data_renderer=None,
header_render=False,
header_renderer=None,
template_dict=None,
test=False,
test_url=None,
node='minion',
port=80,
opts=None,
backend=None,
ca_bundle=None,
verify_ssl=None,
cert=None,
text_out=None,
headers_out=None,
decode_out=None,
stream=False,
streaming_callback=None,
header_callback=None,
handle=False,
agent=USERAGENT,
hide_fields=None,
raise_error=True,
**kwargs):
'''
Query a resource, and decode the return data
'''
ret = {}
if opts is None:
if node == 'master':
opts = salt.config.master_config(
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
elif node == 'minion':
opts = salt.config.minion_config(
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
else:
opts = {}
if not backend:
backend = opts.get('backend', 'tornado')
match = re.match(r'https?://((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)($|/)', url)
if not match:
salt.utils.network.refresh_dns()
if backend == 'requests':
if HAS_REQUESTS is False:
ret['error'] = ('http.query has been set to use requests, but the '
'requests library does not seem to be installed')
log.error(ret['error'])
return ret
else:
requests_log = logging.getLogger('requests')
requests_log.setLevel(logging.WARNING)
# Some libraries don't support separation of url and GET parameters
# Don't need a try/except block, since Salt depends on tornado
url_full = tornado.httputil.url_concat(url, params) if params else url
if ca_bundle is None:
ca_bundle = get_ca_bundle(opts)
if verify_ssl is None:
verify_ssl = opts.get('verify_ssl', True)
if cert is None:
cert = opts.get('cert', None)
if data_file is not None:
data = _render(
data_file, data_render, data_renderer, template_dict, opts
)
# Make sure no secret fields show up in logs
log_url = sanitize_url(url_full, hide_fields)
log.debug('Requesting URL %s using %s method', log_url, method)
log.debug("Using backend: %s", backend)
if method == 'POST' and log.isEnabledFor(logging.TRACE):
# Make sure no secret fields show up in logs
if isinstance(data, dict):
log_data = data.copy()
if isinstance(hide_fields, list):
for item in data:
for field in hide_fields:
if item == field:
log_data[item] = 'XXXXXXXXXX'
log.trace('Request POST Data: %s', pprint.pformat(log_data))
else:
log.trace('Request POST Data: %s', pprint.pformat(data))
if header_file is not None:
header_tpl = _render(
header_file, header_render, header_renderer, template_dict, opts
)
if isinstance(header_tpl, dict):
header_dict = header_tpl
else:
header_list = header_tpl.splitlines()
if header_dict is None:
header_dict = {}
if header_list is None:
header_list = []
if cookie_jar is None:
cookie_jar = os.path.join(opts.get('cachedir', salt.syspaths.CACHE_DIR), 'cookies.txt')
if session_cookie_jar is None:
session_cookie_jar = os.path.join(opts.get('cachedir', salt.syspaths.CACHE_DIR), 'cookies.session.p')
if persist_session is True and HAS_MSGPACK:
# TODO: This is hackish; it will overwrite the session cookie jar with
# all cookies from this one connection, rather than behaving like a
# proper cookie jar. Unfortunately, since session cookies do not
# contain expirations, they can't be stored in a proper cookie jar.
if os.path.isfile(session_cookie_jar):
with salt.utils.files.fopen(session_cookie_jar, 'rb') as fh_:
session_cookies = salt.utils.msgpack.load(fh_)
if isinstance(session_cookies, dict):
header_dict.update(session_cookies)
else:
with salt.utils.files.fopen(session_cookie_jar, 'wb') as fh_:
salt.utils.msgpack.dump('', fh_)
for header in header_list:
comps = header.split(':')
if len(comps) < 2:
continue
header_dict[comps[0].strip()] = comps[1].strip()
if not auth:
if username and password:
auth = (username, password)
if agent == USERAGENT:
user_agent = opts.get('user_agent', None)
if user_agent:
agent = user_agent
agent = '{0} http.query()'.format(agent)
header_dict['User-agent'] = agent
if backend == 'requests':
sess = requests.Session()
sess.auth = auth
sess.headers.update(header_dict)
log.trace('Request Headers: %s', sess.headers)
sess_cookies = sess.cookies
sess.verify = verify_ssl
elif backend == 'urllib2':
sess_cookies = None
else:
# Tornado
sess_cookies = None
if cookies is not None:
if cookie_format == 'mozilla':
sess_cookies = salt.ext.six.moves.http_cookiejar.MozillaCookieJar(cookie_jar)
else:
sess_cookies = salt.ext.six.moves.http_cookiejar.LWPCookieJar(cookie_jar)
if not os.path.isfile(cookie_jar):
sess_cookies.save()
sess_cookies.load()
if test is True:
if test_url is None:
return {}
else:
url = test_url
ret['test'] = True
if backend == 'requests':
req_kwargs = {}
if stream is True:
if requests.__version__[0] == '0':
# 'stream' was called 'prefetch' before 1.0, with flipped meaning
req_kwargs['prefetch'] = False
else:
req_kwargs['stream'] = True
# Client-side cert handling
if cert is not None:
if isinstance(cert, six.string_types):
if os.path.exists(cert):
req_kwargs['cert'] = cert
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
req_kwargs['cert'] = cert
else:
log.error('The client-side certificate path that'
' was passed is not valid: %s', cert)
result = sess.request(
method, url, params=params, data=data, **req_kwargs
)
result.raise_for_status()
if stream is True:
# fake a HTTP response header
header_callback('HTTP/1.0 {0} MESSAGE'.format(result.status_code))
# fake streaming the content
streaming_callback(result.content)
return {
'handle': result,
}
if handle is True:
return {
'handle': result,
'body': result.content,
}
log.debug('Final URL location of Response: %s',
sanitize_url(result.url, hide_fields))
result_status_code = result.status_code
result_headers = result.headers
result_text = result.content
result_cookies = result.cookies
body = result.content
if not isinstance(body, six.text_type):
body = body.decode(result.encoding or 'utf-8')
ret['body'] = body
elif backend == 'urllib2':
request = urllib_request.Request(url_full, data)
handlers = [
urllib_request.HTTPHandler,
urllib_request.HTTPCookieProcessor(sess_cookies)
]
if url.startswith('https'):
hostname = request.get_host()
handlers[0] = urllib_request.HTTPSHandler(1)
if not HAS_MATCHHOSTNAME:
log.warning('match_hostname() not available, SSL hostname checking '
'not available. THIS CONNECTION MAY NOT BE SECURE!')
elif verify_ssl is False:
log.warning('SSL certificate verification has been explicitly '
'disabled. THIS CONNECTION MAY NOT BE SECURE!')
else:
if ':' in hostname:
hostname, port = hostname.split(':')
else:
port = 443
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, int(port)))
sockwrap = ssl.wrap_socket(
sock,
ca_certs=ca_bundle,
cert_reqs=ssl.CERT_REQUIRED
)
try:
match_hostname(sockwrap.getpeercert(), hostname)
except CertificateError as exc:
ret['error'] = (
'The certificate was invalid. '
'Error returned was: %s',
pprint.pformat(exc)
)
return ret
# Client-side cert handling
if cert is not None:
cert_chain = None
if isinstance(cert, six.string_types):
if os.path.exists(cert):
cert_chain = (cert)
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
cert_chain = cert
else:
log.error('The client-side certificate path that was '
'passed is not valid: %s', cert)
return
if hasattr(ssl, 'SSLContext'):
# Python >= 2.7.9
context = ssl.SSLContext.load_cert_chain(*cert_chain)
handlers.append(urllib_request.HTTPSHandler(context=context)) # pylint: disable=E1123
else:
# Python < 2.7.9
cert_kwargs = {
'host': request.get_host(),
'port': port,
'cert_file': cert_chain[0]
}
if len(cert_chain) > 1:
cert_kwargs['key_file'] = cert_chain[1]
handlers[0] = salt.ext.six.moves.http_client.HTTPSConnection(**cert_kwargs)
opener = urllib_request.build_opener(*handlers)
for header in header_dict:
request.add_header(header, header_dict[header])
request.get_method = lambda: method
try:
result = opener.open(request)
except URLError as exc:
return {'Error': six.text_type(exc)}
if stream is True or handle is True:
return {
'handle': result,
'body': result.content,
}
result_status_code = result.code
result_headers = dict(result.info())
result_text = result.read()
if 'Content-Type' in result_headers:
res_content_type, res_params = cgi.parse_header(result_headers['Content-Type'])
if res_content_type.startswith('text/') and \
'charset' in res_params and \
not isinstance(result_text, six.text_type):
result_text = result_text.decode(res_params['charset'])
if six.PY3 and isinstance(result_text, bytes):
result_text = result.body.decode('utf-8')
ret['body'] = result_text
else:
# Tornado
req_kwargs = {}
# Client-side cert handling
if cert is not None:
if isinstance(cert, six.string_types):
if os.path.exists(cert):
req_kwargs['client_cert'] = cert
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
req_kwargs['client_cert'] = cert[0]
req_kwargs['client_key'] = cert[1]
else:
log.error('The client-side certificate path that '
'was passed is not valid: %s', cert)
if isinstance(data, dict):
data = _urlencode(data)
if verify_ssl:
req_kwargs['ca_certs'] = ca_bundle
max_body = opts.get('http_max_body', salt.config.DEFAULT_MINION_OPTS['http_max_body'])
connect_timeout = opts.get('http_connect_timeout', salt.config.DEFAULT_MINION_OPTS['http_connect_timeout'])
timeout = opts.get('http_request_timeout', salt.config.DEFAULT_MINION_OPTS['http_request_timeout'])
client_argspec = None
proxy_host = opts.get('proxy_host', None)
if proxy_host:
# tornado requires a str for proxy_host, cannot be a unicode str in py2
proxy_host = salt.utils.stringutils.to_str(proxy_host)
proxy_port = opts.get('proxy_port', None)
proxy_username = opts.get('proxy_username', None)
if proxy_username:
# tornado requires a str, cannot be unicode str in py2
proxy_username = salt.utils.stringutils.to_str(proxy_username)
proxy_password = opts.get('proxy_password', None)
if proxy_password:
# tornado requires a str, cannot be unicode str in py2
proxy_password = salt.utils.stringutils.to_str(proxy_password)
no_proxy = opts.get('no_proxy', [])
# Since tornado doesnt support no_proxy, we'll always hand it empty proxies or valid ones
# except we remove the valid ones if a url has a no_proxy hostname in it
if urlparse(url_full).hostname in no_proxy:
proxy_host = None
proxy_port = None
# We want to use curl_http if we have a proxy defined
if proxy_host and proxy_port:
if HAS_CURL_HTTPCLIENT is False:
ret['error'] = ('proxy_host and proxy_port has been set. This requires pycurl and tornado, '
'but the libraries does not seem to be installed')
log.error(ret['error'])
return ret
tornado.httpclient.AsyncHTTPClient.configure('tornado.curl_httpclient.CurlAsyncHTTPClient')
client_argspec = salt.utils.args.get_function_argspec(
tornado.curl_httpclient.CurlAsyncHTTPClient.initialize)
else:
client_argspec = salt.utils.args.get_function_argspec(
tornado.simple_httpclient.SimpleAsyncHTTPClient.initialize)
supports_max_body_size = 'max_body_size' in client_argspec.args
req_kwargs.update({
'method': method,
'headers': header_dict,
'auth_username': username,
'auth_password': password,
'body': data,
'validate_cert': verify_ssl,
'allow_nonstandard_methods': True,
'streaming_callback': streaming_callback,
'header_callback': header_callback,
'connect_timeout': connect_timeout,
'request_timeout': timeout,
'proxy_host': proxy_host,
'proxy_port': proxy_port,
'proxy_username': proxy_username,
'proxy_password': proxy_password,
'raise_error': raise_error,
'decompress_response': False,
})
# Unicode types will cause a TypeError when Tornado's curl HTTPClient
# invokes setopt. Therefore, make sure all arguments we pass which
# contain strings are str types.
req_kwargs = salt.utils.data.decode(req_kwargs, to_str=True)
try:
download_client = HTTPClient(max_body_size=max_body) \
if supports_max_body_size \
else HTTPClient()
result = download_client.fetch(url_full, **req_kwargs)
except tornado.httpclient.HTTPError as exc:
ret['status'] = exc.code
ret['error'] = six.text_type(exc)
return ret
except socket.gaierror as exc:
if status is True:
ret['status'] = 0
ret['error'] = six.text_type(exc)
return ret
if stream is True or handle is True:
return {
'handle': result,
'body': result.body,
}
result_status_code = result.code
result_headers = result.headers
result_text = result.body
if 'Content-Type' in result_headers:
res_content_type, res_params = cgi.parse_header(result_headers['Content-Type'])
if res_content_type.startswith('text/') and \
'charset' in res_params and \
not isinstance(result_text, six.text_type):
result_text = result_text.decode(res_params['charset'])
if six.PY3 and isinstance(result_text, bytes):
result_text = result_text.decode('utf-8')
ret['body'] = result_text
if 'Set-Cookie' in result_headers and cookies is not None:
result_cookies = parse_cookie_header(result_headers['Set-Cookie'])
for item in result_cookies:
sess_cookies.set_cookie(item)
else:
result_cookies = None
if isinstance(result_headers, list):
result_headers_dict = {}
for header in result_headers:
comps = header.split(':')
result_headers_dict[comps[0].strip()] = ':'.join(comps[1:]).strip()
result_headers = result_headers_dict
log.debug('Response Status Code: %s', result_status_code)
log.trace('Response Headers: %s', result_headers)
log.trace('Response Cookies: %s', sess_cookies)
# log.trace("Content: %s", result_text)
coding = result_headers.get('Content-Encoding', "identity")
# Requests will always decompress the content, and working around that is annoying.
if backend != 'requests':
result_text = __decompressContent(coding, result_text)
try:
log.trace('Response Text: %s', result_text)
except UnicodeEncodeError as exc:
log.trace('Cannot Trace Log Response Text: %s. This may be due to '
'incompatibilities between requests and logging.', exc)
if text_out is not None:
with salt.utils.files.fopen(text_out, 'w') as tof:
tof.write(result_text)
if headers_out is not None and os.path.exists(headers_out):
with salt.utils.files.fopen(headers_out, 'w') as hof:
hof.write(result_headers)
if cookies is not None:
sess_cookies.save()
if persist_session is True and HAS_MSGPACK:
# TODO: See persist_session above
if 'set-cookie' in result_headers:
with salt.utils.files.fopen(session_cookie_jar, 'wb') as fh_:
session_cookies = result_headers.get('set-cookie', None)
if session_cookies is not None:
salt.utils.msgpack.dump({'Cookie': session_cookies}, fh_)
else:
salt.utils.msgpack.dump('', fh_)
if status is True:
ret['status'] = result_status_code
if headers is True:
ret['headers'] = result_headers
if decode is True:
if decode_type == 'auto':
content_type = result_headers.get(
'content-type', 'application/json'
)
if 'xml' in content_type:
decode_type = 'xml'
elif 'json' in content_type:
decode_type = 'json'
elif 'yaml' in content_type:
decode_type = 'yaml'
else:
decode_type = 'plain'
valid_decodes = ('json', 'xml', 'yaml', 'plain')
if decode_type not in valid_decodes:
ret['error'] = (
'Invalid decode_type specified. '
'Valid decode types are: {0}'.format(
pprint.pformat(valid_decodes)
)
)
log.error(ret['error'])
return ret
if decode_type == 'json':
ret['dict'] = salt.utils.json.loads(result_text)
elif decode_type == 'xml':
ret['dict'] = []
items = ET.fromstring(result_text)
for item in items:
ret['dict'].append(xml.to_dict(item))
elif decode_type == 'yaml':
ret['dict'] = salt.utils.data.decode(salt.utils.yaml.safe_load(result_text))
else:
text = True
if decode_out:
with salt.utils.files.fopen(decode_out, 'w') as dof:
dof.write(result_text)
if text is True:
ret['text'] = result_text
return ret | python | def query(url,
method='GET',
params=None,
data=None,
data_file=None,
header_dict=None,
header_list=None,
header_file=None,
username=None,
password=None,
auth=None,
decode=False,
decode_type='auto',
status=False,
headers=False,
text=False,
cookies=None,
cookie_jar=None,
cookie_format='lwp',
persist_session=False,
session_cookie_jar=None,
data_render=False,
data_renderer=None,
header_render=False,
header_renderer=None,
template_dict=None,
test=False,
test_url=None,
node='minion',
port=80,
opts=None,
backend=None,
ca_bundle=None,
verify_ssl=None,
cert=None,
text_out=None,
headers_out=None,
decode_out=None,
stream=False,
streaming_callback=None,
header_callback=None,
handle=False,
agent=USERAGENT,
hide_fields=None,
raise_error=True,
**kwargs):
'''
Query a resource, and decode the return data
'''
ret = {}
if opts is None:
if node == 'master':
opts = salt.config.master_config(
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
elif node == 'minion':
opts = salt.config.minion_config(
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
else:
opts = {}
if not backend:
backend = opts.get('backend', 'tornado')
match = re.match(r'https?://((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)($|/)', url)
if not match:
salt.utils.network.refresh_dns()
if backend == 'requests':
if HAS_REQUESTS is False:
ret['error'] = ('http.query has been set to use requests, but the '
'requests library does not seem to be installed')
log.error(ret['error'])
return ret
else:
requests_log = logging.getLogger('requests')
requests_log.setLevel(logging.WARNING)
# Some libraries don't support separation of url and GET parameters
# Don't need a try/except block, since Salt depends on tornado
url_full = tornado.httputil.url_concat(url, params) if params else url
if ca_bundle is None:
ca_bundle = get_ca_bundle(opts)
if verify_ssl is None:
verify_ssl = opts.get('verify_ssl', True)
if cert is None:
cert = opts.get('cert', None)
if data_file is not None:
data = _render(
data_file, data_render, data_renderer, template_dict, opts
)
# Make sure no secret fields show up in logs
log_url = sanitize_url(url_full, hide_fields)
log.debug('Requesting URL %s using %s method', log_url, method)
log.debug("Using backend: %s", backend)
if method == 'POST' and log.isEnabledFor(logging.TRACE):
# Make sure no secret fields show up in logs
if isinstance(data, dict):
log_data = data.copy()
if isinstance(hide_fields, list):
for item in data:
for field in hide_fields:
if item == field:
log_data[item] = 'XXXXXXXXXX'
log.trace('Request POST Data: %s', pprint.pformat(log_data))
else:
log.trace('Request POST Data: %s', pprint.pformat(data))
if header_file is not None:
header_tpl = _render(
header_file, header_render, header_renderer, template_dict, opts
)
if isinstance(header_tpl, dict):
header_dict = header_tpl
else:
header_list = header_tpl.splitlines()
if header_dict is None:
header_dict = {}
if header_list is None:
header_list = []
if cookie_jar is None:
cookie_jar = os.path.join(opts.get('cachedir', salt.syspaths.CACHE_DIR), 'cookies.txt')
if session_cookie_jar is None:
session_cookie_jar = os.path.join(opts.get('cachedir', salt.syspaths.CACHE_DIR), 'cookies.session.p')
if persist_session is True and HAS_MSGPACK:
# TODO: This is hackish; it will overwrite the session cookie jar with
# all cookies from this one connection, rather than behaving like a
# proper cookie jar. Unfortunately, since session cookies do not
# contain expirations, they can't be stored in a proper cookie jar.
if os.path.isfile(session_cookie_jar):
with salt.utils.files.fopen(session_cookie_jar, 'rb') as fh_:
session_cookies = salt.utils.msgpack.load(fh_)
if isinstance(session_cookies, dict):
header_dict.update(session_cookies)
else:
with salt.utils.files.fopen(session_cookie_jar, 'wb') as fh_:
salt.utils.msgpack.dump('', fh_)
for header in header_list:
comps = header.split(':')
if len(comps) < 2:
continue
header_dict[comps[0].strip()] = comps[1].strip()
if not auth:
if username and password:
auth = (username, password)
if agent == USERAGENT:
user_agent = opts.get('user_agent', None)
if user_agent:
agent = user_agent
agent = '{0} http.query()'.format(agent)
header_dict['User-agent'] = agent
if backend == 'requests':
sess = requests.Session()
sess.auth = auth
sess.headers.update(header_dict)
log.trace('Request Headers: %s', sess.headers)
sess_cookies = sess.cookies
sess.verify = verify_ssl
elif backend == 'urllib2':
sess_cookies = None
else:
# Tornado
sess_cookies = None
if cookies is not None:
if cookie_format == 'mozilla':
sess_cookies = salt.ext.six.moves.http_cookiejar.MozillaCookieJar(cookie_jar)
else:
sess_cookies = salt.ext.six.moves.http_cookiejar.LWPCookieJar(cookie_jar)
if not os.path.isfile(cookie_jar):
sess_cookies.save()
sess_cookies.load()
if test is True:
if test_url is None:
return {}
else:
url = test_url
ret['test'] = True
if backend == 'requests':
req_kwargs = {}
if stream is True:
if requests.__version__[0] == '0':
# 'stream' was called 'prefetch' before 1.0, with flipped meaning
req_kwargs['prefetch'] = False
else:
req_kwargs['stream'] = True
# Client-side cert handling
if cert is not None:
if isinstance(cert, six.string_types):
if os.path.exists(cert):
req_kwargs['cert'] = cert
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
req_kwargs['cert'] = cert
else:
log.error('The client-side certificate path that'
' was passed is not valid: %s', cert)
result = sess.request(
method, url, params=params, data=data, **req_kwargs
)
result.raise_for_status()
if stream is True:
# fake a HTTP response header
header_callback('HTTP/1.0 {0} MESSAGE'.format(result.status_code))
# fake streaming the content
streaming_callback(result.content)
return {
'handle': result,
}
if handle is True:
return {
'handle': result,
'body': result.content,
}
log.debug('Final URL location of Response: %s',
sanitize_url(result.url, hide_fields))
result_status_code = result.status_code
result_headers = result.headers
result_text = result.content
result_cookies = result.cookies
body = result.content
if not isinstance(body, six.text_type):
body = body.decode(result.encoding or 'utf-8')
ret['body'] = body
elif backend == 'urllib2':
request = urllib_request.Request(url_full, data)
handlers = [
urllib_request.HTTPHandler,
urllib_request.HTTPCookieProcessor(sess_cookies)
]
if url.startswith('https'):
hostname = request.get_host()
handlers[0] = urllib_request.HTTPSHandler(1)
if not HAS_MATCHHOSTNAME:
log.warning('match_hostname() not available, SSL hostname checking '
'not available. THIS CONNECTION MAY NOT BE SECURE!')
elif verify_ssl is False:
log.warning('SSL certificate verification has been explicitly '
'disabled. THIS CONNECTION MAY NOT BE SECURE!')
else:
if ':' in hostname:
hostname, port = hostname.split(':')
else:
port = 443
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, int(port)))
sockwrap = ssl.wrap_socket(
sock,
ca_certs=ca_bundle,
cert_reqs=ssl.CERT_REQUIRED
)
try:
match_hostname(sockwrap.getpeercert(), hostname)
except CertificateError as exc:
ret['error'] = (
'The certificate was invalid. '
'Error returned was: %s',
pprint.pformat(exc)
)
return ret
# Client-side cert handling
if cert is not None:
cert_chain = None
if isinstance(cert, six.string_types):
if os.path.exists(cert):
cert_chain = (cert)
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
cert_chain = cert
else:
log.error('The client-side certificate path that was '
'passed is not valid: %s', cert)
return
if hasattr(ssl, 'SSLContext'):
# Python >= 2.7.9
context = ssl.SSLContext.load_cert_chain(*cert_chain)
handlers.append(urllib_request.HTTPSHandler(context=context)) # pylint: disable=E1123
else:
# Python < 2.7.9
cert_kwargs = {
'host': request.get_host(),
'port': port,
'cert_file': cert_chain[0]
}
if len(cert_chain) > 1:
cert_kwargs['key_file'] = cert_chain[1]
handlers[0] = salt.ext.six.moves.http_client.HTTPSConnection(**cert_kwargs)
opener = urllib_request.build_opener(*handlers)
for header in header_dict:
request.add_header(header, header_dict[header])
request.get_method = lambda: method
try:
result = opener.open(request)
except URLError as exc:
return {'Error': six.text_type(exc)}
if stream is True or handle is True:
return {
'handle': result,
'body': result.content,
}
result_status_code = result.code
result_headers = dict(result.info())
result_text = result.read()
if 'Content-Type' in result_headers:
res_content_type, res_params = cgi.parse_header(result_headers['Content-Type'])
if res_content_type.startswith('text/') and \
'charset' in res_params and \
not isinstance(result_text, six.text_type):
result_text = result_text.decode(res_params['charset'])
if six.PY3 and isinstance(result_text, bytes):
result_text = result.body.decode('utf-8')
ret['body'] = result_text
else:
# Tornado
req_kwargs = {}
# Client-side cert handling
if cert is not None:
if isinstance(cert, six.string_types):
if os.path.exists(cert):
req_kwargs['client_cert'] = cert
elif isinstance(cert, list):
if os.path.exists(cert[0]) and os.path.exists(cert[1]):
req_kwargs['client_cert'] = cert[0]
req_kwargs['client_key'] = cert[1]
else:
log.error('The client-side certificate path that '
'was passed is not valid: %s', cert)
if isinstance(data, dict):
data = _urlencode(data)
if verify_ssl:
req_kwargs['ca_certs'] = ca_bundle
max_body = opts.get('http_max_body', salt.config.DEFAULT_MINION_OPTS['http_max_body'])
connect_timeout = opts.get('http_connect_timeout', salt.config.DEFAULT_MINION_OPTS['http_connect_timeout'])
timeout = opts.get('http_request_timeout', salt.config.DEFAULT_MINION_OPTS['http_request_timeout'])
client_argspec = None
proxy_host = opts.get('proxy_host', None)
if proxy_host:
# tornado requires a str for proxy_host, cannot be a unicode str in py2
proxy_host = salt.utils.stringutils.to_str(proxy_host)
proxy_port = opts.get('proxy_port', None)
proxy_username = opts.get('proxy_username', None)
if proxy_username:
# tornado requires a str, cannot be unicode str in py2
proxy_username = salt.utils.stringutils.to_str(proxy_username)
proxy_password = opts.get('proxy_password', None)
if proxy_password:
# tornado requires a str, cannot be unicode str in py2
proxy_password = salt.utils.stringutils.to_str(proxy_password)
no_proxy = opts.get('no_proxy', [])
# Since tornado doesnt support no_proxy, we'll always hand it empty proxies or valid ones
# except we remove the valid ones if a url has a no_proxy hostname in it
if urlparse(url_full).hostname in no_proxy:
proxy_host = None
proxy_port = None
# We want to use curl_http if we have a proxy defined
if proxy_host and proxy_port:
if HAS_CURL_HTTPCLIENT is False:
ret['error'] = ('proxy_host and proxy_port has been set. This requires pycurl and tornado, '
'but the libraries does not seem to be installed')
log.error(ret['error'])
return ret
tornado.httpclient.AsyncHTTPClient.configure('tornado.curl_httpclient.CurlAsyncHTTPClient')
client_argspec = salt.utils.args.get_function_argspec(
tornado.curl_httpclient.CurlAsyncHTTPClient.initialize)
else:
client_argspec = salt.utils.args.get_function_argspec(
tornado.simple_httpclient.SimpleAsyncHTTPClient.initialize)
supports_max_body_size = 'max_body_size' in client_argspec.args
req_kwargs.update({
'method': method,
'headers': header_dict,
'auth_username': username,
'auth_password': password,
'body': data,
'validate_cert': verify_ssl,
'allow_nonstandard_methods': True,
'streaming_callback': streaming_callback,
'header_callback': header_callback,
'connect_timeout': connect_timeout,
'request_timeout': timeout,
'proxy_host': proxy_host,
'proxy_port': proxy_port,
'proxy_username': proxy_username,
'proxy_password': proxy_password,
'raise_error': raise_error,
'decompress_response': False,
})
# Unicode types will cause a TypeError when Tornado's curl HTTPClient
# invokes setopt. Therefore, make sure all arguments we pass which
# contain strings are str types.
req_kwargs = salt.utils.data.decode(req_kwargs, to_str=True)
try:
download_client = HTTPClient(max_body_size=max_body) \
if supports_max_body_size \
else HTTPClient()
result = download_client.fetch(url_full, **req_kwargs)
except tornado.httpclient.HTTPError as exc:
ret['status'] = exc.code
ret['error'] = six.text_type(exc)
return ret
except socket.gaierror as exc:
if status is True:
ret['status'] = 0
ret['error'] = six.text_type(exc)
return ret
if stream is True or handle is True:
return {
'handle': result,
'body': result.body,
}
result_status_code = result.code
result_headers = result.headers
result_text = result.body
if 'Content-Type' in result_headers:
res_content_type, res_params = cgi.parse_header(result_headers['Content-Type'])
if res_content_type.startswith('text/') and \
'charset' in res_params and \
not isinstance(result_text, six.text_type):
result_text = result_text.decode(res_params['charset'])
if six.PY3 and isinstance(result_text, bytes):
result_text = result_text.decode('utf-8')
ret['body'] = result_text
if 'Set-Cookie' in result_headers and cookies is not None:
result_cookies = parse_cookie_header(result_headers['Set-Cookie'])
for item in result_cookies:
sess_cookies.set_cookie(item)
else:
result_cookies = None
if isinstance(result_headers, list):
result_headers_dict = {}
for header in result_headers:
comps = header.split(':')
result_headers_dict[comps[0].strip()] = ':'.join(comps[1:]).strip()
result_headers = result_headers_dict
log.debug('Response Status Code: %s', result_status_code)
log.trace('Response Headers: %s', result_headers)
log.trace('Response Cookies: %s', sess_cookies)
# log.trace("Content: %s", result_text)
coding = result_headers.get('Content-Encoding', "identity")
# Requests will always decompress the content, and working around that is annoying.
if backend != 'requests':
result_text = __decompressContent(coding, result_text)
try:
log.trace('Response Text: %s', result_text)
except UnicodeEncodeError as exc:
log.trace('Cannot Trace Log Response Text: %s. This may be due to '
'incompatibilities between requests and logging.', exc)
if text_out is not None:
with salt.utils.files.fopen(text_out, 'w') as tof:
tof.write(result_text)
if headers_out is not None and os.path.exists(headers_out):
with salt.utils.files.fopen(headers_out, 'w') as hof:
hof.write(result_headers)
if cookies is not None:
sess_cookies.save()
if persist_session is True and HAS_MSGPACK:
# TODO: See persist_session above
if 'set-cookie' in result_headers:
with salt.utils.files.fopen(session_cookie_jar, 'wb') as fh_:
session_cookies = result_headers.get('set-cookie', None)
if session_cookies is not None:
salt.utils.msgpack.dump({'Cookie': session_cookies}, fh_)
else:
salt.utils.msgpack.dump('', fh_)
if status is True:
ret['status'] = result_status_code
if headers is True:
ret['headers'] = result_headers
if decode is True:
if decode_type == 'auto':
content_type = result_headers.get(
'content-type', 'application/json'
)
if 'xml' in content_type:
decode_type = 'xml'
elif 'json' in content_type:
decode_type = 'json'
elif 'yaml' in content_type:
decode_type = 'yaml'
else:
decode_type = 'plain'
valid_decodes = ('json', 'xml', 'yaml', 'plain')
if decode_type not in valid_decodes:
ret['error'] = (
'Invalid decode_type specified. '
'Valid decode types are: {0}'.format(
pprint.pformat(valid_decodes)
)
)
log.error(ret['error'])
return ret
if decode_type == 'json':
ret['dict'] = salt.utils.json.loads(result_text)
elif decode_type == 'xml':
ret['dict'] = []
items = ET.fromstring(result_text)
for item in items:
ret['dict'].append(xml.to_dict(item))
elif decode_type == 'yaml':
ret['dict'] = salt.utils.data.decode(salt.utils.yaml.safe_load(result_text))
else:
text = True
if decode_out:
with salt.utils.files.fopen(decode_out, 'w') as dof:
dof.write(result_text)
if text is True:
ret['text'] = result_text
return ret | [
"def",
"query",
"(",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_file",
"=",
"None",
",",
"header_dict",
"=",
"None",
",",
"header_list",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"use... | Query a resource, and decode the return data | [
"Query",
"a",
"resource",
"and",
"decode",
"the",
"return",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L133-L700 | train |
saltstack/salt | salt/utils/http.py | get_ca_bundle | def get_ca_bundle(opts=None):
'''
Return the location of the ca bundle file. See the following article:
http://tinyurl.com/k7rx42a
'''
if hasattr(get_ca_bundle, '__return_value__'):
return get_ca_bundle.__return_value__
if opts is None:
opts = {}
opts_bundle = opts.get('ca_bundle', None)
if opts_bundle is not None and os.path.exists(opts_bundle):
return opts_bundle
file_roots = opts.get('file_roots', {'base': [salt.syspaths.SRV_ROOT_DIR]})
# Please do not change the order without good reason
# Check Salt first
for salt_root in file_roots.get('base', []):
for path in ('cacert.pem', 'ca-bundle.crt'):
cert_path = os.path.join(salt_root, path)
if os.path.exists(cert_path):
return cert_path
locations = (
# Debian has paths that often exist on other distros
'/etc/ssl/certs/ca-certificates.crt',
# RedHat is also very common
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/pki/tls/certs/ca-bundle.trust.crt',
# RedHat's link for Debian compatibility
'/etc/ssl/certs/ca-bundle.crt',
# SUSE has an unusual path
'/var/lib/ca-certificates/ca-bundle.pem',
# OpenBSD has an unusual path
'/etc/ssl/cert.pem',
)
for path in locations:
if os.path.exists(path):
return path
if salt.utils.platform.is_windows() and HAS_CERTIFI:
return certifi.where()
return None | python | def get_ca_bundle(opts=None):
'''
Return the location of the ca bundle file. See the following article:
http://tinyurl.com/k7rx42a
'''
if hasattr(get_ca_bundle, '__return_value__'):
return get_ca_bundle.__return_value__
if opts is None:
opts = {}
opts_bundle = opts.get('ca_bundle', None)
if opts_bundle is not None and os.path.exists(opts_bundle):
return opts_bundle
file_roots = opts.get('file_roots', {'base': [salt.syspaths.SRV_ROOT_DIR]})
# Please do not change the order without good reason
# Check Salt first
for salt_root in file_roots.get('base', []):
for path in ('cacert.pem', 'ca-bundle.crt'):
cert_path = os.path.join(salt_root, path)
if os.path.exists(cert_path):
return cert_path
locations = (
# Debian has paths that often exist on other distros
'/etc/ssl/certs/ca-certificates.crt',
# RedHat is also very common
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/pki/tls/certs/ca-bundle.trust.crt',
# RedHat's link for Debian compatibility
'/etc/ssl/certs/ca-bundle.crt',
# SUSE has an unusual path
'/var/lib/ca-certificates/ca-bundle.pem',
# OpenBSD has an unusual path
'/etc/ssl/cert.pem',
)
for path in locations:
if os.path.exists(path):
return path
if salt.utils.platform.is_windows() and HAS_CERTIFI:
return certifi.where()
return None | [
"def",
"get_ca_bundle",
"(",
"opts",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"get_ca_bundle",
",",
"'__return_value__'",
")",
":",
"return",
"get_ca_bundle",
".",
"__return_value__",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"opts_bundle",... | Return the location of the ca bundle file. See the following article:
http://tinyurl.com/k7rx42a | [
"Return",
"the",
"location",
"of",
"the",
"ca",
"bundle",
"file",
".",
"See",
"the",
"following",
"article",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L703-L750 | train |
saltstack/salt | salt/utils/http.py | update_ca_bundle | def update_ca_bundle(
target=None,
source=None,
opts=None,
merge_files=None,
):
'''
Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new location on disk
will be created and updated.
The default ``source`` is:
http://curl.haxx.se/ca/cacert.pem
This is based on the information at:
http://curl.haxx.se/docs/caextract.html
A string or list of strings representing files to be appended to the end of
the CA bundle file may also be passed through as ``merge_files``.
'''
if opts is None:
opts = {}
if target is None:
target = get_ca_bundle(opts)
if target is None:
log.error('Unable to detect location to write CA bundle to')
return
if source is None:
source = opts.get('ca_bundle_url', 'http://curl.haxx.se/ca/cacert.pem')
log.debug('Attempting to download %s to %s', source, target)
query(
source,
text=True,
decode=False,
headers=False,
status=False,
text_out=target
)
if merge_files is not None:
if isinstance(merge_files, six.string_types):
merge_files = [merge_files]
if not isinstance(merge_files, list):
log.error('A value was passed as merge_files which was not either '
'a string or a list')
return
merge_content = ''
for cert_file in merge_files:
if os.path.exists(cert_file):
log.debug(
'Queueing up %s to be appended to %s',
cert_file, target
)
try:
with salt.utils.files.fopen(cert_file, 'r') as fcf:
merge_content = '\n'.join((merge_content, fcf.read()))
except IOError as exc:
log.error(
'Reading from %s caused the following error: %s',
cert_file, exc
)
if merge_content:
log.debug('Appending merge_files to %s', target)
try:
with salt.utils.files.fopen(target, 'a') as tfp:
tfp.write('\n')
tfp.write(merge_content)
except IOError as exc:
log.error(
'Writing to %s caused the following error: %s',
target, exc
) | python | def update_ca_bundle(
target=None,
source=None,
opts=None,
merge_files=None,
):
'''
Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new location on disk
will be created and updated.
The default ``source`` is:
http://curl.haxx.se/ca/cacert.pem
This is based on the information at:
http://curl.haxx.se/docs/caextract.html
A string or list of strings representing files to be appended to the end of
the CA bundle file may also be passed through as ``merge_files``.
'''
if opts is None:
opts = {}
if target is None:
target = get_ca_bundle(opts)
if target is None:
log.error('Unable to detect location to write CA bundle to')
return
if source is None:
source = opts.get('ca_bundle_url', 'http://curl.haxx.se/ca/cacert.pem')
log.debug('Attempting to download %s to %s', source, target)
query(
source,
text=True,
decode=False,
headers=False,
status=False,
text_out=target
)
if merge_files is not None:
if isinstance(merge_files, six.string_types):
merge_files = [merge_files]
if not isinstance(merge_files, list):
log.error('A value was passed as merge_files which was not either '
'a string or a list')
return
merge_content = ''
for cert_file in merge_files:
if os.path.exists(cert_file):
log.debug(
'Queueing up %s to be appended to %s',
cert_file, target
)
try:
with salt.utils.files.fopen(cert_file, 'r') as fcf:
merge_content = '\n'.join((merge_content, fcf.read()))
except IOError as exc:
log.error(
'Reading from %s caused the following error: %s',
cert_file, exc
)
if merge_content:
log.debug('Appending merge_files to %s', target)
try:
with salt.utils.files.fopen(target, 'a') as tfp:
tfp.write('\n')
tfp.write(merge_content)
except IOError as exc:
log.error(
'Writing to %s caused the following error: %s',
target, exc
) | [
"def",
"update_ca_bundle",
"(",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"merge_files",
"=",
"None",
",",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"if",
"target",
"is",
"None",
":",
... | Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new location on disk
will be created and updated.
The default ``source`` is:
http://curl.haxx.se/ca/cacert.pem
This is based on the information at:
http://curl.haxx.se/docs/caextract.html
A string or list of strings representing files to be appended to the end of
the CA bundle file may also be passed through as ``merge_files``. | [
"Attempt",
"to",
"update",
"the",
"CA",
"bundle",
"file",
"from",
"a",
"URL"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L753-L836 | train |
saltstack/salt | salt/utils/http.py | _render | def _render(template, render, renderer, template_dict, opts):
'''
Render a template
'''
if render:
if template_dict is None:
template_dict = {}
if not renderer:
renderer = opts.get('renderer', 'jinja|yaml')
rend = salt.loader.render(opts, {})
blacklist = opts.get('renderer_blacklist')
whitelist = opts.get('renderer_whitelist')
ret = compile_template(template, rend, renderer, blacklist, whitelist, **template_dict)
if salt.utils.stringio.is_readable(ret):
ret = ret.read()
if six.text_type(ret).startswith('#!') and not six.text_type(ret).startswith('#!/'):
ret = six.text_type(ret).split('\n', 1)[1]
return ret
with salt.utils.files.fopen(template, 'r') as fh_:
return fh_.read() | python | def _render(template, render, renderer, template_dict, opts):
'''
Render a template
'''
if render:
if template_dict is None:
template_dict = {}
if not renderer:
renderer = opts.get('renderer', 'jinja|yaml')
rend = salt.loader.render(opts, {})
blacklist = opts.get('renderer_blacklist')
whitelist = opts.get('renderer_whitelist')
ret = compile_template(template, rend, renderer, blacklist, whitelist, **template_dict)
if salt.utils.stringio.is_readable(ret):
ret = ret.read()
if six.text_type(ret).startswith('#!') and not six.text_type(ret).startswith('#!/'):
ret = six.text_type(ret).split('\n', 1)[1]
return ret
with salt.utils.files.fopen(template, 'r') as fh_:
return fh_.read() | [
"def",
"_render",
"(",
"template",
",",
"render",
",",
"renderer",
",",
"template_dict",
",",
"opts",
")",
":",
"if",
"render",
":",
"if",
"template_dict",
"is",
"None",
":",
"template_dict",
"=",
"{",
"}",
"if",
"not",
"renderer",
":",
"renderer",
"=",
... | Render a template | [
"Render",
"a",
"template"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L839-L858 | train |
saltstack/salt | salt/utils/http.py | parse_cookie_header | def parse_cookie_header(header):
'''
Parse the "Set-cookie" header, and return a list of cookies.
This function is here because Tornado's HTTPClient doesn't handle cookies.
'''
attribs = ('expires', 'path', 'domain', 'version', 'httponly', 'secure', 'comment', 'max-age')
# Split into cookie(s); handles headers with multiple cookies defined
morsels = []
for item in header.split(';'):
item = item.strip()
if ',' in item and 'expires' not in item:
for part in item.split(','):
morsels.append(part)
else:
morsels.append(item)
# Break down morsels into actual cookies
cookies = []
cookie = {}
value_set = False
for morsel in morsels:
parts = morsel.split('=')
if parts[0].lower() in attribs:
if parts[0] in cookie:
cookies.append(cookie)
cookie = {}
if len(parts) > 1:
cookie[parts[0]] = '='.join(parts[1:])
else:
cookie[parts[0]] = True
else:
if value_set is True:
# This is a new cookie; save the old one and clear for this one
cookies.append(cookie)
cookie = {}
value_set = False
cookie[parts[0]] = '='.join(parts[1:])
value_set = True
if cookie:
# Set the last cookie that was processed
cookies.append(cookie)
# These arguments are required by cookielib.Cookie()
reqd = (
'version',
'port',
'port_specified',
'domain',
'domain_specified',
'domain_initial_dot',
'path',
'path_specified',
'secure',
'expires',
'discard',
'comment',
'comment_url',
'rest',
)
ret = []
for cookie in cookies:
name = None
value = None
for item in list(cookie):
if item in attribs:
continue
name = item
value = cookie.pop(item)
# cookielib.Cookie() requires an epoch
if 'expires' in cookie:
cookie['expires'] = salt.ext.six.moves.http_cookiejar.http2time(cookie['expires'])
# Fill in missing required fields
for req in reqd:
if req not in cookie:
cookie[req] = ''
if cookie['version'] == '':
cookie['version'] = 0
if cookie['rest'] == '':
cookie['rest'] = {}
if cookie['expires'] == '':
cookie['expires'] = 0
if 'httponly' in cookie:
del cookie['httponly']
ret.append(salt.ext.six.moves.http_cookiejar.Cookie(name=name, value=value, **cookie))
return ret | python | def parse_cookie_header(header):
'''
Parse the "Set-cookie" header, and return a list of cookies.
This function is here because Tornado's HTTPClient doesn't handle cookies.
'''
attribs = ('expires', 'path', 'domain', 'version', 'httponly', 'secure', 'comment', 'max-age')
# Split into cookie(s); handles headers with multiple cookies defined
morsels = []
for item in header.split(';'):
item = item.strip()
if ',' in item and 'expires' not in item:
for part in item.split(','):
morsels.append(part)
else:
morsels.append(item)
# Break down morsels into actual cookies
cookies = []
cookie = {}
value_set = False
for morsel in morsels:
parts = morsel.split('=')
if parts[0].lower() in attribs:
if parts[0] in cookie:
cookies.append(cookie)
cookie = {}
if len(parts) > 1:
cookie[parts[0]] = '='.join(parts[1:])
else:
cookie[parts[0]] = True
else:
if value_set is True:
# This is a new cookie; save the old one and clear for this one
cookies.append(cookie)
cookie = {}
value_set = False
cookie[parts[0]] = '='.join(parts[1:])
value_set = True
if cookie:
# Set the last cookie that was processed
cookies.append(cookie)
# These arguments are required by cookielib.Cookie()
reqd = (
'version',
'port',
'port_specified',
'domain',
'domain_specified',
'domain_initial_dot',
'path',
'path_specified',
'secure',
'expires',
'discard',
'comment',
'comment_url',
'rest',
)
ret = []
for cookie in cookies:
name = None
value = None
for item in list(cookie):
if item in attribs:
continue
name = item
value = cookie.pop(item)
# cookielib.Cookie() requires an epoch
if 'expires' in cookie:
cookie['expires'] = salt.ext.six.moves.http_cookiejar.http2time(cookie['expires'])
# Fill in missing required fields
for req in reqd:
if req not in cookie:
cookie[req] = ''
if cookie['version'] == '':
cookie['version'] = 0
if cookie['rest'] == '':
cookie['rest'] = {}
if cookie['expires'] == '':
cookie['expires'] = 0
if 'httponly' in cookie:
del cookie['httponly']
ret.append(salt.ext.six.moves.http_cookiejar.Cookie(name=name, value=value, **cookie))
return ret | [
"def",
"parse_cookie_header",
"(",
"header",
")",
":",
"attribs",
"=",
"(",
"'expires'",
",",
"'path'",
",",
"'domain'",
",",
"'version'",
",",
"'httponly'",
",",
"'secure'",
",",
"'comment'",
",",
"'max-age'",
")",
"# Split into cookie(s); handles headers with mult... | Parse the "Set-cookie" header, and return a list of cookies.
This function is here because Tornado's HTTPClient doesn't handle cookies. | [
"Parse",
"the",
"Set",
"-",
"cookie",
"header",
"and",
"return",
"a",
"list",
"of",
"cookies",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L861-L953 | train |
saltstack/salt | salt/utils/http.py | sanitize_url | def sanitize_url(url, hide_fields):
'''
Make sure no secret fields show up in logs
'''
if isinstance(hide_fields, list):
url_comps = splitquery(url)
log_url = url_comps[0]
if len(url_comps) > 1:
log_url += '?'
for pair in url_comps[1:]:
url_tmp = None
for field in hide_fields:
comps_list = pair.split('&')
if url_tmp:
url_tmp = url_tmp.split('&')
url_tmp = _sanitize_url_components(url_tmp, field)
else:
url_tmp = _sanitize_url_components(comps_list, field)
log_url += url_tmp
return log_url.rstrip('&')
else:
return six.text_type(url) | python | def sanitize_url(url, hide_fields):
'''
Make sure no secret fields show up in logs
'''
if isinstance(hide_fields, list):
url_comps = splitquery(url)
log_url = url_comps[0]
if len(url_comps) > 1:
log_url += '?'
for pair in url_comps[1:]:
url_tmp = None
for field in hide_fields:
comps_list = pair.split('&')
if url_tmp:
url_tmp = url_tmp.split('&')
url_tmp = _sanitize_url_components(url_tmp, field)
else:
url_tmp = _sanitize_url_components(comps_list, field)
log_url += url_tmp
return log_url.rstrip('&')
else:
return six.text_type(url) | [
"def",
"sanitize_url",
"(",
"url",
",",
"hide_fields",
")",
":",
"if",
"isinstance",
"(",
"hide_fields",
",",
"list",
")",
":",
"url_comps",
"=",
"splitquery",
"(",
"url",
")",
"log_url",
"=",
"url_comps",
"[",
"0",
"]",
"if",
"len",
"(",
"url_comps",
... | Make sure no secret fields show up in logs | [
"Make",
"sure",
"no",
"secret",
"fields",
"show",
"up",
"in",
"logs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L956-L977 | train |
saltstack/salt | salt/utils/http.py | _sanitize_url_components | def _sanitize_url_components(comp_list, field):
'''
Recursive function to sanitize each component of the url.
'''
if not comp_list:
return ''
elif comp_list[0].startswith('{0}='.format(field)):
ret = '{0}=XXXXXXXXXX&'.format(field)
comp_list.remove(comp_list[0])
return ret + _sanitize_url_components(comp_list, field)
else:
ret = '{0}&'.format(comp_list[0])
comp_list.remove(comp_list[0])
return ret + _sanitize_url_components(comp_list, field) | python | def _sanitize_url_components(comp_list, field):
'''
Recursive function to sanitize each component of the url.
'''
if not comp_list:
return ''
elif comp_list[0].startswith('{0}='.format(field)):
ret = '{0}=XXXXXXXXXX&'.format(field)
comp_list.remove(comp_list[0])
return ret + _sanitize_url_components(comp_list, field)
else:
ret = '{0}&'.format(comp_list[0])
comp_list.remove(comp_list[0])
return ret + _sanitize_url_components(comp_list, field) | [
"def",
"_sanitize_url_components",
"(",
"comp_list",
",",
"field",
")",
":",
"if",
"not",
"comp_list",
":",
"return",
"''",
"elif",
"comp_list",
"[",
"0",
"]",
".",
"startswith",
"(",
"'{0}='",
".",
"format",
"(",
"field",
")",
")",
":",
"ret",
"=",
"'... | Recursive function to sanitize each component of the url. | [
"Recursive",
"function",
"to",
"sanitize",
"each",
"component",
"of",
"the",
"url",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/http.py#L980-L993 | train |
saltstack/salt | salt/modules/namecheap_domains_ns.py | get_info | def get_info(sld, tld, nameserver):
'''
Retrieves information about a registered nameserver. Returns the following
information:
- IP Address set for the nameserver
- Domain name which was queried
- A list of nameservers and their statuses
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to retrieve
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.get_info sld tld nameserver
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.delete')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
domainnsinforesult = response_xml.getElementsByTagName('DomainNSInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(domainnsinforesult) | python | def get_info(sld, tld, nameserver):
'''
Retrieves information about a registered nameserver. Returns the following
information:
- IP Address set for the nameserver
- Domain name which was queried
- A list of nameservers and their statuses
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to retrieve
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.get_info sld tld nameserver
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.delete')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
domainnsinforesult = response_xml.getElementsByTagName('DomainNSInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(domainnsinforesult) | [
"def",
"get_info",
"(",
"sld",
",",
"tld",
",",
"nameserver",
")",
":",
"opts",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_opts",
"(",
"'namecheap.domains.ns.delete'",
")",
"opts",
"[",
"'SLD'",
"]",
"=",
"sld",
"opts",
"[",
"'TLD'",
"]",
"... | Retrieves information about a registered nameserver. Returns the following
information:
- IP Address set for the nameserver
- Domain name which was queried
- A list of nameservers and their statuses
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to retrieve
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.get_info sld tld nameserver | [
"Retrieves",
"information",
"about",
"a",
"registered",
"nameserver",
".",
"Returns",
"the",
"following",
"information",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_ns.py#L52-L87 | train |
saltstack/salt | salt/modules/namecheap_domains_ns.py | update | def update(sld, tld, nameserver, old_ip, new_ip):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was updated
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
old_ip
Current ip address
new_ip
New ip address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.update sld tld nameserver old_ip new_ip
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.update')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
opts['OldIP'] = old_ip
opts['IP'] = new_ip
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnsupdateresult = response_xml.getElementsByTagName('DomainNSUpdateResult')[0]
return salt.utils.namecheap.string_to_value(domainnsupdateresult.getAttribute('IsSuccess')) | python | def update(sld, tld, nameserver, old_ip, new_ip):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was updated
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
old_ip
Current ip address
new_ip
New ip address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.update sld tld nameserver old_ip new_ip
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.update')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
opts['OldIP'] = old_ip
opts['IP'] = new_ip
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnsupdateresult = response_xml.getElementsByTagName('DomainNSUpdateResult')[0]
return salt.utils.namecheap.string_to_value(domainnsupdateresult.getAttribute('IsSuccess')) | [
"def",
"update",
"(",
"sld",
",",
"tld",
",",
"nameserver",
",",
"old_ip",
",",
"new_ip",
")",
":",
"opts",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_opts",
"(",
"'namecheap.domains.ns.update'",
")",
"opts",
"[",
"'SLD'",
"]",
"=",
"sld",
... | Deletes a nameserver. Returns ``True`` if the nameserver was updated
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
old_ip
Current ip address
new_ip
New ip address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.update sld tld nameserver old_ip new_ip | [
"Deletes",
"a",
"nameserver",
".",
"Returns",
"True",
"if",
"the",
"nameserver",
"was",
"updated",
"successfully",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_ns.py#L90-L128 | train |
saltstack/salt | salt/modules/namecheap_domains_ns.py | delete | def delete(sld, tld, nameserver):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.delete sld tld nameserver
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.delete')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnsdeleteresult = response_xml.getElementsByTagName('DomainNSDeleteResult')[0]
return salt.utils.namecheap.string_to_value(domainnsdeleteresult.getAttribute('IsSuccess')) | python | def delete(sld, tld, nameserver):
'''
Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.delete sld tld nameserver
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.delete')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnsdeleteresult = response_xml.getElementsByTagName('DomainNSDeleteResult')[0]
return salt.utils.namecheap.string_to_value(domainnsdeleteresult.getAttribute('IsSuccess')) | [
"def",
"delete",
"(",
"sld",
",",
"tld",
",",
"nameserver",
")",
":",
"opts",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_opts",
"(",
"'namecheap.domains.ns.delete'",
")",
"opts",
"[",
"'SLD'",
"]",
"=",
"sld",
"opts",
"[",
"'TLD'",
"]",
"="... | Deletes a nameserver. Returns ``True`` if the nameserver was deleted
successfully
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to delete
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.delete sld tld nameserver | [
"Deletes",
"a",
"nameserver",
".",
"Returns",
"True",
"if",
"the",
"nameserver",
"was",
"deleted",
"successfully"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_ns.py#L131-L161 | train |
saltstack/salt | salt/modules/namecheap_domains_ns.py | create | def create(sld, tld, nameserver, ip):
'''
Creates a new nameserver. Returns ``True`` if the nameserver was created
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
ip
Nameserver IP address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.create sld tld nameserver ip
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.create')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
opts['IP'] = ip
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnscreateresult = response_xml.getElementsByTagName('DomainNSCreateResult')[0]
return salt.utils.namecheap.string_to_value(domainnscreateresult.getAttribute('IsSuccess')) | python | def create(sld, tld, nameserver, ip):
'''
Creates a new nameserver. Returns ``True`` if the nameserver was created
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
ip
Nameserver IP address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.create sld tld nameserver ip
'''
opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.create')
opts['SLD'] = sld
opts['TLD'] = tld
opts['Nameserver'] = nameserver
opts['IP'] = ip
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return False
domainnscreateresult = response_xml.getElementsByTagName('DomainNSCreateResult')[0]
return salt.utils.namecheap.string_to_value(domainnscreateresult.getAttribute('IsSuccess')) | [
"def",
"create",
"(",
"sld",
",",
"tld",
",",
"nameserver",
",",
"ip",
")",
":",
"opts",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_opts",
"(",
"'namecheap.domains.ns.create'",
")",
"opts",
"[",
"'SLD'",
"]",
"=",
"sld",
"opts",
"[",
"'TLD'... | Creates a new nameserver. Returns ``True`` if the nameserver was created
successfully.
sld
SLD of the domain name
tld
TLD of the domain name
nameserver
Nameserver to create
ip
Nameserver IP address
CLI Example:
.. code-block:: bash
salt '*' namecheap_domains_ns.create sld tld nameserver ip | [
"Creates",
"a",
"new",
"nameserver",
".",
"Returns",
"True",
"if",
"the",
"nameserver",
"was",
"created",
"successfully",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_ns.py#L164-L199 | train |
saltstack/salt | salt/modules/dnsmasq.py | version | def version():
'''
Shows installed version of dnsmasq.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.version
'''
cmd = 'dnsmasq -v'
out = __salt__['cmd.run'](cmd).splitlines()
comps = out[0].split()
return comps[2] | python | def version():
'''
Shows installed version of dnsmasq.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.version
'''
cmd = 'dnsmasq -v'
out = __salt__['cmd.run'](cmd).splitlines()
comps = out[0].split()
return comps[2] | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"'dnsmasq -v'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"comps",
"=",
"out",
"[",
"0",
"]",
".",
"split",
"(",
")",
"return",
"comps",
"[",
"2",
"]"... | Shows installed version of dnsmasq.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.version | [
"Shows",
"installed",
"version",
"of",
"dnsmasq",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L35-L48 | train |
saltstack/salt | salt/modules/dnsmasq.py | fullversion | def fullversion():
'''
Shows installed version of dnsmasq and compile options.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.fullversion
'''
cmd = 'dnsmasq -v'
out = __salt__['cmd.run'](cmd).splitlines()
comps = out[0].split()
version_num = comps[2]
comps = out[1].split()
return {'version': version_num,
'compile options': comps[3:]} | python | def fullversion():
'''
Shows installed version of dnsmasq and compile options.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.fullversion
'''
cmd = 'dnsmasq -v'
out = __salt__['cmd.run'](cmd).splitlines()
comps = out[0].split()
version_num = comps[2]
comps = out[1].split()
return {'version': version_num,
'compile options': comps[3:]} | [
"def",
"fullversion",
"(",
")",
":",
"cmd",
"=",
"'dnsmasq -v'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"comps",
"=",
"out",
"[",
"0",
"]",
".",
"split",
"(",
")",
"version_num",
"=",
"comps",
"... | Shows installed version of dnsmasq and compile options.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.fullversion | [
"Shows",
"installed",
"version",
"of",
"dnsmasq",
"and",
"compile",
"options",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L51-L67 | train |
saltstack/salt | salt/modules/dnsmasq.py | set_config | def set_config(config_file='/etc/dnsmasq.conf', follow=True, **kwargs):
'''
Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not find it inside any files, it will append it to the main config
file. Setting follow to False will turn off this behavior.
If a config option currently appears multiple times (such as dhcp-host,
which is specified at least once per host), the new option will be added
to the end of the main config file (and not to any includes). If you need
an option added to a specific include file, specify it as the config_file.
:param string config_file: config file where settings should be updated / added.
:param bool follow: attempt to set the config option inside any file within
the ``conf-dir`` where it has already been enabled.
:param kwargs: key value pairs that contain the configuration settings that you
want set.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.set_config domain=mydomain.com
salt '*' dnsmasq.set_config follow=False domain=mydomain.com
salt '*' dnsmasq.set_config config_file=/etc/dnsmasq.conf domain=mydomain.com
'''
dnsopts = get_config(config_file)
includes = [config_file]
if follow is True and 'conf-dir' in dnsopts:
for filename in os.listdir(dnsopts['conf-dir']):
if filename.startswith('.'):
continue
if filename.endswith('~'):
continue
if filename.endswith('bak'):
continue
if filename.endswith('#') and filename.endswith('#'):
continue
includes.append('{0}/{1}'.format(dnsopts['conf-dir'], filename))
ret_kwargs = {}
for key in kwargs:
# Filter out __pub keys as they should not be added to the config file
# See Issue #34263 for more information
if key.startswith('__'):
continue
ret_kwargs[key] = kwargs[key]
if key in dnsopts:
if isinstance(dnsopts[key], six.string_types):
for config in includes:
__salt__['file.sed'](path=config,
before='^{0}=.*'.format(key),
after='{0}={1}'.format(key, kwargs[key]))
else:
__salt__['file.append'](config_file,
'{0}={1}'.format(key, kwargs[key]))
else:
__salt__['file.append'](config_file,
'{0}={1}'.format(key, kwargs[key]))
return ret_kwargs | python | def set_config(config_file='/etc/dnsmasq.conf', follow=True, **kwargs):
'''
Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not find it inside any files, it will append it to the main config
file. Setting follow to False will turn off this behavior.
If a config option currently appears multiple times (such as dhcp-host,
which is specified at least once per host), the new option will be added
to the end of the main config file (and not to any includes). If you need
an option added to a specific include file, specify it as the config_file.
:param string config_file: config file where settings should be updated / added.
:param bool follow: attempt to set the config option inside any file within
the ``conf-dir`` where it has already been enabled.
:param kwargs: key value pairs that contain the configuration settings that you
want set.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.set_config domain=mydomain.com
salt '*' dnsmasq.set_config follow=False domain=mydomain.com
salt '*' dnsmasq.set_config config_file=/etc/dnsmasq.conf domain=mydomain.com
'''
dnsopts = get_config(config_file)
includes = [config_file]
if follow is True and 'conf-dir' in dnsopts:
for filename in os.listdir(dnsopts['conf-dir']):
if filename.startswith('.'):
continue
if filename.endswith('~'):
continue
if filename.endswith('bak'):
continue
if filename.endswith('#') and filename.endswith('#'):
continue
includes.append('{0}/{1}'.format(dnsopts['conf-dir'], filename))
ret_kwargs = {}
for key in kwargs:
# Filter out __pub keys as they should not be added to the config file
# See Issue #34263 for more information
if key.startswith('__'):
continue
ret_kwargs[key] = kwargs[key]
if key in dnsopts:
if isinstance(dnsopts[key], six.string_types):
for config in includes:
__salt__['file.sed'](path=config,
before='^{0}=.*'.format(key),
after='{0}={1}'.format(key, kwargs[key]))
else:
__salt__['file.append'](config_file,
'{0}={1}'.format(key, kwargs[key]))
else:
__salt__['file.append'](config_file,
'{0}={1}'.format(key, kwargs[key]))
return ret_kwargs | [
"def",
"set_config",
"(",
"config_file",
"=",
"'/etc/dnsmasq.conf'",
",",
"follow",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"dnsopts",
"=",
"get_config",
"(",
"config_file",
")",
"includes",
"=",
"[",
"config_file",
"]",
"if",
"follow",
"is",
"True... | Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not find it inside any files, it will append it to the main config
file. Setting follow to False will turn off this behavior.
If a config option currently appears multiple times (such as dhcp-host,
which is specified at least once per host), the new option will be added
to the end of the main config file (and not to any includes). If you need
an option added to a specific include file, specify it as the config_file.
:param string config_file: config file where settings should be updated / added.
:param bool follow: attempt to set the config option inside any file within
the ``conf-dir`` where it has already been enabled.
:param kwargs: key value pairs that contain the configuration settings that you
want set.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.set_config domain=mydomain.com
salt '*' dnsmasq.set_config follow=False domain=mydomain.com
salt '*' dnsmasq.set_config config_file=/etc/dnsmasq.conf domain=mydomain.com | [
"Sets",
"a",
"value",
"or",
"a",
"set",
"of",
"values",
"in",
"the",
"specified",
"file",
".",
"By",
"default",
"if",
"conf",
"-",
"dir",
"is",
"configured",
"in",
"this",
"file",
"salt",
"will",
"attempt",
"to",
"set",
"the",
"option",
"in",
"any",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L70-L131 | train |
saltstack/salt | salt/modules/dnsmasq.py | get_config | def get_config(config_file='/etc/dnsmasq.conf'):
'''
Dumps all options from the config file.
config_file
The location of the config file from which to obtain contents.
Defaults to ``/etc/dnsmasq.conf``.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.get_config
salt '*' dnsmasq.get_config config_file=/etc/dnsmasq.conf
'''
dnsopts = _parse_dnamasq(config_file)
if 'conf-dir' in dnsopts:
for filename in os.listdir(dnsopts['conf-dir']):
if filename.startswith('.'):
continue
if filename.endswith('~'):
continue
if filename.endswith('#') and filename.endswith('#'):
continue
dnsopts.update(_parse_dnamasq('{0}/{1}'.format(dnsopts['conf-dir'],
filename)))
return dnsopts | python | def get_config(config_file='/etc/dnsmasq.conf'):
'''
Dumps all options from the config file.
config_file
The location of the config file from which to obtain contents.
Defaults to ``/etc/dnsmasq.conf``.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.get_config
salt '*' dnsmasq.get_config config_file=/etc/dnsmasq.conf
'''
dnsopts = _parse_dnamasq(config_file)
if 'conf-dir' in dnsopts:
for filename in os.listdir(dnsopts['conf-dir']):
if filename.startswith('.'):
continue
if filename.endswith('~'):
continue
if filename.endswith('#') and filename.endswith('#'):
continue
dnsopts.update(_parse_dnamasq('{0}/{1}'.format(dnsopts['conf-dir'],
filename)))
return dnsopts | [
"def",
"get_config",
"(",
"config_file",
"=",
"'/etc/dnsmasq.conf'",
")",
":",
"dnsopts",
"=",
"_parse_dnamasq",
"(",
"config_file",
")",
"if",
"'conf-dir'",
"in",
"dnsopts",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"dnsopts",
"[",
"'conf-dir'"... | Dumps all options from the config file.
config_file
The location of the config file from which to obtain contents.
Defaults to ``/etc/dnsmasq.conf``.
CLI Examples:
.. code-block:: bash
salt '*' dnsmasq.get_config
salt '*' dnsmasq.get_config config_file=/etc/dnsmasq.conf | [
"Dumps",
"all",
"options",
"from",
"the",
"config",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L134-L160 | train |
saltstack/salt | salt/modules/dnsmasq.py | _parse_dnamasq | def _parse_dnamasq(filename):
'''
Generic function for parsing dnsmasq files including includes.
'''
fileopts = {}
if not os.path.isfile(filename):
raise CommandExecutionError(
'Error: No such file \'{0}\''.format(filename)
)
with salt.utils.files.fopen(filename, 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if line.startswith('#'):
continue
if '=' in line:
comps = line.split('=')
if comps[0] in fileopts:
if isinstance(fileopts[comps[0]], six.string_types):
temp = fileopts[comps[0]]
fileopts[comps[0]] = [temp]
fileopts[comps[0]].append(comps[1].strip())
else:
fileopts[comps[0]] = comps[1].strip()
else:
if 'unparsed' not in fileopts:
fileopts['unparsed'] = []
fileopts['unparsed'].append(line)
return fileopts | python | def _parse_dnamasq(filename):
'''
Generic function for parsing dnsmasq files including includes.
'''
fileopts = {}
if not os.path.isfile(filename):
raise CommandExecutionError(
'Error: No such file \'{0}\''.format(filename)
)
with salt.utils.files.fopen(filename, 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if line.startswith('#'):
continue
if '=' in line:
comps = line.split('=')
if comps[0] in fileopts:
if isinstance(fileopts[comps[0]], six.string_types):
temp = fileopts[comps[0]]
fileopts[comps[0]] = [temp]
fileopts[comps[0]].append(comps[1].strip())
else:
fileopts[comps[0]] = comps[1].strip()
else:
if 'unparsed' not in fileopts:
fileopts['unparsed'] = []
fileopts['unparsed'].append(line)
return fileopts | [
"def",
"_parse_dnamasq",
"(",
"filename",
")",
":",
"fileopts",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Error: No such file \\'{0}\\''",
".",
"format",
"(",
"filename",
... | Generic function for parsing dnsmasq files including includes. | [
"Generic",
"function",
"for",
"parsing",
"dnsmasq",
"files",
"including",
"includes",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L163-L194 | train |
saltstack/salt | salt/output/key.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Read in the dict structure generated by the salt key API methods and
print the structure.
'''
color = salt.utils.color.get_colors(
__opts__.get('color'),
__opts__.get('color_theme'))
strip_colors = __opts__.get('strip_colors', True)
ident = 0
if __opts__.get('__multi_key'):
ident = 4
if __opts__['transport'] in ('zeromq', 'tcp'):
acc = 'minions'
pend = 'minions_pre'
den = 'minions_denied'
rej = 'minions_rejected'
cmap = {pend: color['RED'],
acc: color['GREEN'],
den: color['MAGENTA'],
rej: color['BLUE'],
'local': color['MAGENTA']}
trans = {pend: u'{0}{1}Unaccepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_RED'],
color['ENDC']),
acc: u'{0}{1}Accepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_GREEN'],
color['ENDC']),
den: u'{0}{1}Denied Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC']),
rej: u'{0}{1}Rejected Keys:{2}'.format(
' ' * ident,
color['LIGHT_BLUE'],
color['ENDC']),
'local': u'{0}{1}Local Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC'])}
else:
acc = 'accepted'
pend = 'pending'
rej = 'rejected'
cmap = {pend: color['RED'],
acc: color['GREEN'],
rej: color['BLUE'],
'local': color['MAGENTA']}
trans = {pend: u'{0}{1}Unaccepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_RED'],
color['ENDC']),
acc: u'{0}{1}Accepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_GREEN'],
color['ENDC']),
rej: u'{0}{1}Rejected Keys:{2}'.format(
' ' * ident,
color['LIGHT_BLUE'],
color['ENDC']),
'local': u'{0}{1}Local Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC'])}
ret = ''
for status in sorted(data):
ret += u'{0}\n'.format(trans[status])
for key in sorted(data[status]):
key = salt.utils.data.decode(key)
skey = salt.output.strip_esc_sequence(key) if strip_colors else key
if isinstance(data[status], list):
ret += u'{0}{1}{2}{3}\n'.format(
' ' * ident,
cmap[status],
skey,
color['ENDC'])
if isinstance(data[status], dict):
ret += u'{0}{1}{2}: {3}{4}\n'.format(
' ' * ident,
cmap[status],
skey,
data[status][key],
color['ENDC'])
return ret | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Read in the dict structure generated by the salt key API methods and
print the structure.
'''
color = salt.utils.color.get_colors(
__opts__.get('color'),
__opts__.get('color_theme'))
strip_colors = __opts__.get('strip_colors', True)
ident = 0
if __opts__.get('__multi_key'):
ident = 4
if __opts__['transport'] in ('zeromq', 'tcp'):
acc = 'minions'
pend = 'minions_pre'
den = 'minions_denied'
rej = 'minions_rejected'
cmap = {pend: color['RED'],
acc: color['GREEN'],
den: color['MAGENTA'],
rej: color['BLUE'],
'local': color['MAGENTA']}
trans = {pend: u'{0}{1}Unaccepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_RED'],
color['ENDC']),
acc: u'{0}{1}Accepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_GREEN'],
color['ENDC']),
den: u'{0}{1}Denied Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC']),
rej: u'{0}{1}Rejected Keys:{2}'.format(
' ' * ident,
color['LIGHT_BLUE'],
color['ENDC']),
'local': u'{0}{1}Local Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC'])}
else:
acc = 'accepted'
pend = 'pending'
rej = 'rejected'
cmap = {pend: color['RED'],
acc: color['GREEN'],
rej: color['BLUE'],
'local': color['MAGENTA']}
trans = {pend: u'{0}{1}Unaccepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_RED'],
color['ENDC']),
acc: u'{0}{1}Accepted Keys:{2}'.format(
' ' * ident,
color['LIGHT_GREEN'],
color['ENDC']),
rej: u'{0}{1}Rejected Keys:{2}'.format(
' ' * ident,
color['LIGHT_BLUE'],
color['ENDC']),
'local': u'{0}{1}Local Keys:{2}'.format(
' ' * ident,
color['LIGHT_MAGENTA'],
color['ENDC'])}
ret = ''
for status in sorted(data):
ret += u'{0}\n'.format(trans[status])
for key in sorted(data[status]):
key = salt.utils.data.decode(key)
skey = salt.output.strip_esc_sequence(key) if strip_colors else key
if isinstance(data[status], list):
ret += u'{0}{1}{2}{3}\n'.format(
' ' * ident,
cmap[status],
skey,
color['ENDC'])
if isinstance(data[status], dict):
ret += u'{0}{1}{2}: {3}{4}\n'.format(
' ' * ident,
cmap[status],
skey,
data[status][key],
color['ENDC'])
return ret | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"color",
"=",
"salt",
".",
"utils",
".",
"color",
".",
"get_colors",
"(",
"__opts__",
".",
"get",
"(",
"'color'",
")",
",",
"__opts__",
".",
"get",
"(",... | Read in the dict structure generated by the salt key API methods and
print the structure. | [
"Read",
"in",
"the",
"dict",
"structure",
"generated",
"by",
"the",
"salt",
"key",
"API",
"methods",
"and",
"print",
"the",
"structure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/key.py#L16-L107 | train |
saltstack/salt | salt/engines/sqs_events.py | _get_sqs_conn | def _get_sqs_conn(profile, region=None, key=None, keyid=None):
'''
Get a boto connection to SQS.
'''
if profile:
if isinstance(profile, six.string_types):
_profile = __opts__[profile]
elif isinstance(profile, dict):
_profile = profile
key = _profile.get('key', None)
keyid = _profile.get('keyid', None)
region = _profile.get('region', None)
if not region:
region = __opts__.get('sqs.region', 'us-east-1')
if not key:
key = __opts__.get('sqs.key', None)
if not keyid:
keyid = __opts__.get('sqs.keyid', None)
try:
conn = boto.sqs.connect_to_region(region, aws_access_key_id=keyid,
aws_secret_access_key=key)
except boto.exception.NoAuthHandlerFound:
log.error('No authentication credentials found when attempting to'
' make sqs_event engine connection to AWS.')
return None
return conn | python | def _get_sqs_conn(profile, region=None, key=None, keyid=None):
'''
Get a boto connection to SQS.
'''
if profile:
if isinstance(profile, six.string_types):
_profile = __opts__[profile]
elif isinstance(profile, dict):
_profile = profile
key = _profile.get('key', None)
keyid = _profile.get('keyid', None)
region = _profile.get('region', None)
if not region:
region = __opts__.get('sqs.region', 'us-east-1')
if not key:
key = __opts__.get('sqs.key', None)
if not keyid:
keyid = __opts__.get('sqs.keyid', None)
try:
conn = boto.sqs.connect_to_region(region, aws_access_key_id=keyid,
aws_secret_access_key=key)
except boto.exception.NoAuthHandlerFound:
log.error('No authentication credentials found when attempting to'
' make sqs_event engine connection to AWS.')
return None
return conn | [
"def",
"_get_sqs_conn",
"(",
"profile",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
")",
":",
"if",
"profile",
":",
"if",
"isinstance",
"(",
"profile",
",",
"six",
".",
"string_types",
")",
":",
"_profile",
"=",
"_... | Get a boto connection to SQS. | [
"Get",
"a",
"boto",
"connection",
"to",
"SQS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/sqs_events.py#L105-L131 | train |
saltstack/salt | salt/engines/sqs_events.py | start | def start(queue, profile=None, tag='salt/engine/sqs', owner_acct_id=None):
'''
Listen to sqs and fire message on event bus
'''
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir'],
listen=False).fire_event
else:
fire_master = __salt__['event.send']
message_format = __opts__.get('sqs.message_format', None)
sqs = _get_sqs_conn(profile)
q = None
while True:
if not q:
q = sqs.get_queue(queue, owner_acct_id=owner_acct_id)
q.set_message_class(boto.sqs.message.RawMessage)
_process_queue(q, queue, fire_master, tag=tag, owner_acct_id=owner_acct_id, message_format=message_format) | python | def start(queue, profile=None, tag='salt/engine/sqs', owner_acct_id=None):
'''
Listen to sqs and fire message on event bus
'''
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir'],
listen=False).fire_event
else:
fire_master = __salt__['event.send']
message_format = __opts__.get('sqs.message_format', None)
sqs = _get_sqs_conn(profile)
q = None
while True:
if not q:
q = sqs.get_queue(queue, owner_acct_id=owner_acct_id)
q.set_message_class(boto.sqs.message.RawMessage)
_process_queue(q, queue, fire_master, tag=tag, owner_acct_id=owner_acct_id, message_format=message_format) | [
"def",
"start",
"(",
"queue",
",",
"profile",
"=",
"None",
",",
"tag",
"=",
"'salt/engine/sqs'",
",",
"owner_acct_id",
"=",
"None",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'__role'",
")",
"==",
"'master'",
":",
"fire_master",
"=",
"salt",
".",
"u... | Listen to sqs and fire message on event bus | [
"Listen",
"to",
"sqs",
"and",
"fire",
"message",
"on",
"event",
"bus"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/sqs_events.py#L151-L172 | train |
saltstack/salt | salt/client/ssh/wrapper/cp.py | get_file | def get_file(path,
dest,
saltenv='base',
makedirs=False,
template=None,
gzip=None):
'''
Send a file from the master to the location in specified
.. note::
gzip compression is not supported in the salt-ssh version of
cp.get_file. The argument is only accepted for interface compatibility.
'''
if gzip is not None:
log.warning('The gzip argument to cp.get_file in salt-ssh is '
'unsupported')
if template is not None:
(path, dest) = _render_filenames(path, dest, saltenv, template)
src = __context__['fileclient'].cache_file(
path,
saltenv,
cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))
single = salt.client.ssh.Single(
__opts__,
'',
**__salt__.kwargs)
ret = single.shell.send(src, dest, makedirs)
return not ret[2] | python | def get_file(path,
dest,
saltenv='base',
makedirs=False,
template=None,
gzip=None):
'''
Send a file from the master to the location in specified
.. note::
gzip compression is not supported in the salt-ssh version of
cp.get_file. The argument is only accepted for interface compatibility.
'''
if gzip is not None:
log.warning('The gzip argument to cp.get_file in salt-ssh is '
'unsupported')
if template is not None:
(path, dest) = _render_filenames(path, dest, saltenv, template)
src = __context__['fileclient'].cache_file(
path,
saltenv,
cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))
single = salt.client.ssh.Single(
__opts__,
'',
**__salt__.kwargs)
ret = single.shell.send(src, dest, makedirs)
return not ret[2] | [
"def",
"get_file",
"(",
"path",
",",
"dest",
",",
"saltenv",
"=",
"'base'",
",",
"makedirs",
"=",
"False",
",",
"template",
"=",
"None",
",",
"gzip",
"=",
"None",
")",
":",
"if",
"gzip",
"is",
"not",
"None",
":",
"log",
".",
"warning",
"(",
"'The g... | Send a file from the master to the location in specified
.. note::
gzip compression is not supported in the salt-ssh version of
cp.get_file. The argument is only accepted for interface compatibility. | [
"Send",
"a",
"file",
"from",
"the",
"master",
"to",
"the",
"location",
"in",
"specified"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/cp.py#L20-L50 | train |
saltstack/salt | salt/client/ssh/wrapper/cp.py | get_dir | def get_dir(path, dest, saltenv='base'):
'''
Transfer a directory down
'''
src = __context__['fileclient'].cache_dir(
path,
saltenv,
cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))
src = ' '.join(src)
single = salt.client.ssh.Single(
__opts__,
'',
**__salt__.kwargs)
ret = single.shell.send(src, dest)
return not ret[2] | python | def get_dir(path, dest, saltenv='base'):
'''
Transfer a directory down
'''
src = __context__['fileclient'].cache_dir(
path,
saltenv,
cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))
src = ' '.join(src)
single = salt.client.ssh.Single(
__opts__,
'',
**__salt__.kwargs)
ret = single.shell.send(src, dest)
return not ret[2] | [
"def",
"get_dir",
"(",
"path",
",",
"dest",
",",
"saltenv",
"=",
"'base'",
")",
":",
"src",
"=",
"__context__",
"[",
"'fileclient'",
"]",
".",
"cache_dir",
"(",
"path",
",",
"saltenv",
",",
"cachedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'salt... | Transfer a directory down | [
"Transfer",
"a",
"directory",
"down"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/cp.py#L53-L67 | train |
saltstack/salt | salt/utils/immutabletypes.py | freeze | def freeze(obj):
'''
Freeze python types by turning them into immutable structures.
'''
if isinstance(obj, dict):
return ImmutableDict(obj)
if isinstance(obj, list):
return ImmutableList(obj)
if isinstance(obj, set):
return ImmutableSet(obj)
return obj | python | def freeze(obj):
'''
Freeze python types by turning them into immutable structures.
'''
if isinstance(obj, dict):
return ImmutableDict(obj)
if isinstance(obj, list):
return ImmutableList(obj)
if isinstance(obj, set):
return ImmutableSet(obj)
return obj | [
"def",
"freeze",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"ImmutableDict",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"ImmutableList",
"(",
"obj",
")",
"if",
"isinst... | Freeze python types by turning them into immutable structures. | [
"Freeze",
"python",
"types",
"by",
"turning",
"them",
"into",
"immutable",
"structures",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/immutabletypes.py#L105-L115 | train |
saltstack/salt | salt/modules/alternatives.py | display | def display(name):
'''
Display alternatives settings for defined command name
CLI Example:
.. code-block:: bash
salt '*' alternatives.display editor
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return out['stderr']
return out['stdout'] | python | def display(name):
'''
Display alternatives settings for defined command name
CLI Example:
.. code-block:: bash
salt '*' alternatives.display editor
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return out['stderr']
return out['stdout'] | [
"def",
"display",
"(",
"name",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--display'",
",",
"name",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"out",
"[",
"'retcode'"... | Display alternatives settings for defined command name
CLI Example:
.. code-block:: bash
salt '*' alternatives.display editor | [
"Display",
"alternatives",
"settings",
"for",
"defined",
"command",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L53-L67 | train |
saltstack/salt | salt/modules/alternatives.py | show_link | def show_link(name):
'''
Display master link for the alternative
.. versionadded:: 2015.8.13,2016.3.4,2016.11.0
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_link editor
'''
if __grains__['os_family'] == 'RedHat':
path = '/var/lib/'
elif __grains__['os_family'] == 'Suse':
path = '/var/lib/rpm/'
else:
path = '/var/lib/dpkg/'
path += 'alternatives/{0}'.format(name)
try:
with salt.utils.files.fopen(path, 'rb') as r_file:
contents = salt.utils.stringutils.to_unicode(r_file.read())
return contents.splitlines(True)[1].rstrip('\n')
except OSError:
log.error('alternatives: %s does not exist', name)
except (IOError, IndexError) as exc:
log.error(
'alternatives: unable to get master link for %s. '
'Exception: %s', name, exc
)
return False | python | def show_link(name):
'''
Display master link for the alternative
.. versionadded:: 2015.8.13,2016.3.4,2016.11.0
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_link editor
'''
if __grains__['os_family'] == 'RedHat':
path = '/var/lib/'
elif __grains__['os_family'] == 'Suse':
path = '/var/lib/rpm/'
else:
path = '/var/lib/dpkg/'
path += 'alternatives/{0}'.format(name)
try:
with salt.utils.files.fopen(path, 'rb') as r_file:
contents = salt.utils.stringutils.to_unicode(r_file.read())
return contents.splitlines(True)[1].rstrip('\n')
except OSError:
log.error('alternatives: %s does not exist', name)
except (IOError, IndexError) as exc:
log.error(
'alternatives: unable to get master link for %s. '
'Exception: %s', name, exc
)
return False | [
"def",
"show_link",
"(",
"name",
")",
":",
"if",
"__grains__",
"[",
"'os_family'",
"]",
"==",
"'RedHat'",
":",
"path",
"=",
"'/var/lib/'",
"elif",
"__grains__",
"[",
"'os_family'",
"]",
"==",
"'Suse'",
":",
"path",
"=",
"'/var/lib/rpm/'",
"else",
":",
"pat... | Display master link for the alternative
.. versionadded:: 2015.8.13,2016.3.4,2016.11.0
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_link editor | [
"Display",
"master",
"link",
"for",
"the",
"alternative"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L70-L104 | train |
saltstack/salt | salt/modules/alternatives.py | check_exists | def check_exists(name, path):
'''
Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return False
return any((line.startswith(path) for line in out['stdout'].splitlines())) | python | def check_exists(name, path):
'''
Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return False
return any((line.startswith(path) for line in out['stdout'].splitlines())) | [
"def",
"check_exists",
"(",
"name",
",",
"path",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--display'",
",",
"name",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"out"... | Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path | [
"Check",
"if",
"the",
"given",
"path",
"is",
"an",
"alternative",
"for",
"a",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L125-L143 | train |
saltstack/salt | salt/modules/alternatives.py | install | def install(name, link, path, priority):
'''
Install symbolic links determining default commands
CLI Example:
.. code-block:: bash
salt '*' alternatives.install editor /usr/bin/editor /usr/bin/emacs23 50
'''
cmd = [_get_cmd(), '--install', link, name, path, six.text_type(priority)]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return out['stderr']
return out['stdout'] | python | def install(name, link, path, priority):
'''
Install symbolic links determining default commands
CLI Example:
.. code-block:: bash
salt '*' alternatives.install editor /usr/bin/editor /usr/bin/emacs23 50
'''
cmd = [_get_cmd(), '--install', link, name, path, six.text_type(priority)]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['stderr'] != '':
return out['stderr']
return out['stdout'] | [
"def",
"install",
"(",
"name",
",",
"link",
",",
"path",
",",
"priority",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--install'",
",",
"link",
",",
"name",
",",
"path",
",",
"six",
".",
"text_type",
"(",
"priority",
")",
"]",
"out",
... | Install symbolic links determining default commands
CLI Example:
.. code-block:: bash
salt '*' alternatives.install editor /usr/bin/editor /usr/bin/emacs23 50 | [
"Install",
"symbolic",
"links",
"determining",
"default",
"commands"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L163-L177 | train |
saltstack/salt | salt/modules/alternatives.py | remove | def remove(name, path):
'''
Remove symbolic links determining the default commands.
CLI Example:
.. code-block:: bash
salt '*' alternatives.remove name path
'''
cmd = [_get_cmd(), '--remove', name, path]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
return out['stderr']
return out['stdout'] | python | def remove(name, path):
'''
Remove symbolic links determining the default commands.
CLI Example:
.. code-block:: bash
salt '*' alternatives.remove name path
'''
cmd = [_get_cmd(), '--remove', name, path]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
return out['stderr']
return out['stdout'] | [
"def",
"remove",
"(",
"name",
",",
"path",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--remove'",
",",
"name",
",",
"path",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if... | Remove symbolic links determining the default commands.
CLI Example:
.. code-block:: bash
salt '*' alternatives.remove name path | [
"Remove",
"symbolic",
"links",
"determining",
"the",
"default",
"commands",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L180-L194 | train |
saltstack/salt | salt/modules/alternatives.py | auto | def auto(name):
'''
Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name
'''
cmd = [_get_cmd(), '--auto', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
return out['stderr']
return out['stdout'] | python | def auto(name):
'''
Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name
'''
cmd = [_get_cmd(), '--auto', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
return out['stderr']
return out['stdout'] | [
"def",
"auto",
"(",
"name",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--auto'",
",",
"name",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"out",
"[",
"'retcode'",
"]... | Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name | [
"Trigger",
"alternatives",
"to",
"set",
"the",
"path",
"for",
"<name",
">",
"as",
"specified",
"by",
"priority",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L197-L212 | train |
saltstack/salt | salt/modules/alternatives.py | _read_link | def _read_link(name):
'''
Read the link from /etc/alternatives
Throws an OSError if the link does not exist
'''
alt_link_path = '/etc/alternatives/{0}'.format(name)
return salt.utils.path.readlink(alt_link_path) | python | def _read_link(name):
'''
Read the link from /etc/alternatives
Throws an OSError if the link does not exist
'''
alt_link_path = '/etc/alternatives/{0}'.format(name)
return salt.utils.path.readlink(alt_link_path) | [
"def",
"_read_link",
"(",
"name",
")",
":",
"alt_link_path",
"=",
"'/etc/alternatives/{0}'",
".",
"format",
"(",
"name",
")",
"return",
"salt",
".",
"utils",
".",
"path",
".",
"readlink",
"(",
"alt_link_path",
")"
] | Read the link from /etc/alternatives
Throws an OSError if the link does not exist | [
"Read",
"the",
"link",
"from",
"/",
"etc",
"/",
"alternatives"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L232-L239 | train |
saltstack/salt | salt/utils/pbm.py | get_placement_solver | def get_placement_solver(service_instance):
'''
Returns a placement solver
service_instance
Service instance to the host or vCenter
'''
stub = salt.utils.vmware.get_new_service_instance_stub(
service_instance, ns='pbm/2.0', path='/pbm/sdk')
pbm_si = pbm.ServiceInstance('ServiceInstance', stub)
try:
profile_manager = pbm_si.RetrieveContent().placementSolver
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
return profile_manager | python | def get_placement_solver(service_instance):
'''
Returns a placement solver
service_instance
Service instance to the host or vCenter
'''
stub = salt.utils.vmware.get_new_service_instance_stub(
service_instance, ns='pbm/2.0', path='/pbm/sdk')
pbm_si = pbm.ServiceInstance('ServiceInstance', stub)
try:
profile_manager = pbm_si.RetrieveContent().placementSolver
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
return profile_manager | [
"def",
"get_placement_solver",
"(",
"service_instance",
")",
":",
"stub",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_new_service_instance_stub",
"(",
"service_instance",
",",
"ns",
"=",
"'pbm/2.0'",
",",
"path",
"=",
"'/pbm/sdk'",
")",
"pbm_si",
"=",
... | Returns a placement solver
service_instance
Service instance to the host or vCenter | [
"Returns",
"a",
"placement",
"solver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L98-L120 | train |
saltstack/salt | salt/utils/pbm.py | get_capability_definitions | def get_capability_definitions(profile_manager):
'''
Returns a list of all capability definitions.
profile_manager
Reference to the profile manager.
'''
res_type = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
try:
cap_categories = profile_manager.FetchCapabilityMetadata(res_type)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
cap_definitions = []
for cat in cap_categories:
cap_definitions.extend(cat.capabilityMetadata)
return cap_definitions | python | def get_capability_definitions(profile_manager):
'''
Returns a list of all capability definitions.
profile_manager
Reference to the profile manager.
'''
res_type = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
try:
cap_categories = profile_manager.FetchCapabilityMetadata(res_type)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
cap_definitions = []
for cat in cap_categories:
cap_definitions.extend(cat.capabilityMetadata)
return cap_definitions | [
"def",
"get_capability_definitions",
"(",
"profile_manager",
")",
":",
"res_type",
"=",
"pbm",
".",
"profile",
".",
"ResourceType",
"(",
"resourceType",
"=",
"pbm",
".",
"profile",
".",
"ResourceTypeEnum",
".",
"STORAGE",
")",
"try",
":",
"cap_categories",
"=",
... | Returns a list of all capability definitions.
profile_manager
Reference to the profile manager. | [
"Returns",
"a",
"list",
"of",
"all",
"capability",
"definitions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L123-L147 | train |
saltstack/salt | salt/utils/pbm.py | get_policies_by_id | def get_policies_by_id(profile_manager, policy_ids):
'''
Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve.
'''
try:
return profile_manager.RetrieveContent(policy_ids)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | python | def get_policies_by_id(profile_manager, policy_ids):
'''
Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve.
'''
try:
return profile_manager.RetrieveContent(policy_ids)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | [
"def",
"get_policies_by_id",
"(",
"profile_manager",
",",
"policy_ids",
")",
":",
"try",
":",
"return",
"profile_manager",
".",
"RetrieveContent",
"(",
"policy_ids",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"except... | Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve. | [
"Returns",
"a",
"list",
"of",
"policies",
"with",
"the",
"specified",
"ids",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L150-L171 | train |
saltstack/salt | salt/utils/pbm.py | get_storage_policies | def get_storage_policies(profile_manager, policy_names=None,
get_all_policies=False):
'''
Returns a list of the storage policies, filtered by name.
profile_manager
Reference to the profile manager.
policy_names
List of policy names to filter by.
Default is None.
get_all_policies
Flag specifying to return all policies, regardless of the specified
filter.
'''
res_type = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
try:
policy_ids = profile_manager.QueryProfile(res_type)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
log.trace('policy_ids = %s', policy_ids)
# More policies are returned so we need to filter again
policies = [p for p in get_policies_by_id(profile_manager, policy_ids)
if p.resourceType.resourceType ==
pbm.profile.ResourceTypeEnum.STORAGE]
if get_all_policies:
return policies
if not policy_names:
policy_names = []
return [p for p in policies if p.name in policy_names] | python | def get_storage_policies(profile_manager, policy_names=None,
get_all_policies=False):
'''
Returns a list of the storage policies, filtered by name.
profile_manager
Reference to the profile manager.
policy_names
List of policy names to filter by.
Default is None.
get_all_policies
Flag specifying to return all policies, regardless of the specified
filter.
'''
res_type = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
try:
policy_ids = profile_manager.QueryProfile(res_type)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
log.trace('policy_ids = %s', policy_ids)
# More policies are returned so we need to filter again
policies = [p for p in get_policies_by_id(profile_manager, policy_ids)
if p.resourceType.resourceType ==
pbm.profile.ResourceTypeEnum.STORAGE]
if get_all_policies:
return policies
if not policy_names:
policy_names = []
return [p for p in policies if p.name in policy_names] | [
"def",
"get_storage_policies",
"(",
"profile_manager",
",",
"policy_names",
"=",
"None",
",",
"get_all_policies",
"=",
"False",
")",
":",
"res_type",
"=",
"pbm",
".",
"profile",
".",
"ResourceType",
"(",
"resourceType",
"=",
"pbm",
".",
"profile",
".",
"Resour... | Returns a list of the storage policies, filtered by name.
profile_manager
Reference to the profile manager.
policy_names
List of policy names to filter by.
Default is None.
get_all_policies
Flag specifying to return all policies, regardless of the specified
filter. | [
"Returns",
"a",
"list",
"of",
"the",
"storage",
"policies",
"filtered",
"by",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L174-L213 | train |
saltstack/salt | salt/utils/pbm.py | create_storage_policy | def create_storage_policy(profile_manager, policy_spec):
'''
Creates a storage policy.
profile_manager
Reference to the profile manager.
policy_spec
Policy update spec.
'''
try:
profile_manager.Create(policy_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | python | def create_storage_policy(profile_manager, policy_spec):
'''
Creates a storage policy.
profile_manager
Reference to the profile manager.
policy_spec
Policy update spec.
'''
try:
profile_manager.Create(policy_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | [
"def",
"create_storage_policy",
"(",
"profile_manager",
",",
"policy_spec",
")",
":",
"try",
":",
"profile_manager",
".",
"Create",
"(",
"policy_spec",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"... | Creates a storage policy.
profile_manager
Reference to the profile manager.
policy_spec
Policy update spec. | [
"Creates",
"a",
"storage",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L216-L237 | train |
saltstack/salt | salt/utils/pbm.py | update_storage_policy | def update_storage_policy(profile_manager, policy, policy_spec):
'''
Updates a storage policy.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to be updated.
policy_spec
Policy update spec.
'''
try:
profile_manager.Update(policy.profileId, policy_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | python | def update_storage_policy(profile_manager, policy, policy_spec):
'''
Updates a storage policy.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to be updated.
policy_spec
Policy update spec.
'''
try:
profile_manager.Update(policy.profileId, policy_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | [
"def",
"update_storage_policy",
"(",
"profile_manager",
",",
"policy",
",",
"policy_spec",
")",
":",
"try",
":",
"profile_manager",
".",
"Update",
"(",
"policy",
".",
"profileId",
",",
"policy_spec",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as... | Updates a storage policy.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to be updated.
policy_spec
Policy update spec. | [
"Updates",
"a",
"storage",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L240-L264 | train |
saltstack/salt | salt/utils/pbm.py | get_default_storage_policy_of_datastore | def get_default_storage_policy_of_datastore(profile_manager, datastore):
'''
Returns the default storage policy reference assigned to a datastore.
profile_manager
Reference to the profile manager.
datastore
Reference to the datastore.
'''
# Retrieve all datastores visible
hub = pbm.placement.PlacementHub(
hubId=datastore._moId, hubType='Datastore')
log.trace('placement_hub = %s', hub)
try:
policy_id = profile_manager.QueryDefaultRequirementProfile(hub)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
policy_refs = get_policies_by_id(profile_manager, [policy_id])
if not policy_refs:
raise VMwareObjectRetrievalError('Storage policy with id \'{0}\' was '
'not found'.format(policy_id))
return policy_refs[0] | python | def get_default_storage_policy_of_datastore(profile_manager, datastore):
'''
Returns the default storage policy reference assigned to a datastore.
profile_manager
Reference to the profile manager.
datastore
Reference to the datastore.
'''
# Retrieve all datastores visible
hub = pbm.placement.PlacementHub(
hubId=datastore._moId, hubType='Datastore')
log.trace('placement_hub = %s', hub)
try:
policy_id = profile_manager.QueryDefaultRequirementProfile(hub)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
policy_refs = get_policies_by_id(profile_manager, [policy_id])
if not policy_refs:
raise VMwareObjectRetrievalError('Storage policy with id \'{0}\' was '
'not found'.format(policy_id))
return policy_refs[0] | [
"def",
"get_default_storage_policy_of_datastore",
"(",
"profile_manager",
",",
"datastore",
")",
":",
"# Retrieve all datastores visible",
"hub",
"=",
"pbm",
".",
"placement",
".",
"PlacementHub",
"(",
"hubId",
"=",
"datastore",
".",
"_moId",
",",
"hubType",
"=",
"'... | Returns the default storage policy reference assigned to a datastore.
profile_manager
Reference to the profile manager.
datastore
Reference to the datastore. | [
"Returns",
"the",
"default",
"storage",
"policy",
"reference",
"assigned",
"to",
"a",
"datastore",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L267-L297 | train |
saltstack/salt | salt/utils/pbm.py | assign_default_storage_policy_to_datastore | def assign_default_storage_policy_to_datastore(profile_manager, policy,
datastore):
'''
Assigns a storage policy as the default policy to a datastore.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to assigned.
datastore
Reference to the datastore.
'''
placement_hub = pbm.placement.PlacementHub(
hubId=datastore._moId, hubType='Datastore')
log.trace('placement_hub = %s', placement_hub)
try:
profile_manager.AssignDefaultRequirementProfile(policy.profileId,
[placement_hub])
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | python | def assign_default_storage_policy_to_datastore(profile_manager, policy,
datastore):
'''
Assigns a storage policy as the default policy to a datastore.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to assigned.
datastore
Reference to the datastore.
'''
placement_hub = pbm.placement.PlacementHub(
hubId=datastore._moId, hubType='Datastore')
log.trace('placement_hub = %s', placement_hub)
try:
profile_manager.AssignDefaultRequirementProfile(policy.profileId,
[placement_hub])
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | [
"def",
"assign_default_storage_policy_to_datastore",
"(",
"profile_manager",
",",
"policy",
",",
"datastore",
")",
":",
"placement_hub",
"=",
"pbm",
".",
"placement",
".",
"PlacementHub",
"(",
"hubId",
"=",
"datastore",
".",
"_moId",
",",
"hubType",
"=",
"'Datasto... | Assigns a storage policy as the default policy to a datastore.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to assigned.
datastore
Reference to the datastore. | [
"Assigns",
"a",
"storage",
"policy",
"as",
"the",
"default",
"policy",
"to",
"a",
"datastore",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pbm.py#L300-L329 | train |
saltstack/salt | salt/sdb/redis_sdb.py | set_ | def set_(key, value, profile=None):
'''
Set a value into the Redis SDB.
'''
if not profile:
return False
redis_kwargs = profile.copy()
redis_kwargs.pop('driver')
redis_conn = redis.StrictRedis(**redis_kwargs)
return redis_conn.set(key, value) | python | def set_(key, value, profile=None):
'''
Set a value into the Redis SDB.
'''
if not profile:
return False
redis_kwargs = profile.copy()
redis_kwargs.pop('driver')
redis_conn = redis.StrictRedis(**redis_kwargs)
return redis_conn.set(key, value) | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"profile",
":",
"return",
"False",
"redis_kwargs",
"=",
"profile",
".",
"copy",
"(",
")",
"redis_kwargs",
".",
"pop",
"(",
"'driver'",
")",
"redis_conn",
"=",
... | Set a value into the Redis SDB. | [
"Set",
"a",
"value",
"into",
"the",
"Redis",
"SDB",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/redis_sdb.py#L51-L60 | train |
saltstack/salt | salt/sdb/redis_sdb.py | get | def get(key, profile=None):
'''
Get a value from the Redis SDB.
'''
if not profile:
return False
redis_kwargs = profile.copy()
redis_kwargs.pop('driver')
redis_conn = redis.StrictRedis(**redis_kwargs)
return redis_conn.get(key) | python | def get(key, profile=None):
'''
Get a value from the Redis SDB.
'''
if not profile:
return False
redis_kwargs = profile.copy()
redis_kwargs.pop('driver')
redis_conn = redis.StrictRedis(**redis_kwargs)
return redis_conn.get(key) | [
"def",
"get",
"(",
"key",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"profile",
":",
"return",
"False",
"redis_kwargs",
"=",
"profile",
".",
"copy",
"(",
")",
"redis_kwargs",
".",
"pop",
"(",
"'driver'",
")",
"redis_conn",
"=",
"redis",
".",
... | Get a value from the Redis SDB. | [
"Get",
"a",
"value",
"from",
"the",
"Redis",
"SDB",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/redis_sdb.py#L63-L72 | train |
saltstack/salt | salt/states/libcloud_loadbalancer.py | balancer_present | def balancer_present(name, port, protocol, profile, algorithm=None, members=None, **libcloud_kwargs):
'''
Ensures a load balancer is present.
:param name: Load Balancer name
:type name: ``str``
:param port: Port the load balancer should listen on, defaults to 80
:type port: ``str``
:param protocol: Loadbalancer protocol, defaults to http.
:type protocol: ``str``
:param profile: The profile key
:type profile: ``str``
:param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type
in Libcloud documentation for a full listing.
:type algorithm: ``str``
:param members: An optional list of members to create on deployment
:type members: ``list`` of ``dict`` (ip, port)
'''
balancers = __salt__['libcloud_loadbalancer.list_balancers'](profile)
match = [z for z in balancers if z['name'] == name]
if match:
return state_result(True, "Balancer already exists", name)
else:
starting_members = None
if members is not None:
starting_members = []
for m in members:
starting_members.append({'ip': m['ip'], 'port': m['port']})
balancer = __salt__['libcloud_loadbalancer.create_balancer'](
name, port, protocol,
profile, algorithm=algorithm,
members=starting_members,
**libcloud_kwargs)
return state_result(True, "Created new load balancer", name, balancer) | python | def balancer_present(name, port, protocol, profile, algorithm=None, members=None, **libcloud_kwargs):
'''
Ensures a load balancer is present.
:param name: Load Balancer name
:type name: ``str``
:param port: Port the load balancer should listen on, defaults to 80
:type port: ``str``
:param protocol: Loadbalancer protocol, defaults to http.
:type protocol: ``str``
:param profile: The profile key
:type profile: ``str``
:param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type
in Libcloud documentation for a full listing.
:type algorithm: ``str``
:param members: An optional list of members to create on deployment
:type members: ``list`` of ``dict`` (ip, port)
'''
balancers = __salt__['libcloud_loadbalancer.list_balancers'](profile)
match = [z for z in balancers if z['name'] == name]
if match:
return state_result(True, "Balancer already exists", name)
else:
starting_members = None
if members is not None:
starting_members = []
for m in members:
starting_members.append({'ip': m['ip'], 'port': m['port']})
balancer = __salt__['libcloud_loadbalancer.create_balancer'](
name, port, protocol,
profile, algorithm=algorithm,
members=starting_members,
**libcloud_kwargs)
return state_result(True, "Created new load balancer", name, balancer) | [
"def",
"balancer_present",
"(",
"name",
",",
"port",
",",
"protocol",
",",
"profile",
",",
"algorithm",
"=",
"None",
",",
"members",
"=",
"None",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"balancers",
"=",
"__salt__",
"[",
"'libcloud_loadbalancer.list_balanc... | Ensures a load balancer is present.
:param name: Load Balancer name
:type name: ``str``
:param port: Port the load balancer should listen on, defaults to 80
:type port: ``str``
:param protocol: Loadbalancer protocol, defaults to http.
:type protocol: ``str``
:param profile: The profile key
:type profile: ``str``
:param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type
in Libcloud documentation for a full listing.
:type algorithm: ``str``
:param members: An optional list of members to create on deployment
:type members: ``list`` of ``dict`` (ip, port) | [
"Ensures",
"a",
"load",
"balancer",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_loadbalancer.py#L76-L114 | train |
saltstack/salt | salt/states/libcloud_loadbalancer.py | balancer_absent | def balancer_absent(name, profile, **libcloud_kwargs):
'''
Ensures a load balancer is absent.
:param name: Load Balancer name
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
balancers = __salt__['libcloud_loadbalancer.list_balancers'](profile)
match = [z for z in balancers if z['name'] == name]
if not match:
return state_result(True, "Balancer already absent", name)
else:
result = __salt__['libcloud_loadbalancer.destroy_balancer'](match[0]['id'], profile, **libcloud_kwargs)
return state_result(result, "Deleted load balancer", name) | python | def balancer_absent(name, profile, **libcloud_kwargs):
'''
Ensures a load balancer is absent.
:param name: Load Balancer name
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
balancers = __salt__['libcloud_loadbalancer.list_balancers'](profile)
match = [z for z in balancers if z['name'] == name]
if not match:
return state_result(True, "Balancer already absent", name)
else:
result = __salt__['libcloud_loadbalancer.destroy_balancer'](match[0]['id'], profile, **libcloud_kwargs)
return state_result(result, "Deleted load balancer", name) | [
"def",
"balancer_absent",
"(",
"name",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"balancers",
"=",
"__salt__",
"[",
"'libcloud_loadbalancer.list_balancers'",
"]",
"(",
"profile",
")",
"match",
"=",
"[",
"z",
"for",
"z",
"in",
"balancers",
"... | Ensures a load balancer is absent.
:param name: Load Balancer name
:type name: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensures",
"a",
"load",
"balancer",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_loadbalancer.py#L117-L133 | train |
saltstack/salt | salt/states/libcloud_loadbalancer.py | member_present | def member_present(ip, port, balancer_id, profile, **libcloud_kwargs):
'''
Ensure a load balancer member is present
:param ip: IP address for the new member
:type ip: ``str``
:param port: Port for the new member
:type port: ``int``
:param balancer_id: id of a load balancer you want to attach the member to
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_members = __salt__['libcloud_loadbalancer.list_balancer_members'](balancer_id, profile)
for member in existing_members:
if member['ip'] == ip and member['port'] == port:
return state_result(True, "Member already present", balancer_id)
member = __salt__['libcloud_loadbalancer.balancer_attach_member'](balancer_id, ip, port, profile, **libcloud_kwargs)
return state_result(True, "Member added to balancer, id: {0}".format(member['id']), balancer_id, member) | python | def member_present(ip, port, balancer_id, profile, **libcloud_kwargs):
'''
Ensure a load balancer member is present
:param ip: IP address for the new member
:type ip: ``str``
:param port: Port for the new member
:type port: ``int``
:param balancer_id: id of a load balancer you want to attach the member to
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_members = __salt__['libcloud_loadbalancer.list_balancer_members'](balancer_id, profile)
for member in existing_members:
if member['ip'] == ip and member['port'] == port:
return state_result(True, "Member already present", balancer_id)
member = __salt__['libcloud_loadbalancer.balancer_attach_member'](balancer_id, ip, port, profile, **libcloud_kwargs)
return state_result(True, "Member added to balancer, id: {0}".format(member['id']), balancer_id, member) | [
"def",
"member_present",
"(",
"ip",
",",
"port",
",",
"balancer_id",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"existing_members",
"=",
"__salt__",
"[",
"'libcloud_loadbalancer.list_balancer_members'",
"]",
"(",
"balancer_id",
",",
"profile",
")"... | Ensure a load balancer member is present
:param ip: IP address for the new member
:type ip: ``str``
:param port: Port for the new member
:type port: ``int``
:param balancer_id: id of a load balancer you want to attach the member to
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensure",
"a",
"load",
"balancer",
"member",
"is",
"present"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_loadbalancer.py#L136-L157 | train |
saltstack/salt | salt/states/libcloud_loadbalancer.py | member_absent | def member_absent(ip, port, balancer_id, profile, **libcloud_kwargs):
'''
Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a load balancer you want to detach the member from
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_members = __salt__['libcloud_loadbalancer.list_balancer_members'](balancer_id, profile)
for member in existing_members:
if member['ip'] == ip and member['port'] == port:
result = __salt__['libcloud_loadbalancer.balancer_detach_member'](balancer_id, member['id'], profile, **libcloud_kwargs)
return state_result(result, "Member removed", balancer_id)
return state_result(True, "Member already absent", balancer_id) | python | def member_absent(ip, port, balancer_id, profile, **libcloud_kwargs):
'''
Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a load balancer you want to detach the member from
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_members = __salt__['libcloud_loadbalancer.list_balancer_members'](balancer_id, profile)
for member in existing_members:
if member['ip'] == ip and member['port'] == port:
result = __salt__['libcloud_loadbalancer.balancer_detach_member'](balancer_id, member['id'], profile, **libcloud_kwargs)
return state_result(result, "Member removed", balancer_id)
return state_result(True, "Member already absent", balancer_id) | [
"def",
"member_absent",
"(",
"ip",
",",
"port",
",",
"balancer_id",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"existing_members",
"=",
"__salt__",
"[",
"'libcloud_loadbalancer.list_balancer_members'",
"]",
"(",
"balancer_id",
",",
"profile",
")",... | Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a load balancer you want to detach the member from
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensure",
"a",
"load",
"balancer",
"member",
"is",
"absent",
"based",
"on",
"IP",
"and",
"Port"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_loadbalancer.py#L160-L181 | train |
saltstack/salt | salt/modules/sysbench.py | _parser | def _parser(result):
'''
parses the output into a dictionary
'''
# regexes to match
_total_time = re.compile(r'total time:\s*(\d*.\d*s)')
_total_execution = re.compile(r'event execution:\s*(\d*.\d*s?)')
_min_response_time = re.compile(r'min:\s*(\d*.\d*ms)')
_max_response_time = re.compile(r'max:\s*(\d*.\d*ms)')
_avg_response_time = re.compile(r'avg:\s*(\d*.\d*ms)')
_per_response_time = re.compile(r'95 percentile:\s*(\d*.\d*ms)')
# extracting data
total_time = re.search(_total_time, result).group(1)
total_execution = re.search(_total_execution, result).group(1)
min_response_time = re.search(_min_response_time, result).group(1)
max_response_time = re.search(_max_response_time, result).group(1)
avg_response_time = re.search(_avg_response_time, result).group(1)
per_response_time = re.search(_per_response_time, result)
if per_response_time is not None:
per_response_time = per_response_time.group(1)
# returning the data as dictionary
return {
'total time': total_time,
'total execution time': total_execution,
'minimum response time': min_response_time,
'maximum response time': max_response_time,
'average response time': avg_response_time,
'95 percentile': per_response_time
} | python | def _parser(result):
'''
parses the output into a dictionary
'''
# regexes to match
_total_time = re.compile(r'total time:\s*(\d*.\d*s)')
_total_execution = re.compile(r'event execution:\s*(\d*.\d*s?)')
_min_response_time = re.compile(r'min:\s*(\d*.\d*ms)')
_max_response_time = re.compile(r'max:\s*(\d*.\d*ms)')
_avg_response_time = re.compile(r'avg:\s*(\d*.\d*ms)')
_per_response_time = re.compile(r'95 percentile:\s*(\d*.\d*ms)')
# extracting data
total_time = re.search(_total_time, result).group(1)
total_execution = re.search(_total_execution, result).group(1)
min_response_time = re.search(_min_response_time, result).group(1)
max_response_time = re.search(_max_response_time, result).group(1)
avg_response_time = re.search(_avg_response_time, result).group(1)
per_response_time = re.search(_per_response_time, result)
if per_response_time is not None:
per_response_time = per_response_time.group(1)
# returning the data as dictionary
return {
'total time': total_time,
'total execution time': total_execution,
'minimum response time': min_response_time,
'maximum response time': max_response_time,
'average response time': avg_response_time,
'95 percentile': per_response_time
} | [
"def",
"_parser",
"(",
"result",
")",
":",
"# regexes to match",
"_total_time",
"=",
"re",
".",
"compile",
"(",
"r'total time:\\s*(\\d*.\\d*s)'",
")",
"_total_execution",
"=",
"re",
".",
"compile",
"(",
"r'event execution:\\s*(\\d*.\\d*s?)'",
")",
"_min_response_time",
... | parses the output into a dictionary | [
"parses",
"the",
"output",
"into",
"a",
"dictionary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L25-L56 | train |
saltstack/salt | salt/modules/sysbench.py | cpu | def cpu():
'''
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu
'''
# Test data
max_primes = [500, 1000, 2500, 5000]
# Initializing the test variables
test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
result = None
ret_val = {}
# Test beings!
for primes in max_primes:
key = 'Prime numbers limit: {0}'.format(primes)
run_command = test_command.format(primes)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | python | def cpu():
'''
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu
'''
# Test data
max_primes = [500, 1000, 2500, 5000]
# Initializing the test variables
test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
result = None
ret_val = {}
# Test beings!
for primes in max_primes:
key = 'Prime numbers limit: {0}'.format(primes)
run_command = test_command.format(primes)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | [
"def",
"cpu",
"(",
")",
":",
"# Test data",
"max_primes",
"=",
"[",
"500",
",",
"1000",
",",
"2500",
",",
"5000",
"]",
"# Initializing the test variables",
"test_command",
"=",
"'sysbench --test=cpu --cpu-max-prime={0} run'",
"result",
"=",
"None",
"ret_val",
"=",
... | Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu | [
"Tests",
"for",
"the",
"CPU",
"performance",
"of",
"minions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L59-L85 | train |
saltstack/salt | salt/modules/sysbench.py | threads | def threads():
'''
This tests the performance of the processor's scheduler
CLI Example:
.. code-block:: bash
salt '*' sysbench.threads
'''
# Test data
thread_yields = [100, 200, 500, 1000]
thread_locks = [2, 4, 8, 16]
# Initializing the test variables
test_command = 'sysbench --num-threads=64 --test=threads '
test_command += '--thread-yields={0} --thread-locks={1} run '
result = None
ret_val = {}
# Test begins!
for yields, locks in zip(thread_yields, thread_locks):
key = 'Yields: {0} Locks: {1}'.format(yields, locks)
run_command = test_command.format(yields, locks)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | python | def threads():
'''
This tests the performance of the processor's scheduler
CLI Example:
.. code-block:: bash
salt '*' sysbench.threads
'''
# Test data
thread_yields = [100, 200, 500, 1000]
thread_locks = [2, 4, 8, 16]
# Initializing the test variables
test_command = 'sysbench --num-threads=64 --test=threads '
test_command += '--thread-yields={0} --thread-locks={1} run '
result = None
ret_val = {}
# Test begins!
for yields, locks in zip(thread_yields, thread_locks):
key = 'Yields: {0} Locks: {1}'.format(yields, locks)
run_command = test_command.format(yields, locks)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | [
"def",
"threads",
"(",
")",
":",
"# Test data",
"thread_yields",
"=",
"[",
"100",
",",
"200",
",",
"500",
",",
"1000",
"]",
"thread_locks",
"=",
"[",
"2",
",",
"4",
",",
"8",
",",
"16",
"]",
"# Initializing the test variables",
"test_command",
"=",
"'sys... | This tests the performance of the processor's scheduler
CLI Example:
.. code-block:: bash
salt '*' sysbench.threads | [
"This",
"tests",
"the",
"performance",
"of",
"the",
"processor",
"s",
"scheduler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L88-L116 | train |
saltstack/salt | salt/modules/sysbench.py | mutex | def mutex():
'''
Tests the implementation of mutex
CLI Examples:
.. code-block:: bash
salt '*' sysbench.mutex
'''
# Test options and the values they take
# --mutex-num = [50,500,1000]
# --mutex-locks = [10000,25000,50000]
# --mutex-loops = [2500,5000,10000]
# Test data (Orthogonal test cases)
mutex_num = [50, 50, 50, 500, 500, 500, 1000, 1000, 1000]
locks = [10000, 25000, 50000, 10000, 25000, 50000, 10000, 25000, 50000]
mutex_locks = []
mutex_locks.extend(locks)
mutex_loops = [2500, 5000, 10000, 10000, 2500, 5000, 5000, 10000, 2500]
# Initializing the test variables
test_command = 'sysbench --num-threads=250 --test=mutex '
test_command += '--mutex-num={0} --mutex-locks={1} --mutex-loops={2} run '
result = None
ret_val = {}
# Test begins!
for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops):
key = 'Mutex: {0} Locks: {1} Loops: {2}'.format(num, locks, loops)
run_command = test_command.format(num, locks, loops)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | python | def mutex():
'''
Tests the implementation of mutex
CLI Examples:
.. code-block:: bash
salt '*' sysbench.mutex
'''
# Test options and the values they take
# --mutex-num = [50,500,1000]
# --mutex-locks = [10000,25000,50000]
# --mutex-loops = [2500,5000,10000]
# Test data (Orthogonal test cases)
mutex_num = [50, 50, 50, 500, 500, 500, 1000, 1000, 1000]
locks = [10000, 25000, 50000, 10000, 25000, 50000, 10000, 25000, 50000]
mutex_locks = []
mutex_locks.extend(locks)
mutex_loops = [2500, 5000, 10000, 10000, 2500, 5000, 5000, 10000, 2500]
# Initializing the test variables
test_command = 'sysbench --num-threads=250 --test=mutex '
test_command += '--mutex-num={0} --mutex-locks={1} --mutex-loops={2} run '
result = None
ret_val = {}
# Test begins!
for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops):
key = 'Mutex: {0} Locks: {1} Loops: {2}'.format(num, locks, loops)
run_command = test_command.format(num, locks, loops)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | [
"def",
"mutex",
"(",
")",
":",
"# Test options and the values they take",
"# --mutex-num = [50,500,1000]",
"# --mutex-locks = [10000,25000,50000]",
"# --mutex-loops = [2500,5000,10000]",
"# Test data (Orthogonal test cases)",
"mutex_num",
"=",
"[",
"50",
",",
"50",
",",
"50",
","... | Tests the implementation of mutex
CLI Examples:
.. code-block:: bash
salt '*' sysbench.mutex | [
"Tests",
"the",
"implementation",
"of",
"mutex"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L119-L155 | train |
saltstack/salt | salt/modules/sysbench.py | memory | def memory():
'''
This tests the memory for read and write operations.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.memory
'''
# test defaults
# --memory-block-size = 10M
# --memory-total-size = 1G
# We test memory read / write against global / local scope of memory
# Test data
memory_oper = ['read', 'write']
memory_scope = ['local', 'global']
# Initializing the test variables
test_command = 'sysbench --num-threads=64 --test=memory '
test_command += '--memory-oper={0} --memory-scope={1} '
test_command += '--memory-block-size=1K --memory-total-size=32G run '
result = None
ret_val = {}
# Test begins!
for oper in memory_oper:
for scope in memory_scope:
key = 'Operation: {0} Scope: {1}'.format(oper, scope)
run_command = test_command.format(oper, scope)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | python | def memory():
'''
This tests the memory for read and write operations.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.memory
'''
# test defaults
# --memory-block-size = 10M
# --memory-total-size = 1G
# We test memory read / write against global / local scope of memory
# Test data
memory_oper = ['read', 'write']
memory_scope = ['local', 'global']
# Initializing the test variables
test_command = 'sysbench --num-threads=64 --test=memory '
test_command += '--memory-oper={0} --memory-scope={1} '
test_command += '--memory-block-size=1K --memory-total-size=32G run '
result = None
ret_val = {}
# Test begins!
for oper in memory_oper:
for scope in memory_scope:
key = 'Operation: {0} Scope: {1}'.format(oper, scope)
run_command = test_command.format(oper, scope)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val | [
"def",
"memory",
"(",
")",
":",
"# test defaults",
"# --memory-block-size = 10M",
"# --memory-total-size = 1G",
"# We test memory read / write against global / local scope of memory",
"# Test data",
"memory_oper",
"=",
"[",
"'read'",
",",
"'write'",
"]",
"memory_scope",
"=",
"[... | This tests the memory for read and write operations.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.memory | [
"This",
"tests",
"the",
"memory",
"for",
"read",
"and",
"write",
"operations",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L158-L193 | train |
saltstack/salt | salt/modules/sysbench.py | fileio | def fileio():
'''
This tests for the file read and write operations
Various modes of operations are
* sequential write
* sequential rewrite
* sequential read
* random read
* random write
* random read and write
The test works with 32 files with each file being 1Gb in size
The test consumes a lot of time. Be patient!
CLI Examples:
.. code-block:: bash
salt '*' sysbench.fileio
'''
# Test data
test_modes = ['seqwr', 'seqrewr', 'seqrd', 'rndrd', 'rndwr', 'rndrw']
# Initializing the required variables
test_command = 'sysbench --num-threads=16 --test=fileio '
test_command += '--file-num=32 --file-total-size=1G --file-test-mode={0} '
result = None
ret_val = {}
# Test begins!
for mode in test_modes:
key = 'Mode: {0}'.format(mode)
# Prepare phase
run_command = (test_command + 'prepare').format(mode)
__salt__['cmd.run'](run_command)
# Test phase
run_command = (test_command + 'run').format(mode)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
# Clean up phase
run_command = (test_command + 'cleanup').format(mode)
__salt__['cmd.run'](run_command)
return ret_val | python | def fileio():
'''
This tests for the file read and write operations
Various modes of operations are
* sequential write
* sequential rewrite
* sequential read
* random read
* random write
* random read and write
The test works with 32 files with each file being 1Gb in size
The test consumes a lot of time. Be patient!
CLI Examples:
.. code-block:: bash
salt '*' sysbench.fileio
'''
# Test data
test_modes = ['seqwr', 'seqrewr', 'seqrd', 'rndrd', 'rndwr', 'rndrw']
# Initializing the required variables
test_command = 'sysbench --num-threads=16 --test=fileio '
test_command += '--file-num=32 --file-total-size=1G --file-test-mode={0} '
result = None
ret_val = {}
# Test begins!
for mode in test_modes:
key = 'Mode: {0}'.format(mode)
# Prepare phase
run_command = (test_command + 'prepare').format(mode)
__salt__['cmd.run'](run_command)
# Test phase
run_command = (test_command + 'run').format(mode)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
# Clean up phase
run_command = (test_command + 'cleanup').format(mode)
__salt__['cmd.run'](run_command)
return ret_val | [
"def",
"fileio",
"(",
")",
":",
"# Test data",
"test_modes",
"=",
"[",
"'seqwr'",
",",
"'seqrewr'",
",",
"'seqrd'",
",",
"'rndrd'",
",",
"'rndwr'",
",",
"'rndrw'",
"]",
"# Initializing the required variables",
"test_command",
"=",
"'sysbench --num-threads=16 --test=fi... | This tests for the file read and write operations
Various modes of operations are
* sequential write
* sequential rewrite
* sequential read
* random read
* random write
* random read and write
The test works with 32 files with each file being 1Gb in size
The test consumes a lot of time. Be patient!
CLI Examples:
.. code-block:: bash
salt '*' sysbench.fileio | [
"This",
"tests",
"for",
"the",
"file",
"read",
"and",
"write",
"operations",
"Various",
"modes",
"of",
"operations",
"are"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysbench.py#L196-L244 | train |
saltstack/salt | salt/modules/linux_lvm.py | version | def version():
'''
Return LVM version from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.version
'''
cmd = 'lvm version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split(': ')
return ret[1].strip() | python | def version():
'''
Return LVM version from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.version
'''
cmd = 'lvm version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split(': ')
return ret[1].strip() | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"'lvm version'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"ret",
"=",
"out",
"[",
"0",
"]",
".",
"split",
"(",
"': '",
")",
"return",
"ret",
"[",
"1"... | Return LVM version from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.version | [
"Return",
"LVM",
"version",
"from",
"lvm",
"version"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L32-L45 | train |
saltstack/salt | salt/modules/linux_lvm.py | fullversion | def fullversion():
'''
Return all version info from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.fullversion
'''
ret = {}
cmd = 'lvm version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.split(':')
ret[comps[0].strip()] = comps[1].strip()
return ret | python | def fullversion():
'''
Return all version info from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.fullversion
'''
ret = {}
cmd = 'lvm version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.split(':')
ret[comps[0].strip()] = comps[1].strip()
return ret | [
"def",
"fullversion",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'lvm version'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"out",
":",
"comps",
"=",
"line",
".",
"split"... | Return all version info from lvm version
CLI Example:
.. code-block:: bash
salt '*' lvm.fullversion | [
"Return",
"all",
"version",
"info",
"from",
"lvm",
"version"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L48-L64 | train |
saltstack/salt | salt/modules/linux_lvm.py | pvdisplay | def pvdisplay(pvname='', real=False, quiet=False):
'''
Return information about the physical volume(s)
pvname
physical device name
real
dereference any symlinks and report the real device
.. versionadded:: 2015.8.7
quiet
if the physical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.pvdisplay
salt '*' lvm.pvdisplay /dev/md0
'''
ret = {}
cmd = ['pvdisplay', '-c']
if pvname:
cmd.append(pvname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
if 'is a new physical volume' not in line:
comps = line.strip().split(':')
if real:
device = os.path.realpath(comps[0])
else:
device = comps[0]
ret[device] = {
'Physical Volume Device': comps[0],
'Volume Group Name': comps[1],
'Physical Volume Size (kB)': comps[2],
'Internal Physical Volume Number': comps[3],
'Physical Volume Status': comps[4],
'Physical Volume (not) Allocatable': comps[5],
'Current Logical Volumes Here': comps[6],
'Physical Extent Size (kB)': comps[7],
'Total Physical Extents': comps[8],
'Free Physical Extents': comps[9],
'Allocated Physical Extents': comps[10],
}
if real:
ret[device]['Real Physical Volume Device'] = device
return ret | python | def pvdisplay(pvname='', real=False, quiet=False):
'''
Return information about the physical volume(s)
pvname
physical device name
real
dereference any symlinks and report the real device
.. versionadded:: 2015.8.7
quiet
if the physical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.pvdisplay
salt '*' lvm.pvdisplay /dev/md0
'''
ret = {}
cmd = ['pvdisplay', '-c']
if pvname:
cmd.append(pvname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
if 'is a new physical volume' not in line:
comps = line.strip().split(':')
if real:
device = os.path.realpath(comps[0])
else:
device = comps[0]
ret[device] = {
'Physical Volume Device': comps[0],
'Volume Group Name': comps[1],
'Physical Volume Size (kB)': comps[2],
'Internal Physical Volume Number': comps[3],
'Physical Volume Status': comps[4],
'Physical Volume (not) Allocatable': comps[5],
'Current Logical Volumes Here': comps[6],
'Physical Extent Size (kB)': comps[7],
'Total Physical Extents': comps[8],
'Free Physical Extents': comps[9],
'Allocated Physical Extents': comps[10],
}
if real:
ret[device]['Real Physical Volume Device'] = device
return ret | [
"def",
"pvdisplay",
"(",
"pvname",
"=",
"''",
",",
"real",
"=",
"False",
",",
"quiet",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'pvdisplay'",
",",
"'-c'",
"]",
"if",
"pvname",
":",
"cmd",
".",
"append",
"(",
"pvname",
")",
... | Return information about the physical volume(s)
pvname
physical device name
real
dereference any symlinks and report the real device
.. versionadded:: 2015.8.7
quiet
if the physical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.pvdisplay
salt '*' lvm.pvdisplay /dev/md0 | [
"Return",
"information",
"about",
"the",
"physical",
"volume",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L67-L123 | train |
saltstack/salt | salt/modules/linux_lvm.py | vgdisplay | def vgdisplay(vgname='', quiet=False):
'''
Return information about the volume group(s)
vgname
volume group name
quiet
if the volume group is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.vgdisplay
salt '*' lvm.vgdisplay nova-volumes
'''
ret = {}
cmd = ['vgdisplay', '-c']
if vgname:
cmd.append(vgname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
comps = line.strip().split(':')
ret[comps[0]] = {
'Volume Group Name': comps[0],
'Volume Group Access': comps[1],
'Volume Group Status': comps[2],
'Internal Volume Group Number': comps[3],
'Maximum Logical Volumes': comps[4],
'Current Logical Volumes': comps[5],
'Open Logical Volumes': comps[6],
'Maximum Logical Volume Size': comps[7],
'Maximum Physical Volumes': comps[8],
'Current Physical Volumes': comps[9],
'Actual Physical Volumes': comps[10],
'Volume Group Size (kB)': comps[11],
'Physical Extent Size (kB)': comps[12],
'Total Physical Extents': comps[13],
'Allocated Physical Extents': comps[14],
'Free Physical Extents': comps[15],
'UUID': comps[16],
}
return ret | python | def vgdisplay(vgname='', quiet=False):
'''
Return information about the volume group(s)
vgname
volume group name
quiet
if the volume group is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.vgdisplay
salt '*' lvm.vgdisplay nova-volumes
'''
ret = {}
cmd = ['vgdisplay', '-c']
if vgname:
cmd.append(vgname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
comps = line.strip().split(':')
ret[comps[0]] = {
'Volume Group Name': comps[0],
'Volume Group Access': comps[1],
'Volume Group Status': comps[2],
'Internal Volume Group Number': comps[3],
'Maximum Logical Volumes': comps[4],
'Current Logical Volumes': comps[5],
'Open Logical Volumes': comps[6],
'Maximum Logical Volume Size': comps[7],
'Maximum Physical Volumes': comps[8],
'Current Physical Volumes': comps[9],
'Actual Physical Volumes': comps[10],
'Volume Group Size (kB)': comps[11],
'Physical Extent Size (kB)': comps[12],
'Total Physical Extents': comps[13],
'Allocated Physical Extents': comps[14],
'Free Physical Extents': comps[15],
'UUID': comps[16],
}
return ret | [
"def",
"vgdisplay",
"(",
"vgname",
"=",
"''",
",",
"quiet",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'vgdisplay'",
",",
"'-c'",
"]",
"if",
"vgname",
":",
"cmd",
".",
"append",
"(",
"vgname",
")",
"cmd_ret",
"=",
"__salt__",
... | Return information about the volume group(s)
vgname
volume group name
quiet
if the volume group is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.vgdisplay
salt '*' lvm.vgdisplay nova-volumes | [
"Return",
"information",
"about",
"the",
"volume",
"group",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L126-L175 | train |
saltstack/salt | salt/modules/linux_lvm.py | lvdisplay | def lvdisplay(lvname='', quiet=False):
'''
Return information about the logical volume(s)
lvname
logical device name
quiet
if the logical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvdisplay
salt '*' lvm.lvdisplay /dev/vg_myserver/root
'''
ret = {}
cmd = ['lvdisplay', '-c']
if lvname:
cmd.append(lvname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
comps = line.strip().split(':')
ret[comps[0]] = {
'Logical Volume Name': comps[0],
'Volume Group Name': comps[1],
'Logical Volume Access': comps[2],
'Logical Volume Status': comps[3],
'Internal Logical Volume Number': comps[4],
'Open Logical Volumes': comps[5],
'Logical Volume Size': comps[6],
'Current Logical Extents Associated': comps[7],
'Allocated Logical Extents': comps[8],
'Allocation Policy': comps[9],
'Read Ahead Sectors': comps[10],
'Major Device Number': comps[11],
'Minor Device Number': comps[12],
}
return ret | python | def lvdisplay(lvname='', quiet=False):
'''
Return information about the logical volume(s)
lvname
logical device name
quiet
if the logical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvdisplay
salt '*' lvm.lvdisplay /dev/vg_myserver/root
'''
ret = {}
cmd = ['lvdisplay', '-c']
if lvname:
cmd.append(lvname)
cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False,
ignore_retcode=quiet)
if cmd_ret['retcode'] != 0:
return {}
out = cmd_ret['stdout'].splitlines()
for line in out:
comps = line.strip().split(':')
ret[comps[0]] = {
'Logical Volume Name': comps[0],
'Volume Group Name': comps[1],
'Logical Volume Access': comps[2],
'Logical Volume Status': comps[3],
'Internal Logical Volume Number': comps[4],
'Open Logical Volumes': comps[5],
'Logical Volume Size': comps[6],
'Current Logical Extents Associated': comps[7],
'Allocated Logical Extents': comps[8],
'Allocation Policy': comps[9],
'Read Ahead Sectors': comps[10],
'Major Device Number': comps[11],
'Minor Device Number': comps[12],
}
return ret | [
"def",
"lvdisplay",
"(",
"lvname",
"=",
"''",
",",
"quiet",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'lvdisplay'",
",",
"'-c'",
"]",
"if",
"lvname",
":",
"cmd",
".",
"append",
"(",
"lvname",
")",
"cmd_ret",
"=",
"__salt__",
... | Return information about the logical volume(s)
lvname
logical device name
quiet
if the logical volume is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvdisplay
salt '*' lvm.lvdisplay /dev/vg_myserver/root | [
"Return",
"information",
"about",
"the",
"logical",
"volume",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L178-L223 | train |
saltstack/salt | salt/modules/linux_lvm.py | pvcreate | def pvcreate(devices, override=True, **kwargs):
'''
Set a physical device to be used as an LVM physical volume
override
Skip devices, if they are already LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2
salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s
'''
if not devices:
return 'Error: at least one device is required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['pvcreate', '-y']
for device in devices:
if not os.path.exists(device):
raise CommandExecutionError('{0} does not exist'.format(device))
if not pvdisplay(device, quiet=True):
cmd.append(device)
elif not override:
raise CommandExecutionError('Device "{0}" is already an LVM physical volume.'.format(device))
if not cmd[2:]:
# All specified devices are already LVM volumes
return True
valid = ('metadatasize', 'dataalignment', 'dataalignmentoffset',
'pvmetadatacopies', 'metadatacopies', 'metadataignore',
'restorefile', 'norestorefile', 'labelsector',
'setphysicalvolumesize')
no_parameter = ('force', 'norestorefile')
for var in kwargs:
if kwargs[var] and var in valid:
cmd.extend(['--{0}'.format(var), kwargs[var]])
elif kwargs[var] and var in no_parameter:
cmd.append('--{0}'.format(var))
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out.get('retcode'):
raise CommandExecutionError(out.get('stderr'))
# Verify pvcreate was successful
for device in devices:
if not pvdisplay(device):
raise CommandExecutionError('Device "{0}" was not affected.'.format(device))
return True | python | def pvcreate(devices, override=True, **kwargs):
'''
Set a physical device to be used as an LVM physical volume
override
Skip devices, if they are already LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2
salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s
'''
if not devices:
return 'Error: at least one device is required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['pvcreate', '-y']
for device in devices:
if not os.path.exists(device):
raise CommandExecutionError('{0} does not exist'.format(device))
if not pvdisplay(device, quiet=True):
cmd.append(device)
elif not override:
raise CommandExecutionError('Device "{0}" is already an LVM physical volume.'.format(device))
if not cmd[2:]:
# All specified devices are already LVM volumes
return True
valid = ('metadatasize', 'dataalignment', 'dataalignmentoffset',
'pvmetadatacopies', 'metadatacopies', 'metadataignore',
'restorefile', 'norestorefile', 'labelsector',
'setphysicalvolumesize')
no_parameter = ('force', 'norestorefile')
for var in kwargs:
if kwargs[var] and var in valid:
cmd.extend(['--{0}'.format(var), kwargs[var]])
elif kwargs[var] and var in no_parameter:
cmd.append('--{0}'.format(var))
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out.get('retcode'):
raise CommandExecutionError(out.get('stderr'))
# Verify pvcreate was successful
for device in devices:
if not pvdisplay(device):
raise CommandExecutionError('Device "{0}" was not affected.'.format(device))
return True | [
"def",
"pvcreate",
"(",
"devices",
",",
"override",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"devices",
":",
"return",
"'Error: at least one device is required'",
"if",
"isinstance",
"(",
"devices",
",",
"six",
".",
"string_types",
")",
"... | Set a physical device to be used as an LVM physical volume
override
Skip devices, if they are already LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2
salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s | [
"Set",
"a",
"physical",
"device",
"to",
"be",
"used",
"as",
"an",
"LVM",
"physical",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L226-L278 | train |
saltstack/salt | salt/modules/linux_lvm.py | pvremove | def pvremove(devices, override=True):
'''
Remove a physical device being used as an LVM physical volume
override
Skip devices, if they are already not used as LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2
'''
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['pvremove', '-y']
for device in devices:
if pvdisplay(device):
cmd.append(device)
elif not override:
raise CommandExecutionError('{0} is not a physical volume'.format(device))
if not cmd[2:]:
# Nothing to do
return True
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out.get('retcode'):
raise CommandExecutionError(out.get('stderr'))
# Verify pvcremove was successful
for device in devices:
if pvdisplay(device, quiet=True):
raise CommandExecutionError('Device "{0}" was not affected.'.format(device))
return True | python | def pvremove(devices, override=True):
'''
Remove a physical device being used as an LVM physical volume
override
Skip devices, if they are already not used as LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2
'''
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['pvremove', '-y']
for device in devices:
if pvdisplay(device):
cmd.append(device)
elif not override:
raise CommandExecutionError('{0} is not a physical volume'.format(device))
if not cmd[2:]:
# Nothing to do
return True
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out.get('retcode'):
raise CommandExecutionError(out.get('stderr'))
# Verify pvcremove was successful
for device in devices:
if pvdisplay(device, quiet=True):
raise CommandExecutionError('Device "{0}" was not affected.'.format(device))
return True | [
"def",
"pvremove",
"(",
"devices",
",",
"override",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"devices",
",",
"six",
".",
"string_types",
")",
":",
"devices",
"=",
"devices",
".",
"split",
"(",
"','",
")",
"cmd",
"=",
"[",
"'pvremove'",
",",
"'... | Remove a physical device being used as an LVM physical volume
override
Skip devices, if they are already not used as LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2 | [
"Remove",
"a",
"physical",
"device",
"being",
"used",
"as",
"an",
"LVM",
"physical",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L281-L317 | train |
saltstack/salt | salt/modules/linux_lvm.py | vgcreate | def vgcreate(vgname, devices, **kwargs):
'''
Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
'''
if not vgname or not devices:
return 'Error: vgname and device(s) are both required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['vgcreate', vgname]
for device in devices:
cmd.append(device)
valid = ('clustered', 'maxlogicalvolumes', 'maxphysicalvolumes',
'vgmetadatacopies', 'metadatacopies', 'physicalextentsize')
for var in kwargs:
if kwargs[var] and var in valid:
cmd.append('--{0}'.format(var))
cmd.append(kwargs[var])
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
vgdata = vgdisplay(vgname)
vgdata['Output from vgcreate'] = out[0].strip()
return vgdata | python | def vgcreate(vgname, devices, **kwargs):
'''
Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
'''
if not vgname or not devices:
return 'Error: vgname and device(s) are both required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['vgcreate', vgname]
for device in devices:
cmd.append(device)
valid = ('clustered', 'maxlogicalvolumes', 'maxphysicalvolumes',
'vgmetadatacopies', 'metadatacopies', 'physicalextentsize')
for var in kwargs:
if kwargs[var] and var in valid:
cmd.append('--{0}'.format(var))
cmd.append(kwargs[var])
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
vgdata = vgdisplay(vgname)
vgdata['Output from vgcreate'] = out[0].strip()
return vgdata | [
"def",
"vgcreate",
"(",
"vgname",
",",
"devices",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"vgname",
"or",
"not",
"devices",
":",
"return",
"'Error: vgname and device(s) are both required'",
"if",
"isinstance",
"(",
"devices",
",",
"six",
".",
"string_t... | Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y | [
"Create",
"an",
"LVM",
"volume",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L320-L348 | train |
saltstack/salt | salt/modules/linux_lvm.py | vgextend | def vgextend(vgname, devices):
'''
Add physical volumes to an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgextend my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgextend my_vg /dev/sdb1
'''
if not vgname or not devices:
return 'Error: vgname and device(s) are both required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['vgextend', vgname]
for device in devices:
cmd.append(device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
vgdata = {'Output from vgextend': out[0].strip()}
return vgdata | python | def vgextend(vgname, devices):
'''
Add physical volumes to an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgextend my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgextend my_vg /dev/sdb1
'''
if not vgname or not devices:
return 'Error: vgname and device(s) are both required'
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['vgextend', vgname]
for device in devices:
cmd.append(device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
vgdata = {'Output from vgextend': out[0].strip()}
return vgdata | [
"def",
"vgextend",
"(",
"vgname",
",",
"devices",
")",
":",
"if",
"not",
"vgname",
"or",
"not",
"devices",
":",
"return",
"'Error: vgname and device(s) are both required'",
"if",
"isinstance",
"(",
"devices",
",",
"six",
".",
"string_types",
")",
":",
"devices",... | Add physical volumes to an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgextend my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgextend my_vg /dev/sdb1 | [
"Add",
"physical",
"volumes",
"to",
"an",
"LVM",
"volume",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L351-L372 | train |
saltstack/salt | salt/modules/linux_lvm.py | lvcreate | def lvcreate(lvname,
vgname,
size=None,
extents=None,
snapshot=None,
pv=None,
thinvolume=False,
thinpool=False,
force=False,
**kwargs):
'''
Create a new logical volume, with option for which physical volume to be used
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_volume_name vg_name size=10G
salt '*' lvm.lvcreate new_volume_name vg_name extents=100 pv=/dev/sdb
salt '*' lvm.lvcreate new_snapshot vg_name snapshot=volume_name size=3G
.. versionadded:: to_complete
Support for thin pools and thin volumes
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_thinpool_name vg_name size=20G thinpool=True
salt '*' lvm.lvcreate new_thinvolume_name vg_name/thinpool_name size=10G thinvolume=True
'''
if size and extents:
return 'Error: Please specify only one of size or extents'
if thinvolume and thinpool:
return 'Error: Please set only one of thinvolume or thinpool to True'
valid = ('activate', 'chunksize', 'contiguous', 'discards', 'stripes',
'stripesize', 'minor', 'persistent', 'mirrors', 'noudevsync',
'monitor', 'ignoremonitoring', 'permission', 'poolmetadatasize',
'readahead', 'regionsize', 'type',
'virtualsize', 'zero')
no_parameter = ('noudevsync', 'ignoremonitoring', 'thin', )
extra_arguments = []
if kwargs:
for k, v in six.iteritems(kwargs):
if k in no_parameter:
extra_arguments.append('--{0}'.format(k))
elif k in valid:
extra_arguments.extend(['--{0}'.format(k), '{0}'.format(v)])
cmd = [salt.utils.path.which('lvcreate')]
if thinvolume:
cmd.extend(['--thin', '-n', lvname])
elif thinpool:
cmd.extend(['--thinpool', lvname])
else:
cmd.extend(['-n', lvname])
if snapshot:
cmd.extend(['-s', '{0}/{1}'.format(vgname, snapshot)])
else:
cmd.append(vgname)
if size and thinvolume:
cmd.extend(['-V', '{0}'.format(size)])
elif extents and thinvolume:
return 'Error: Thin volume size cannot be specified as extents'
elif size:
cmd.extend(['-L', '{0}'.format(size)])
elif extents:
cmd.extend(['-l', '{0}'.format(extents)])
else:
return 'Error: Either size or extents must be specified'
if pv:
cmd.append(pv)
if extra_arguments:
cmd.extend(extra_arguments)
if force:
cmd.append('--yes')
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
lvdev = '/dev/{0}/{1}'.format(vgname, lvname)
lvdata = lvdisplay(lvdev)
lvdata['Output from lvcreate'] = out[0].strip()
return lvdata | python | def lvcreate(lvname,
vgname,
size=None,
extents=None,
snapshot=None,
pv=None,
thinvolume=False,
thinpool=False,
force=False,
**kwargs):
'''
Create a new logical volume, with option for which physical volume to be used
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_volume_name vg_name size=10G
salt '*' lvm.lvcreate new_volume_name vg_name extents=100 pv=/dev/sdb
salt '*' lvm.lvcreate new_snapshot vg_name snapshot=volume_name size=3G
.. versionadded:: to_complete
Support for thin pools and thin volumes
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_thinpool_name vg_name size=20G thinpool=True
salt '*' lvm.lvcreate new_thinvolume_name vg_name/thinpool_name size=10G thinvolume=True
'''
if size and extents:
return 'Error: Please specify only one of size or extents'
if thinvolume and thinpool:
return 'Error: Please set only one of thinvolume or thinpool to True'
valid = ('activate', 'chunksize', 'contiguous', 'discards', 'stripes',
'stripesize', 'minor', 'persistent', 'mirrors', 'noudevsync',
'monitor', 'ignoremonitoring', 'permission', 'poolmetadatasize',
'readahead', 'regionsize', 'type',
'virtualsize', 'zero')
no_parameter = ('noudevsync', 'ignoremonitoring', 'thin', )
extra_arguments = []
if kwargs:
for k, v in six.iteritems(kwargs):
if k in no_parameter:
extra_arguments.append('--{0}'.format(k))
elif k in valid:
extra_arguments.extend(['--{0}'.format(k), '{0}'.format(v)])
cmd = [salt.utils.path.which('lvcreate')]
if thinvolume:
cmd.extend(['--thin', '-n', lvname])
elif thinpool:
cmd.extend(['--thinpool', lvname])
else:
cmd.extend(['-n', lvname])
if snapshot:
cmd.extend(['-s', '{0}/{1}'.format(vgname, snapshot)])
else:
cmd.append(vgname)
if size and thinvolume:
cmd.extend(['-V', '{0}'.format(size)])
elif extents and thinvolume:
return 'Error: Thin volume size cannot be specified as extents'
elif size:
cmd.extend(['-L', '{0}'.format(size)])
elif extents:
cmd.extend(['-l', '{0}'.format(extents)])
else:
return 'Error: Either size or extents must be specified'
if pv:
cmd.append(pv)
if extra_arguments:
cmd.extend(extra_arguments)
if force:
cmd.append('--yes')
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
lvdev = '/dev/{0}/{1}'.format(vgname, lvname)
lvdata = lvdisplay(lvdev)
lvdata['Output from lvcreate'] = out[0].strip()
return lvdata | [
"def",
"lvcreate",
"(",
"lvname",
",",
"vgname",
",",
"size",
"=",
"None",
",",
"extents",
"=",
"None",
",",
"snapshot",
"=",
"None",
",",
"pv",
"=",
"None",
",",
"thinvolume",
"=",
"False",
",",
"thinpool",
"=",
"False",
",",
"force",
"=",
"False",
... | Create a new logical volume, with option for which physical volume to be used
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_volume_name vg_name size=10G
salt '*' lvm.lvcreate new_volume_name vg_name extents=100 pv=/dev/sdb
salt '*' lvm.lvcreate new_snapshot vg_name snapshot=volume_name size=3G
.. versionadded:: to_complete
Support for thin pools and thin volumes
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvcreate new_thinpool_name vg_name size=20G thinpool=True
salt '*' lvm.lvcreate new_thinvolume_name vg_name/thinpool_name size=10G thinvolume=True | [
"Create",
"a",
"new",
"logical",
"volume",
"with",
"option",
"for",
"which",
"physical",
"volume",
"to",
"be",
"used"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L375-L465 | train |
saltstack/salt | salt/modules/linux_lvm.py | vgremove | def vgremove(vgname):
'''
Remove an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgremove vgname
salt mymachine lvm.vgremove vgname force=True
'''
cmd = ['vgremove', '-f', vgname]
out = __salt__['cmd.run'](cmd, python_shell=False)
return out.strip() | python | def vgremove(vgname):
'''
Remove an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgremove vgname
salt mymachine lvm.vgremove vgname force=True
'''
cmd = ['vgremove', '-f', vgname]
out = __salt__['cmd.run'](cmd, python_shell=False)
return out.strip() | [
"def",
"vgremove",
"(",
"vgname",
")",
":",
"cmd",
"=",
"[",
"'vgremove'",
",",
"'-f'",
",",
"vgname",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"return",
"out",
".",
"strip",
"(",
")"
] | Remove an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgremove vgname
salt mymachine lvm.vgremove vgname force=True | [
"Remove",
"an",
"LVM",
"volume",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L468-L481 | train |
saltstack/salt | salt/modules/linux_lvm.py | lvremove | def lvremove(lvname, vgname):
'''
Remove a given existing logical volume from a named existing volume group
CLI Example:
.. code-block:: bash
salt '*' lvm.lvremove lvname vgname force=True
'''
cmd = ['lvremove', '-f', '{0}/{1}'.format(vgname, lvname)]
out = __salt__['cmd.run'](cmd, python_shell=False)
return out.strip() | python | def lvremove(lvname, vgname):
'''
Remove a given existing logical volume from a named existing volume group
CLI Example:
.. code-block:: bash
salt '*' lvm.lvremove lvname vgname force=True
'''
cmd = ['lvremove', '-f', '{0}/{1}'.format(vgname, lvname)]
out = __salt__['cmd.run'](cmd, python_shell=False)
return out.strip() | [
"def",
"lvremove",
"(",
"lvname",
",",
"vgname",
")",
":",
"cmd",
"=",
"[",
"'lvremove'",
",",
"'-f'",
",",
"'{0}/{1}'",
".",
"format",
"(",
"vgname",
",",
"lvname",
")",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_sh... | Remove a given existing logical volume from a named existing volume group
CLI Example:
.. code-block:: bash
salt '*' lvm.lvremove lvname vgname force=True | [
"Remove",
"a",
"given",
"existing",
"logical",
"volume",
"from",
"a",
"named",
"existing",
"volume",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L484-L496 | train |
saltstack/salt | salt/modules/linux_lvm.py | lvresize | def lvresize(size=None, lvpath=None, extents=None):
'''
Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE
'''
if size and extents:
log.error('Error: Please specify only one of size or extents')
return {}
cmd = ['lvresize']
if size:
cmd.extend(['-L', '{0}'.format(size)])
elif extents:
cmd.extend(['-l', '{0}'.format(extents)])
else:
log.error('Error: Either size or extents must be specified')
return {}
cmd.append(lvpath)
cmd_ret = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return {'Output from lvresize': cmd_ret[0].strip()} | python | def lvresize(size=None, lvpath=None, extents=None):
'''
Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE
'''
if size and extents:
log.error('Error: Please specify only one of size or extents')
return {}
cmd = ['lvresize']
if size:
cmd.extend(['-L', '{0}'.format(size)])
elif extents:
cmd.extend(['-l', '{0}'.format(extents)])
else:
log.error('Error: Either size or extents must be specified')
return {}
cmd.append(lvpath)
cmd_ret = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return {'Output from lvresize': cmd_ret[0].strip()} | [
"def",
"lvresize",
"(",
"size",
"=",
"None",
",",
"lvpath",
"=",
"None",
",",
"extents",
"=",
"None",
")",
":",
"if",
"size",
"and",
"extents",
":",
"log",
".",
"error",
"(",
"'Error: Please specify only one of size or extents'",
")",
"return",
"{",
"}",
"... | Return information about the logical volume(s)
CLI Examples:
.. code-block:: bash
salt '*' lvm.lvresize +12M /dev/mapper/vg1-test
salt '*' lvm.lvresize lvpath=/dev/mapper/vg1-test extents=+100%FREE | [
"Return",
"information",
"about",
"the",
"logical",
"volume",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L499-L528 | train |
saltstack/salt | salt/modules/azurearm_resource.py | resource_groups_list | def resource_groups_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all resource groups within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_groups_list
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
groups = __utils__['azurearm.paged_object_to_list'](resconn.resource_groups.list())
for group in groups:
result[group['name']] = group
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def resource_groups_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all resource groups within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_groups_list
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
groups = __utils__['azurearm.paged_object_to_list'](resconn.resource_groups.list())
for group in groups:
result[group['name']] = group
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"resource_groups_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"groups",
"=",
"__utils__",
"[",
"'azu... | .. versionadded:: 2019.2.0
List all resource groups within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_groups_list | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L81-L105 | train |
saltstack/salt | salt/modules/azurearm_resource.py | resource_group_check_existence | def resource_group_check_existence(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Check for the existence of a named resource group in the current subscription.
:param name: The resource group name to check.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_check_existence testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
result = resconn.resource_groups.check_existence(name)
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def resource_group_check_existence(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Check for the existence of a named resource group in the current subscription.
:param name: The resource group name to check.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_check_existence testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
result = resconn.resource_groups.check_existence(name)
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"resource_group_check_existence",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"result",
"=",
"re... | .. versionadded:: 2019.2.0
Check for the existence of a named resource group in the current subscription.
:param name: The resource group name to check.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_check_existence testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L108-L131 | train |
saltstack/salt | salt/modules/azurearm_resource.py | resource_group_get | def resource_group_get(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a dictionary representing a resource group's properties.
:param name: The resource group name to get.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_get testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
group = resconn.resource_groups.get(name)
result = group.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def resource_group_get(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a dictionary representing a resource group's properties.
:param name: The resource group name to get.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_get testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
group = resconn.resource_groups.get(name)
result = group.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"resource_group_get",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"group",
"=",
"resconn",
... | .. versionadded:: 2019.2.0
Get a dictionary representing a resource group's properties.
:param name: The resource group name to get.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_get testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L134-L159 | train |
saltstack/salt | salt/modules/azurearm_resource.py | resource_group_create_or_update | def resource_group_create_or_update(name, location, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update a resource group in a given location.
:param name: The name of the resource group to create or update.
:param location: The location of the resource group. This value
is not able to be updated once the resource group is created.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_create_or_update testgroup westus
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
resource_group_params = {
'location': location,
'managed_by': kwargs.get('managed_by'),
'tags': kwargs.get('tags'),
}
try:
group = resconn.resource_groups.create_or_update(name, resource_group_params)
result = group.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def resource_group_create_or_update(name, location, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update a resource group in a given location.
:param name: The name of the resource group to create or update.
:param location: The location of the resource group. This value
is not able to be updated once the resource group is created.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_create_or_update testgroup westus
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
resource_group_params = {
'location': location,
'managed_by': kwargs.get('managed_by'),
'tags': kwargs.get('tags'),
}
try:
group = resconn.resource_groups.create_or_update(name, resource_group_params)
result = group.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"resource_group_create_or_update",
"(",
"name",
",",
"location",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"result",
"=",
"{",
"}",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*"... | .. versionadded:: 2019.2.0
Create or update a resource group in a given location.
:param name: The name of the resource group to create or update.
:param location: The location of the resource group. This value
is not able to be updated once the resource group is created.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_create_or_update testgroup westus | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L162-L194 | train |
saltstack/salt | salt/modules/azurearm_resource.py | resource_group_delete | def resource_group_delete(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a resource group from the subscription.
:param name: The resource group name to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_delete testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
group = resconn.resource_groups.delete(name)
group.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def resource_group_delete(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a resource group from the subscription.
:param name: The resource group name to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_delete testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
group = resconn.resource_groups.delete(name)
group.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"resource_group_delete",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"group",
"=",
"resconn",
... | .. versionadded:: 2019.2.0
Delete a resource group from the subscription.
:param name: The resource group name to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.resource_group_delete testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L197-L221 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_operation_get | def deployment_operation_get(operation, deployment, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a deployment operation within a deployment.
:param operation: The operation ID of the operation within the deployment.
:param deployment: The name of the deployment containing the operation.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operation_get XXXXX testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
operation = resconn.deployment_operations.get(
resource_group_name=resource_group,
deployment_name=deployment,
operation_id=operation
)
result = operation.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def deployment_operation_get(operation, deployment, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a deployment operation within a deployment.
:param operation: The operation ID of the operation within the deployment.
:param deployment: The name of the deployment containing the operation.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operation_get XXXXX testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
operation = resconn.deployment_operations.get(
resource_group_name=resource_group,
deployment_name=deployment,
operation_id=operation
)
result = operation.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"deployment_operation_get",
"(",
"operation",
",",
"deployment",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"op... | .. versionadded:: 2019.2.0
Get a deployment operation within a deployment.
:param operation: The operation ID of the operation within the deployment.
:param deployment: The name of the deployment containing the operation.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operation_get XXXXX testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L224-L257 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_operations_list | def deployment_operations_list(name, resource_group, result_limit=10, **kwargs):
'''
.. versionadded:: 2019.2.0
List all deployment operations within a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
:param result_limit: (Default: 10) The limit on the list of deployment
operations.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operations_list testdeploy testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
operations = __utils__['azurearm.paged_object_to_list'](
resconn.deployment_operations.list(
resource_group_name=resource_group,
deployment_name=name,
top=result_limit
)
)
for oper in operations:
result[oper['operation_id']] = oper
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def deployment_operations_list(name, resource_group, result_limit=10, **kwargs):
'''
.. versionadded:: 2019.2.0
List all deployment operations within a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
:param result_limit: (Default: 10) The limit on the list of deployment
operations.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operations_list testdeploy testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
operations = __utils__['azurearm.paged_object_to_list'](
resconn.deployment_operations.list(
resource_group_name=resource_group,
deployment_name=name,
top=result_limit
)
)
for oper in operations:
result[oper['operation_id']] = oper
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"deployment_operations_list",
"(",
"name",
",",
"resource_group",
",",
"result_limit",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
... | .. versionadded:: 2019.2.0
List all deployment operations within a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
:param result_limit: (Default: 10) The limit on the list of deployment
operations.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_operations_list testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L260-L298 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_delete | def deployment_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a deployment.
:param name: The name of the deployment to delete.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_delete testdeploy testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.delete(
deployment_name=name,
resource_group_name=resource_group
)
deploy.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def deployment_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a deployment.
:param name: The name of the deployment to delete.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_delete testdeploy testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.delete(
deployment_name=name,
resource_group_name=resource_group
)
deploy.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"deployment_delete",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deploy"... | .. versionadded:: 2019.2.0
Delete a deployment.
:param name: The name of the deployment to delete.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_delete testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L301-L331 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_check_existence | def deployment_check_existence(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_check_existence testdeploy testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
result = resconn.deployments.check_existence(
deployment_name=name,
resource_group_name=resource_group
)
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def deployment_check_existence(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_check_existence testdeploy testgroup
'''
result = False
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
result = resconn.deployments.check_existence(
deployment_name=name,
resource_group_name=resource_group
)
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"deployment_check_existence",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
... | .. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_check_existence testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L334-L362 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_get | def deployment_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_get testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.get(
deployment_name=name,
resource_group_name=resource_group
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def deployment_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_get testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.get(
deployment_name=name,
resource_group_name=resource_group
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"deployment_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deploy",
"=",
"resconn",
".",
"d... | .. versionadded:: 2019.2.0
Get details about a specific deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_get testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L473-L502 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_cancel | def deployment_cancel(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Cancel a deployment if in 'Accepted' or 'Running' state.
:param name: The name of the deployment to cancel.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_cancel testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
resconn.deployments.cancel(
deployment_name=name,
resource_group_name=resource_group
)
result = {'result': True}
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {
'error': str(exc),
'result': False
}
return result | python | def deployment_cancel(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Cancel a deployment if in 'Accepted' or 'Running' state.
:param name: The name of the deployment to cancel.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_cancel testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
resconn.deployments.cancel(
deployment_name=name,
resource_group_name=resource_group
)
result = {'result': True}
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {
'error': str(exc),
'result': False
}
return result | [
"def",
"deployment_cancel",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"resconn",
".",
"deployments",
"... | .. versionadded:: 2019.2.0
Cancel a deployment if in 'Accepted' or 'Running' state.
:param name: The name of the deployment to cancel.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_cancel testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L505-L537 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_validate | def deployment_validate(name, resource_group, deploy_mode=None,
debug_setting=None, deploy_params=None,
parameters_link=None, deploy_template=None,
template_link=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Validates whether the specified template is syntactically correct
and will be accepted by Azure Resource Manager.
:param name: The name of the deployment to validate.
:param resource_group: The resource group name assigned to the
deployment.
:param deploy_mode: The mode that is used to deploy resources. This value can be either
'incremental' or 'complete'. In Incremental mode, resources are deployed without deleting
existing resources that are not included in the template. In Complete mode, resources
are deployed and existing resources in the resource group that are not included in
the template are deleted. Be careful when using Complete mode as you may
unintentionally delete resources.
:param debug_setting: The debug setting of the deployment. The permitted values are 'none',
'requestContent', 'responseContent', or 'requestContent,responseContent'. By logging
information about the request or response, you could potentially expose sensitive data
that is retrieved through the deployment operations.
:param deploy_params: JSON string containing name and value pairs that define the deployment
parameters for the template. You use this element when you want to provide the parameter
values directly in the request rather than link to an existing parameter file. Use either
the parameters_link property or the deploy_params property, but not both.
:param parameters_link: The URI of a parameters file. You use this element to link to an existing
parameters file. Use either the parameters_link property or the deploy_params property, but not both.
:param deploy_template: JSON string of template content. You use this element when you want to pass
the template syntax directly in the request rather than link to an existing template. Use either
the template_link property or the deploy_template property, but not both.
:param template_link: The URI of the template. Use either the template_link property or the
deploy_template property, but not both.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_validate testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
prop_kwargs = {'mode': deploy_mode}
prop_kwargs['debug_setting'] = {'detail_level': debug_setting}
if deploy_params:
prop_kwargs['parameters'] = deploy_params
else:
if isinstance(parameters_link, dict):
prop_kwargs['parameters_link'] = parameters_link
else:
prop_kwargs['parameters_link'] = {'uri': parameters_link}
if deploy_template:
prop_kwargs['template'] = deploy_template
else:
if isinstance(template_link, dict):
prop_kwargs['template_link'] = template_link
else:
prop_kwargs['template_link'] = {'uri': template_link}
deploy_kwargs = kwargs.copy()
deploy_kwargs.update(prop_kwargs)
try:
deploy_model = __utils__['azurearm.create_object_model'](
'resource',
'DeploymentProperties',
**deploy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
local_validation = deploy_model.validate()
if local_validation:
raise local_validation[0]
deploy = resconn.deployments.validate(
deployment_name=name,
resource_group_name=resource_group,
properties=deploy_model
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | python | def deployment_validate(name, resource_group, deploy_mode=None,
debug_setting=None, deploy_params=None,
parameters_link=None, deploy_template=None,
template_link=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Validates whether the specified template is syntactically correct
and will be accepted by Azure Resource Manager.
:param name: The name of the deployment to validate.
:param resource_group: The resource group name assigned to the
deployment.
:param deploy_mode: The mode that is used to deploy resources. This value can be either
'incremental' or 'complete'. In Incremental mode, resources are deployed without deleting
existing resources that are not included in the template. In Complete mode, resources
are deployed and existing resources in the resource group that are not included in
the template are deleted. Be careful when using Complete mode as you may
unintentionally delete resources.
:param debug_setting: The debug setting of the deployment. The permitted values are 'none',
'requestContent', 'responseContent', or 'requestContent,responseContent'. By logging
information about the request or response, you could potentially expose sensitive data
that is retrieved through the deployment operations.
:param deploy_params: JSON string containing name and value pairs that define the deployment
parameters for the template. You use this element when you want to provide the parameter
values directly in the request rather than link to an existing parameter file. Use either
the parameters_link property or the deploy_params property, but not both.
:param parameters_link: The URI of a parameters file. You use this element to link to an existing
parameters file. Use either the parameters_link property or the deploy_params property, but not both.
:param deploy_template: JSON string of template content. You use this element when you want to pass
the template syntax directly in the request rather than link to an existing template. Use either
the template_link property or the deploy_template property, but not both.
:param template_link: The URI of the template. Use either the template_link property or the
deploy_template property, but not both.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_validate testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
prop_kwargs = {'mode': deploy_mode}
prop_kwargs['debug_setting'] = {'detail_level': debug_setting}
if deploy_params:
prop_kwargs['parameters'] = deploy_params
else:
if isinstance(parameters_link, dict):
prop_kwargs['parameters_link'] = parameters_link
else:
prop_kwargs['parameters_link'] = {'uri': parameters_link}
if deploy_template:
prop_kwargs['template'] = deploy_template
else:
if isinstance(template_link, dict):
prop_kwargs['template_link'] = template_link
else:
prop_kwargs['template_link'] = {'uri': template_link}
deploy_kwargs = kwargs.copy()
deploy_kwargs.update(prop_kwargs)
try:
deploy_model = __utils__['azurearm.create_object_model'](
'resource',
'DeploymentProperties',
**deploy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
local_validation = deploy_model.validate()
if local_validation:
raise local_validation[0]
deploy = resconn.deployments.validate(
deployment_name=name,
resource_group_name=resource_group,
properties=deploy_model
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | [
"def",
"deployment_validate",
"(",
"name",
",",
"resource_group",
",",
"deploy_mode",
"=",
"None",
",",
"debug_setting",
"=",
"None",
",",
"deploy_params",
"=",
"None",
",",
"parameters_link",
"=",
"None",
",",
"deploy_template",
"=",
"None",
",",
"template_link... | .. versionadded:: 2019.2.0
Validates whether the specified template is syntactically correct
and will be accepted by Azure Resource Manager.
:param name: The name of the deployment to validate.
:param resource_group: The resource group name assigned to the
deployment.
:param deploy_mode: The mode that is used to deploy resources. This value can be either
'incremental' or 'complete'. In Incremental mode, resources are deployed without deleting
existing resources that are not included in the template. In Complete mode, resources
are deployed and existing resources in the resource group that are not included in
the template are deleted. Be careful when using Complete mode as you may
unintentionally delete resources.
:param debug_setting: The debug setting of the deployment. The permitted values are 'none',
'requestContent', 'responseContent', or 'requestContent,responseContent'. By logging
information about the request or response, you could potentially expose sensitive data
that is retrieved through the deployment operations.
:param deploy_params: JSON string containing name and value pairs that define the deployment
parameters for the template. You use this element when you want to provide the parameter
values directly in the request rather than link to an existing parameter file. Use either
the parameters_link property or the deploy_params property, but not both.
:param parameters_link: The URI of a parameters file. You use this element to link to an existing
parameters file. Use either the parameters_link property or the deploy_params property, but not both.
:param deploy_template: JSON string of template content. You use this element when you want to pass
the template syntax directly in the request rather than link to an existing template. Use either
the template_link property or the deploy_template property, but not both.
:param template_link: The URI of the template. Use either the template_link property or the
deploy_template property, but not both.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_validate testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L540-L640 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployment_export_template | def deployment_export_template(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Exports the template used for the specified deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_export_template testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.export_template(
deployment_name=name,
resource_group_name=resource_group
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def deployment_export_template(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Exports the template used for the specified deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_export_template testdeploy testgroup
'''
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deploy = resconn.deployments.export_template(
deployment_name=name,
resource_group_name=resource_group
)
result = deploy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"deployment_export_template",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deploy",
"=",
"resconn",... | .. versionadded:: 2019.2.0
Exports the template used for the specified deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_export_template testdeploy testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L643-L672 | train |
saltstack/salt | salt/modules/azurearm_resource.py | deployments_list | def deployments_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all deployments within a resource group.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployments_list testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deployments = __utils__['azurearm.paged_object_to_list'](
resconn.deployments.list_by_resource_group(
resource_group_name=resource_group
)
)
for deploy in deployments:
result[deploy['name']] = deploy
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def deployments_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all deployments within a resource group.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployments_list testgroup
'''
result = {}
resconn = __utils__['azurearm.get_client']('resource', **kwargs)
try:
deployments = __utils__['azurearm.paged_object_to_list'](
resconn.deployments.list_by_resource_group(
resource_group_name=resource_group
)
)
for deploy in deployments:
result[deploy['name']] = deploy
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"deployments_list",
"(",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deployments",
"=",
... | .. versionadded:: 2019.2.0
List all deployments within a resource group.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployments_list testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L675-L703 | train |
saltstack/salt | salt/modules/azurearm_resource.py | subscriptions_list_locations | def subscriptions_list_locations(subscription_id=None, **kwargs):
'''
.. versionadded:: 2019.2.0
List all locations for a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list_locations XXXXXXXX
'''
result = {}
if not subscription_id:
subscription_id = kwargs.get('subscription_id')
elif not kwargs.get('subscription_id'):
kwargs['subscription_id'] = subscription_id
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
locations = __utils__['azurearm.paged_object_to_list'](
subconn.subscriptions.list_locations(
subscription_id=kwargs['subscription_id']
)
)
for loc in locations:
result[loc['name']] = loc
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def subscriptions_list_locations(subscription_id=None, **kwargs):
'''
.. versionadded:: 2019.2.0
List all locations for a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list_locations XXXXXXXX
'''
result = {}
if not subscription_id:
subscription_id = kwargs.get('subscription_id')
elif not kwargs.get('subscription_id'):
kwargs['subscription_id'] = subscription_id
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
locations = __utils__['azurearm.paged_object_to_list'](
subconn.subscriptions.list_locations(
subscription_id=kwargs['subscription_id']
)
)
for loc in locations:
result[loc['name']] = loc
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"subscriptions_list_locations",
"(",
"subscription_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"if",
"not",
"subscription_id",
":",
"subscription_id",
"=",
"kwargs",
".",
"get",
"(",
"'subscription_id'",
")",
"elif",
... | .. versionadded:: 2019.2.0
List all locations for a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list_locations XXXXXXXX | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L706-L742 | train |
saltstack/salt | salt/modules/azurearm_resource.py | subscription_get | def subscription_get(subscription_id=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscription_get XXXXXXXX
'''
result = {}
if not subscription_id:
subscription_id = kwargs.get('subscription_id')
elif not kwargs.get('subscription_id'):
kwargs['subscription_id'] = subscription_id
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
subscription = subconn.subscriptions.get(
subscription_id=kwargs.get('subscription_id')
)
result = subscription.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def subscription_get(subscription_id=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscription_get XXXXXXXX
'''
result = {}
if not subscription_id:
subscription_id = kwargs.get('subscription_id')
elif not kwargs.get('subscription_id'):
kwargs['subscription_id'] = subscription_id
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
subscription = subconn.subscriptions.get(
subscription_id=kwargs.get('subscription_id')
)
result = subscription.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"subscription_get",
"(",
"subscription_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"if",
"not",
"subscription_id",
":",
"subscription_id",
"=",
"kwargs",
".",
"get",
"(",
"'subscription_id'",
")",
"elif",
"not",
"kw... | .. versionadded:: 2019.2.0
Get details about a subscription.
:param subscription_id: The ID of the subscription to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscription_get XXXXXXXX | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L745-L778 | train |
saltstack/salt | salt/modules/azurearm_resource.py | subscriptions_list | def subscriptions_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all subscriptions for a tenant.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list
'''
result = {}
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
subs = __utils__['azurearm.paged_object_to_list'](subconn.subscriptions.list())
for sub in subs:
result[sub['subscription_id']] = sub
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def subscriptions_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all subscriptions for a tenant.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list
'''
result = {}
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
subs = __utils__['azurearm.paged_object_to_list'](subconn.subscriptions.list())
for sub in subs:
result[sub['subscription_id']] = sub
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"subscriptions_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"subconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'subscription'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"subs",
"=",
"__utils__",
"[",
"'azu... | .. versionadded:: 2019.2.0
List all subscriptions for a tenant.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.subscriptions_list | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L781-L805 | train |
saltstack/salt | salt/modules/azurearm_resource.py | tenants_list | def tenants_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all tenants for your account.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.tenants_list
'''
result = {}
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
tenants = __utils__['azurearm.paged_object_to_list'](subconn.tenants.list())
for tenant in tenants:
result[tenant['tenant_id']] = tenant
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def tenants_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all tenants for your account.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.tenants_list
'''
result = {}
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
tenants = __utils__['azurearm.paged_object_to_list'](subconn.tenants.list())
for tenant in tenants:
result[tenant['tenant_id']] = tenant
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"tenants_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"subconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'subscription'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"tenants",
"=",
"__utils__",
"[",
"'azurea... | .. versionadded:: 2019.2.0
List all tenants for your account.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.tenants_list | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L808-L832 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_assignment_delete | def policy_assignment_delete(name, scope, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a policy assignment.
:param name: The name of the policy assignment to delete.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_delete testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
'''
result = False
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
# pylint: disable=unused-variable
policy = polconn.policy_assignments.delete(
policy_assignment_name=name,
scope=scope
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def policy_assignment_delete(name, scope, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a policy assignment.
:param name: The name of the policy assignment to delete.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_delete testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
'''
result = False
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
# pylint: disable=unused-variable
policy = polconn.policy_assignments.delete(
policy_assignment_name=name,
scope=scope
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"policy_assignment_delete",
"(",
"name",
",",
"scope",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"# pylint: d... | .. versionadded:: 2019.2.0
Delete a policy assignment.
:param name: The name of the policy assignment to delete.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_delete testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852 | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L835-L865 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_assignment_create | def policy_assignment_create(name, scope, definition_name, **kwargs):
'''
.. versionadded:: 2019.2.0
Create a policy assignment.
:param name: The name of the policy assignment to create.
:param scope: The scope of the policy assignment.
:param definition_name: The name of the policy definition to assign.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_create testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852 testpolicy
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
# "get" doesn't work for built-in policies per https://github.com/Azure/azure-cli/issues/692
# Uncomment this section when the ticket above is resolved.
# BEGIN
# definition = policy_definition_get(
# name=definition_name,
# **kwargs
# )
# END
# Delete this section when the ticket above is resolved.
# BEGIN
definition_list = policy_definitions_list(
**kwargs
)
if definition_name in definition_list:
definition = definition_list[definition_name]
else:
definition = {'error': 'The policy definition named "{0}" could not be found.'.format(definition_name)}
# END
if 'error' not in definition:
definition_id = str(definition['id'])
prop_kwargs = {'policy_definition_id': definition_id}
policy_kwargs = kwargs.copy()
policy_kwargs.update(prop_kwargs)
try:
policy_model = __utils__['azurearm.create_object_model'](
'resource.policy',
'PolicyAssignment',
**policy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
policy = polconn.policy_assignments.create(
scope=scope,
policy_assignment_name=name,
parameters=policy_model
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
else:
result = {'error': 'The policy definition named "{0}" could not be found.'.format(definition_name)}
return result | python | def policy_assignment_create(name, scope, definition_name, **kwargs):
'''
.. versionadded:: 2019.2.0
Create a policy assignment.
:param name: The name of the policy assignment to create.
:param scope: The scope of the policy assignment.
:param definition_name: The name of the policy definition to assign.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_create testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852 testpolicy
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
# "get" doesn't work for built-in policies per https://github.com/Azure/azure-cli/issues/692
# Uncomment this section when the ticket above is resolved.
# BEGIN
# definition = policy_definition_get(
# name=definition_name,
# **kwargs
# )
# END
# Delete this section when the ticket above is resolved.
# BEGIN
definition_list = policy_definitions_list(
**kwargs
)
if definition_name in definition_list:
definition = definition_list[definition_name]
else:
definition = {'error': 'The policy definition named "{0}" could not be found.'.format(definition_name)}
# END
if 'error' not in definition:
definition_id = str(definition['id'])
prop_kwargs = {'policy_definition_id': definition_id}
policy_kwargs = kwargs.copy()
policy_kwargs.update(prop_kwargs)
try:
policy_model = __utils__['azurearm.create_object_model'](
'resource.policy',
'PolicyAssignment',
**policy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
policy = polconn.policy_assignments.create(
scope=scope,
policy_assignment_name=name,
parameters=policy_model
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
else:
result = {'error': 'The policy definition named "{0}" could not be found.'.format(definition_name)}
return result | [
"def",
"policy_assignment_create",
"(",
"name",
",",
"scope",
",",
"definition_name",
",",
"*",
"*",
"kwargs",
")",
":",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"# \"get\" doesn't work for bu... | .. versionadded:: 2019.2.0
Create a policy assignment.
:param name: The name of the policy assignment to create.
:param scope: The scope of the policy assignment.
:param definition_name: The name of the policy definition to assign.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_create testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852 testpolicy | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L868-L943 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_assignment_get | def policy_assignment_get(name, scope, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific policy assignment.
:param name: The name of the policy assignment to query.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_get testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy = polconn.policy_assignments.get(
policy_assignment_name=name,
scope=scope
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def policy_assignment_get(name, scope, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific policy assignment.
:param name: The name of the policy assignment to query.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_get testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy = polconn.policy_assignments.get(
policy_assignment_name=name,
scope=scope
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"policy_assignment_get",
"(",
"name",
",",
"scope",
",",
"*",
"*",
"kwargs",
")",
":",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"policy",
"=",
"polconn",
".",
"polic... | .. versionadded:: 2019.2.0
Get details about a specific policy assignment.
:param name: The name of the policy assignment to query.
:param scope: The scope of the policy assignment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignment_get testassign \
/subscriptions/bc75htn-a0fhsi-349b-56gh-4fghti-f84852 | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L946-L975 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.