text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_service(self, name):
""" Delete a service by name. @param name: Service name @return: The deleted ApiService object """ |
return services.delete_service(self._get_resource_root(), name, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_service(self, name):
""" Lookup a service by name. @param name: Service name @return: An ApiService object """ |
return services.get_service(self._get_resource_root(), name, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_services(self, view = None):
""" Get all services in this cluster. @return: A list of ApiService objects. """ |
return services.get_all_services(self._get_resource_root(), self.name, view) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parcel(self, product, version):
""" Lookup a parcel by product and version. @param product: the product name @param version: the product version @return: An ApiParcel object """ |
return parcels.get_parcel(self._get_resource_root(), product, version, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_parcels(self, view = None):
""" Get all parcels in this cluster. @return: A list of ApiParcel objects. """ |
return parcels.get_all_parcels(self._get_resource_root(), self.name, view) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_hosts(self, hostIds):
""" Adds a host to the cluster. @param hostIds: List of IDs of hosts to add to cluster. @return: A list of ApiHostRef objects of the new hosts that were added to the cluster @since: API v3 """ |
hostRefList = [ApiHostRef(self._get_resource_root(), x) for x in hostIds]
return self._post("hosts", ApiHostRef, True, data=hostRefList,
api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self, restart_only_stale_services=None, redeploy_client_configuration=None, restart_service_names=None):
""" Restart all services in the cluster. Services are restarted in the appropriate order given their dependencies. @param restart_only_stale_services: Only restart services that have stale configuration and their dependent services. Default is False. @param redeploy_client_configuration: Re-deploy client configuration for all services in the cluster. Default is False. @param restart_service_names: Only restart services that are specified and their dependent services. Available since API v11. @since API v6 @return: Reference to the submitted command. """ |
if self._get_resource_root().version < 6:
return self._cmd('restart')
else:
args = dict()
args['restartOnlyStaleServices'] = restart_only_stale_services
args['redeployClientConfiguration'] = redeploy_client_configuration
if self._get_resource_root().version >= 11:
args['restartServiceNames'] = restart_service_names
return self._cmd('restart', data=args, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_maintenance_mode(self):
""" Put the cluster in maintenance mode. @return: Reference to the completed command. @since: API v2 """ |
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(get_cluster(self._get_resource_root(), self.name))
return cmd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_host_template(self, name):
""" Retrieves a host templates by name. @param name: Host template name. @return: An ApiHostTemplate object. """ |
return host_templates.get_host_template(self._get_resource_root(), name, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_host_template(self, name):
""" Creates a host template. @param name: Name of the host template to create. @return: An ApiHostTemplate object. """ |
return host_templates.create_host_template(self._get_resource_root(), name, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_host_template(self, name):
""" Deletes a host template. @param name: Name of the host template to delete. @return: An ApiHostTemplate object. """ |
return host_templates.delete_host_template(self._get_resource_root(), name, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rolling_restart(self, slave_batch_size=None, slave_fail_count_threshold=None, sleep_seconds=None, stale_configs_only=None, unupgraded_only=None, roles_to_include=None, restart_service_names=None):
""" Command to do a "best-effort" rolling restart of the given cluster, i.e. it does plain restart of services that cannot be rolling restarted, followed by first rolling restarting non-slaves and then rolling restarting the slave roles of services that can be rolling restarted. The slave restarts are done host-by-host. @param slave_batch_size: Number of hosts with slave roles to restart at a time Must be greater than 0. Default is 1. @param slave_fail_count_threshold: The threshold for number of slave host batches that are allowed to fail to restart before the entire command is considered failed. Must be >= 0. Default is 0. @param sleep_seconds: Number of seconds to sleep between restarts of slave host batches. Must be >=0. Default is 0. @param stale_configs_only: Restart roles with stale configs only. Default is false. @param unupgraded_only: Restart roles that haven't been upgraded yet. Default is false. @param roles_to_include: Role types to restart. Default is slave roles only. @param restart_service_names: List of specific services to restart. @return: Reference to the submitted command. @since: API v4 """ |
args = dict()
if slave_batch_size:
args['slaveBatchSize'] = slave_batch_size
if slave_fail_count_threshold:
args['slaveFailCountThreshold'] = slave_fail_count_threshold
if sleep_seconds:
args['sleepSeconds'] = sleep_seconds
if stale_configs_only:
args['staleConfigsOnly'] = stale_configs_only
if unupgraded_only:
args['unUpgradedOnly'] = unupgraded_only
if roles_to_include:
args['rolesToInclude'] = roles_to_include
if restart_service_names:
args['restartServiceNames'] = restart_service_names
return self._cmd('rollingRestart', data=args, api_version=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rolling_upgrade(self, upgrade_from_cdh_version, upgrade_to_cdh_version, upgrade_service_names, slave_batch_size=None, slave_fail_count_threshold=None, sleep_seconds=None):
""" Command to do a rolling upgrade of services in the given cluster This command does not handle any services that don't support rolling upgrades. The command will throw an error and not start if upgrade of any such service is requested. This command does not upgrade the full CDH Cluster. You should normally use the upgradeCDH Command for upgrading the cluster. This is primarily helpful if you need to need to recover from an upgrade failure or for advanced users to script an alternative to the upgradeCdhCommand. This command expects the binaries to be available on hosts and activated. It does not change any binaries on the hosts. @param upgrade_from_cdh_version: Current CDH Version of the services. Example versions are: "5.1.0", "5.2.2" or "5.4.0" @param upgrade_to_cdh_version: Target CDH Version for the services. The CDH version should already be present and activated on the nodes. Example versions are: "5.1.0", "5.2.2" or "5.4.0" @param upgrade_service_names: List of specific services to be upgraded and restarted. @param slave_batch_size: Number of hosts with slave roles to restart at a time Must be greater than 0. Default is 1. @param slave_fail_count_threshold: The threshold for number of slave host batches that are allowed to fail to restart before the entire command is considered failed. Must be >= 0. Default is 0. @param sleep_seconds: Number of seconds to sleep between restarts of slave host batches. Must be >=0. Default is 0. @return: Reference to the submitted command. @since: API v10 """ |
args = dict()
args['upgradeFromCdhVersion'] = upgrade_from_cdh_version
args['upgradeToCdhVersion'] = upgrade_to_cdh_version
args['upgradeServiceNames'] = upgrade_service_names
if slave_batch_size:
args['slaveBatchSize'] = slave_batch_size
if slave_fail_count_threshold:
args['slaveFailCountThreshold'] = slave_fail_count_threshold
if sleep_seconds:
args['sleepSeconds'] = sleep_seconds
return self._cmd('rollingUpgrade', data=args, api_version=10) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_for_kerberos(self, datanode_transceiver_port=None, datanode_web_port=None):
""" Command to configure the cluster to use Kerberos for authentication. This command will configure all relevant services on a cluster for Kerberos usage. This command will trigger a GenerateCredentials command to create Kerberos keytabs for all roles in the cluster. @param datanode_transceiver_port: The HDFS DataNode transceiver port to use. This will be applied to all DataNode role configuration groups. If not specified, this will default to 1004. @param datanode_web_port: The HDFS DataNode web port to use. This will be applied to all DataNode role configuration groups. If not specified, this will default to 1006. @return: Reference to the submitted command. @since: API v11 """ |
args = dict()
if datanode_transceiver_port:
args['datanodeTransceiverPort'] = datanode_transceiver_port
if datanode_web_port:
args['datanodeWebPort'] = datanode_web_port
return self._cmd('configureForKerberos', data=args, api_version=11) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, export_auto_config=False):
""" Export the cluster template for the given cluster. ccluster must have host templates defined. It cluster does not have host templates defined it will export host templates based on roles assignment. @param export_auto_config: Also export auto configured configs @return: Return cluster template @since: API v12 """ |
return self._get("export", ApiClusterTemplate, False,
params=dict(exportAutoConfig=export_auto_config), api_version=12) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_api_version(resource_root, min_version):
""" Checks if the resource_root's API version it at least the given minimum version. """ |
if resource_root.version < min_version:
raise Exception("API version %s is required but %s is in use."
% (min_version, resource_root.version)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(method, path, ret_type, ret_is_list=False, data=None, params=None, api_version=1):
""" Generic function for calling a resource method and automatically dealing with serialization of parameters and deserialization of return values. @param method: method to call (must be bound to a resource; e.g., "resource_root.get"). @param path: the full path of the API method to call. @param ret_type: return type of the call. @param ret_is_list: whether the return type is an ApiList. @param data: Optional data to send as payload to the call. @param params: Optional query parameters for the call. @param api_version: minimum API version for the call. """ |
check_api_version(method.im_self, api_version)
if data is not None:
data = json.dumps(Attr(is_api_list=True).to_json(data, False))
ret = method(path, data=data, params=params)
else:
ret = method(path, params=params)
if ret_type is None:
return
elif ret_is_list:
return ApiList.from_json_dict(ret, method.im_self, ret_type)
elif isinstance(ret, list):
return [ ret_type.from_json_dict(x, method.im_self) for x in ret ]
else:
return ret_type.from_json_dict(ret, method.im_self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_to_api_list(dic):
""" Converts a python dictionary into a list containing the proper ApiConfig encoding for configuration data. @param dic: Key-value pairs to convert. @return: JSON dictionary of an ApiConfig list (*not* an ApiList). """ |
config = [ ]
for k, v in dic.iteritems():
config.append({ 'name' : k, 'value': v })
return { ApiList.LIST_KEY : config } |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_to_config(dic, full = False):
""" Converts a JSON-decoded config dictionary to a python dictionary. When materializing the full view, the values in the dictionary will be instances of ApiConfig, instead of strings. @param dic: JSON-decoded config dictionary. @param full: Whether to materialize the full view of the config data. @return: Python dictionary with config data. """ |
config = { }
for entry in dic['items']:
k = entry['name']
if full:
config[k] = ApiConfig.from_json_dict(entry, None)
else:
config[k] = entry.get('value')
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self, value, preserve_ro):
""" Returns the JSON encoding of the given attribute value. If the value has a 'to_json_dict' object, that method is called. Otherwise, the following values are returned for each input type: - datetime.datetime: string with the API representation of a date. - dictionary: if 'atype' is ApiConfig, a list of ApiConfig objects. - python list: python list (or ApiList) with JSON encoding of items - the raw value otherwise """ |
if hasattr(value, 'to_json_dict'):
return value.to_json_dict(preserve_ro)
elif isinstance(value, dict) and self._atype == ApiConfig:
return config_to_api_list(value)
elif isinstance(value, datetime.datetime):
return value.strftime(self.DATE_FMT)
elif isinstance(value, list) or isinstance(value, tuple):
if self._is_api_list:
return ApiList(value).to_json_dict()
else:
return [ self.to_json(x, preserve_ro) for x in value ]
else:
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(self, resource_root, data):
""" Parses the given JSON value into an appropriate python object. This means: - a datetime.datetime if 'atype' is datetime.datetime - a converted config dictionary or config list if 'atype' is ApiConfig - if the attr is an API list, an ApiList with instances of 'atype' - an instance of 'atype' if it has a 'from_json_dict' method - a python list with decoded versions of the member objects if the input is a python list. - the raw value otherwise """ |
if data is None:
return None
if self._atype == datetime.datetime:
return datetime.datetime.strptime(data, self.DATE_FMT)
elif self._atype == ApiConfig:
# ApiConfig is special. We want a python dictionary for summary views,
# but an ApiList for full views. Try to detect each case from the JSON
# data.
if not data['items']:
return { }
first = data['items'][0]
return json_to_config(data, len(first) == 2)
elif self._is_api_list:
return ApiList.from_json_dict(data, resource_root, self._atype)
elif isinstance(data, list):
return [ self.from_json(resource_root, x) for x in data ]
elif hasattr(self._atype, 'from_json_dict'):
return self._atype.from_json_dict(data, resource_root)
else:
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update(self, api_obj):
"""Copy state from api_obj to this object.""" |
if not isinstance(self, api_obj.__class__):
raise ValueError(
"Class %s does not derive from %s; cannot update attributes." %
(self.__class__, api_obj.__class__))
for name in self._get_attributes().keys():
try:
val = getattr(api_obj, name)
setattr(self, name, val)
except AttributeError, ignored:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _require_min_api_version(self, version):
""" Raise an exception if the version of the api is less than the given version. @param version: The minimum required version. """ |
actual_version = self._get_resource_root().version
version = max(version, self._api_version())
if actual_version < version:
raise Exception("API version %s is required but %s is in use."
% (version, actual_version)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_config(self, rel_path, view, api_version=1):
""" Retrieves an ApiConfig list from the given relative path. """ |
self._require_min_api_version(api_version)
params = view and dict(view=view) or None
resp = self._get_resource_root().get(self._path() + '/' + rel_path,
params=params)
return json_to_config(resp, view == 'full') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self):
""" Retrieve updated data about the command from the server. @return: A new ApiCommand object. """ |
if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
return self
resp = self._get_resource_root().get(self._path())
return ApiCommand.from_json_dict(resp, self._get_resource_root()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(self, timeout=None):
""" Wait for command to finish. @param timeout: (Optional) Max amount of time (in seconds) to wait. Wait forever by default. @return: The final ApiCommand object, containing the last known state. The command may still be running in case of timeout. """ |
if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
return self
SLEEP_SEC = 5
if timeout is None:
deadline = None
else:
deadline = time.time() + timeout
while True:
cmd = self.fetch()
if not cmd.active:
return cmd
if deadline is not None:
now = time.time()
if deadline < now:
return cmd
else:
time.sleep(min(SLEEP_SEC, deadline - now))
else:
time.sleep(SLEEP_SEC) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self):
""" Abort a running command. @return: A new ApiCommand object with the updated information. """ |
if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
return self
path = self._path() + '/abort'
resp = self._get_resource_root().post(path)
return ApiCommand.from_json_dict(resp, self._get_resource_root()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retry(self):
""" Retry a failed or aborted command. @return: A new ApiCommand object with the updated information. """ |
path = self._path() + '/retry'
resp = self._get_resource_root().post(path)
return ApiCommand.from_json_dict(resp, self._get_resource_root()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_role_config_groups(resource_root, service_name, apigroup_list, cluster_name="default"):
""" Create role config groups. @param resource_root: The root Resource object. @param service_name: Service name. @param apigroup_list: List of role config groups to create. @param cluster_name: Cluster name. @return: New ApiRoleConfigGroup object. @since: API v3 """ |
return call(resource_root.post,
_get_role_config_groups_path(cluster_name, service_name),
ApiRoleConfigGroup, True, data=apigroup_list, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role_config_group(resource_root, service_name, name, cluster_name="default"):
""" Find a role config group by name. @param resource_root: The root Resource object. @param service_name: Service name. @param name: Role config group name. @param cluster_name: Cluster name. @return: An ApiRoleConfigGroup object. """ |
return _get_role_config_group(resource_root, _get_role_config_group_path(
cluster_name, service_name, name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_role_config_groups(resource_root, service_name, cluster_name="default"):
""" Get all role config groups in the specified service. @param resource_root: The root Resource object. @param service_name: Service name. @param cluster_name: Cluster name. @return: A list of ApiRoleConfigGroup objects. @since: API v3 """ |
return call(resource_root.get,
_get_role_config_groups_path(cluster_name, service_name),
ApiRoleConfigGroup, True, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_role_config_group(resource_root, service_name, name, apigroup, cluster_name="default"):
""" Update a role config group by name. @param resource_root: The root Resource object. @param service_name: Service name. @param name: Role config group name. @param apigroup: The updated role config group. @param cluster_name: Cluster name. @return: The updated ApiRoleConfigGroup object. @since: API v3 """ |
return call(resource_root.put,
_get_role_config_group_path(cluster_name, service_name, name),
ApiRoleConfigGroup, data=apigroup, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_roles(resource_root, service_name, name, role_names, cluster_name="default"):
""" Moves roles to the specified role config group. The roles can be moved from any role config group belonging to the same service. The role type of the destination group must match the role type of the roles. @param name: The name of the group the roles will be moved to. @param role_names: The names of the roles to move. @return: List of roles which have been moved successfully. @since: API v3 """ |
return call(resource_root.put,
_get_role_config_group_path(cluster_name, service_name, name) + '/roles',
ApiRole, True, data=role_names, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_roles_to_base_role_config_group(resource_root, service_name, role_names, cluster_name="default"):
""" Moves roles to the base role config group. The roles can be moved from any role config group belonging to the same service. The role type of the roles may vary. Each role will be moved to its corresponding base group depending on its role type. @param role_names: The names of the roles to move. @return: List of roles which have been moved successfully. @since: API v3 """ |
return call(resource_root.put,
_get_role_config_groups_path(cluster_name, service_name) + '/roles',
ApiRole, True, data=role_names, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_config(self, config):
""" Update the group's configuration. @param config: Dictionary with configuration to update. @return: Dictionary with updated configuration. """ |
path = self._path() + '/config'
resp = self._get_resource_root().put(path, data = config_to_json(config))
return json_to_config(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_roles(self, roles):
""" Moves roles to this role config group. The roles can be moved from any role config group belonging to the same service. The role type of the destination group must match the role type of the roles. @param roles: The names of the roles to move. @return: List of roles which have been moved successfully. """ |
return move_roles(self._get_resource_root(), self.serviceRef.serviceName,
self.name, roles, self.serviceRef.clusterName) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role(resource_root, service_name, name, cluster_name="default"):
""" Lookup a role by name @param resource_root: The root Resource object. @param service_name: Service name @param name: Role name @param cluster_name: Cluster name @return: An ApiRole object """ |
return _get_role(resource_root, _get_role_path(cluster_name, service_name, name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_roles(resource_root, service_name, cluster_name="default", view=None):
""" Get all roles @param resource_root: The root Resource object. @param service_name: Service name @param cluster_name: Cluster name @return: A list of ApiRole objects. """ |
return call(resource_root.get,
_get_roles_path(cluster_name, service_name),
ApiRole, True, params=view and dict(view=view) or None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_roles_by_type(resource_root, service_name, role_type, cluster_name="default", view=None):
""" Get all roles of a certain type in a service @param resource_root: The root Resource object. @param service_name: Service name @param role_type: Role type @param cluster_name: Cluster name @return: A list of ApiRole objects. """ |
roles = get_all_roles(resource_root, service_name, cluster_name, view)
return [ r for r in roles if r.type == role_type ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_role(resource_root, service_name, name, cluster_name="default"):
""" Delete a role by name @param resource_root: The root Resource object. @param service_name: Service name @param name: Role name @param cluster_name: Cluster name @return: The deleted ApiRole object """ |
return call(resource_root.delete,
_get_role_path(cluster_name, service_name, name), ApiRole) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_users(resource_root, view=None):
""" Get all users. @param resource_root: The root Resource object @param view: View to materialize ('full' or 'summary'). @return: A list of ApiUser objects. """ |
return call(resource_root.get, USERS_PATH, ApiUser, True,
params=view and dict(view=view) or None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grant_admin_role(self):
""" Grant admin access to a user. If the user already has admin access, this does nothing. If the user currently has a non-admin role, it will be replaced with the admin role. @return: An ApiUser object """ |
apiuser = ApiUser(self._get_resource_root(), self.name, roles=['ROLE_ADMIN'])
return self._put('', ApiUser, data=apiuser) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_batch(resource_root, elements):
""" Execute a batch request with one or more elements. If any element fails, the entire request is rolled back and subsequent elements are ignored. @param elements: A list of ApiBatchRequestElements @return: an ApiBatchResponseList @since: API v6 """ |
return call(resource_root.post, BATCH_PATH, ApiBatchResponseList,
data=elements, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_services(resource_root, cluster_name="default", view=None):
""" Get all services @param resource_root: The root Resource object. @param cluster_name: Cluster name @return: A list of ApiService objects. """ |
return call(resource_root.get,
SERVICES_PATH % (cluster_name,),
ApiService, True, params=view and dict(view=view) or None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_service(resource_root, name, cluster_name="default"):
""" Delete a service by name @param resource_root: The root Resource object. @param name: Service name @param cluster_name: Cluster name @return: The deleted ApiService object """ |
return call(resource_root.delete,
"%s/%s" % (SERVICES_PATH % (cluster_name,), name),
ApiService) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_svc_config(self, json_dic, view = None):
""" Parse a json-decoded ApiServiceConfig dictionary into a 2-tuple. @param json_dic: The json dictionary with the config data. @param view: View to materialize. @return: 2-tuple (service config dictionary, role type configurations) """ |
svc_config = json_to_config(json_dic, view == 'full')
rt_configs = { }
if json_dic.has_key(ROLETYPES_CFG_KEY):
for rt_config in json_dic[ROLETYPES_CFG_KEY]:
rt_configs[rt_config['roleType']] = \
json_to_config(rt_config, view == 'full')
return (svc_config, rt_configs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_watched_directory(self, dir_path):
""" Adds a directory to the watching list. @param dir_path: The path of the directory to be added to the watching list @return: The added directory, or null if failed @since: API v14 """ |
req = ApiWatchedDir(self._get_resource_root(), path=dir_path)
return self._post("watcheddir", ApiWatchedDir, data=req, api_version=14) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_impala_queries(self, start_time, end_time, filter_str="", limit=100, offset=0):
""" Returns a list of queries that satisfy the filter @type start_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See the python datetime documentation for more details about python's time zone handling. @param start_time: Queries must have ended after this time @type end_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See the python datetime documentation for more details about python's time zone handling. @param end_time: Queries must have started before this time @param filter_str: A filter to apply to the queries. For example: 'user = root and queryDuration > 5s' @param limit: The maximum number of results to return @param offset: The offset into the return list @since: API v4 """ |
params = {
'from': start_time.isoformat(),
'to': end_time.isoformat(),
'filter': filter_str,
'limit': limit,
'offset': offset,
}
return self._get("impalaQueries", ApiImpalaQueryResponse,
params=params, api_version=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_query_details(self, query_id, format='text'):
""" Get the query details @param query_id: The query ID @param format: The format of the response ('text' or 'thrift_encoded') @return: The details text @since: API v4 """ |
return self._get("impalaQueries/" + query_id, ApiImpalaQueryDetailsResponse,
params=dict(format=format), api_version=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_llama_rm(self, llama1_host_id, llama1_role_name=None, llama2_host_id=None, llama2_role_name=None, zk_service_name=None, skip_restart=False):
""" Enable Llama-based resource management for Impala. This command only applies to CDH 5.1+ Impala services. This command configures YARN and Impala for Llama resource management, and then creates one or two Llama roles, as specified by the parameters. When two Llama roles are created, they are configured as an active-standby pair. Auto-failover from active to standby Llama will be enabled using ZooKeeper. If optional role name(s) are specified, the new Llama role(s) will be named accordingly; otherwise, role name(s) will be automatically generated. By default, YARN, Impala, and any dependent services will be restarted, and client configuration will be re-deployed across the cluster. These default actions may be suppressed. In order to enable Llama resource management, a YARN service must be present in the cluster, and Cgroup-based resource management must be enabled for all hosts with NodeManager roles. If these preconditions are not met, the command will fail. @param llama1_host_id: id of the host where the first Llama role will be created. @param llama1_role_name: Name of the first Llama role. If omitted, a name will be generated automatically. @param llama2_host_id: id of the host where the second Llama role will be created. If omitted, only one Llama role will be created (i.e., high availability will not be enabled). @param llama2_role_name: Name of the second Llama role. If omitted, a name will be generated automatically. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. Only relevant when enabling Llama RM in HA mode (i.e., when creating two Llama roles). If Impala's ZooKeeper dependency is already set, then that ZooKeeper service will be used for auto-failover, and this parameter may be omitted. @param skip_restart: true to skip the restart of Yarn, Impala, and their dependent services, and to skip deployment of client configuration. Default is False (i.e., by default dependent services are restarted and client configuration is deployed). @return: Reference to the submitted command. @since: API v8 """ |
args = dict(
llama1HostId = llama1_host_id,
llama1RoleName = llama1_role_name,
llama2HostId = llama2_host_id,
llama2RoleName = llama2_role_name,
zkServiceName = zk_service_name,
skipRestart = skip_restart
)
return self._cmd('impalaEnableLlamaRm', data=args, api_version=8) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_llama_ha(self, new_llama_host_id, zk_service_name=None, new_llama_role_name=None):
""" Enable high availability for an Impala Llama ApplicationMaster. This command only applies to CDH 5.1+ Impala services. @param new_llama_host_id: id of the host where the second Llama role will be added. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If Impala's ZooKeeper dependency is already set, then that ZooKeeper service will be used for auto-failover, and this parameter may be omitted. @param new_llama_role_name: Name of the new Llama role. If omitted, a name will be generated automatically. @return: Reference to the submitted command. @since: API v8 """ |
args = dict(
newLlamaHostId = new_llama_host_id,
zkServiceName = zk_service_name,
newLlamaRoleName = new_llama_role_name
)
return self._cmd('impalaEnableLlamaHa', data=args, api_version=8) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_yarn_applications(self, start_time, end_time, filter_str="", limit=100, offset=0):
""" Returns a list of YARN applications that satisfy the filter @type start_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See the python datetime documentation for more details about python's time zone handling. @param start_time: Applications must have ended after this time @type end_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See the python datetime documentation for more details about python's time zone handling. @param filter_str: A filter to apply to the applications. For example: 'user = root and applicationDuration > 5s' @param limit: The maximum number of results to return @param offset: The offset into the return list @since: API v6 """ |
params = {
'from': start_time.isoformat(),
'to': end_time.isoformat(),
'filter': filter_str,
'limit': limit,
'offset': offset
}
return self._get("yarnApplications", ApiYarnApplicationResponse,
params=params, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_yarn_application_diagnostics_bundle(self, application_ids, ticket_number=None, comments=None):
""" Collects the Diagnostics data for Yarn applications. @param application_ids: An array of strings containing the ids of the yarn applications. @param ticket_number: If applicable, the support ticket number of the issue being experienced on the cluster. @param comments: Additional comments @return: Reference to the submitted command. @since: API v10 """ |
args = dict(applicationIds = application_ids,
ticketNumber = ticket_number,
comments = comments)
return self._cmd('yarnApplicationDiagnosticsCollection', api_version=10, data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_config(self, view = None):
""" Retrieve the service's configuration. Retrieves both the service configuration and role type configuration for each of the service's supported role types. The role type configurations are returned as a dictionary, whose keys are the role type name, and values are the respective configuration dictionaries. The 'summary' view contains strings as the dictionary values. The full view contains ApiConfig instances as the values. @param view: View to materialize ('full' or 'summary') @return: 2-tuple (service config dictionary, role type configurations) """ |
path = self._path() + '/config'
resp = self._get_resource_root().get(path,
params = view and dict(view=view) or None)
return self._parse_svc_config(resp, view) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_config(self, svc_config, **rt_configs):
""" Update the service's configuration. @param svc_config: Dictionary with service configuration to update. @param rt_configs: Dict of role type configurations to update. @return: 2-tuple (service config dictionary, role type configurations) """ |
path = self._path() + '/config'
if svc_config:
data = config_to_api_list(svc_config)
else:
data = { }
if rt_configs:
rt_list = [ ]
for rt, cfg in rt_configs.iteritems():
rt_data = config_to_api_list(cfg)
rt_data['roleType'] = rt
rt_list.append(rt_data)
data[ROLETYPES_CFG_KEY] = rt_list
resp = self._get_resource_root().put(path, data = json.dumps(data))
return self._parse_svc_config(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_role(self, role_name, role_type, host_id):
""" Create a role. @param role_name: Role name @param role_type: Role type @param host_id: ID of the host to assign the role to @return: An ApiRole object """ |
return roles.create_role(self._get_resource_root(), self.name, role_type,
role_name, host_id, self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_role(self, name):
""" Delete a role by name. @param name: Role name @return: The deleted ApiRole object """ |
return roles.delete_role(self._get_resource_root(), self.name, name,
self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role(self, name):
""" Lookup a role by name. @param name: Role name @return: An ApiRole object """ |
return roles.get_role(self._get_resource_root(), self.name, name,
self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_roles(self, view = None):
""" Get all roles in the service. @param view: View to materialize ('full' or 'summary') @return: A list of ApiRole objects. """ |
return roles.get_all_roles(self._get_resource_root(), self.name,
self._get_cluster_name(), view) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_roles_by_type(self, role_type, view = None):
""" Get all roles of a certain type in a service. @param role_type: Role type @param view: View to materialize ('full' or 'summary') @return: A list of ApiRole objects. """ |
return roles.get_roles_by_type(self._get_resource_root(), self.name,
role_type, self._get_cluster_name(), view) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role_types(self):
""" Get a list of role types in a service. @return: A list of role types (strings) """ |
resp = self._get_resource_root().get(self._path() + '/roleTypes')
return resp[ApiList.LIST_KEY] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_role_config_groups(self):
""" Get a list of role configuration groups in the service. @return: A list of ApiRoleConfigGroup objects. @since: API v3 """ |
return role_config_groups.get_all_role_config_groups(
self._get_resource_root(), self.name, self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role_config_group(self, name):
""" Get a role configuration group in the service by name. @param name: The name of the role config group. @return: An ApiRoleConfigGroup object. @since: API v3 """ |
return role_config_groups.get_role_config_group(
self._get_resource_root(), self.name, name, self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_role_config_group(self, name, apigroup):
""" Update a role config group. @param name: Role config group name. @param apigroup: The updated role config group. @return: The updated ApiRoleConfigGroup object. @since: API v3 """ |
return role_config_groups.update_role_config_group(
self._get_resource_root(), self.name, name, apigroup,
self._get_cluster_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_hdfs_ha(self, active_name, secondary_name, start_dependent_services=True, deploy_client_configs=True, disable_quorum_storage=False):
""" Disable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use disable_nn_ha instead. @param active_name: Name of the NameNode to keep. @param secondary_name: Name of (existing) SecondaryNameNode to link to remaining NameNode. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param disable_quorum_storage: whether to disable Quorum-based Storage. Available since API v2. Quorum-based Storage will be disabled for all nameservices that have Quorum-based Storage enabled. @return: Reference to the submitted command. """ |
args = dict(
activeName = active_name,
secondaryName = secondary_name,
startDependentServices = start_dependent_services,
deployClientConfigs = deploy_client_configs,
)
version = self._get_resource_root().version
if version < 2:
if disable_quorum_storage:
raise AttributeError("Quorum-based Storage requires at least API version 2 available in Cloudera Manager 4.1.")
else:
args['disableQuorumStorage'] = disable_quorum_storage
return self._cmd('hdfsDisableHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_hdfs_auto_failover(self, nameservice, active_fc_name, standby_fc_name, zk_service):
""" Enable auto-failover for an HDFS nameservice. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param nameservice: Nameservice for which to enable auto-failover. @param active_fc_name: Name of failover controller to create for active node. @param standby_fc_name: Name of failover controller to create for stand-by node. @param zk_service: ZooKeeper service to use. @return: Reference to the submitted command. """ |
version = self._get_resource_root().version
args = dict(
nameservice = nameservice,
activeFCName = active_fc_name,
standByFCName = standby_fc_name,
zooKeeperService = dict(
clusterName = zk_service.clusterRef.clusterName,
serviceName = zk_service.name,
),
)
return self._cmd('hdfsEnableAutoFailover', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_hdfs_ha(self, active_name, active_shared_path, standby_name, standby_shared_path, nameservice, start_dependent_services=True, deploy_client_configs=True, enable_quorum_storage=False):
""" Enable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param active_name: name of active NameNode. @param active_shared_path: shared edits path for active NameNode. Ignored if Quorum-based Storage is being enabled. @param standby_name: name of stand-by NameNode. @param standby_shared_path: shared edits path for stand-by NameNode. Ignored if Quourm Journal is being enabled. @param nameservice: nameservice for the HA pair. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param enable_quorum_storage: whether to enable Quorum-based Storage. Available since API v2. Quorum-based Storage will be enabled for all nameservices except those configured with NFS High Availability. @return: Reference to the submitted command. """ |
version = self._get_resource_root().version
args = dict(
activeName = active_name,
standByName = standby_name,
nameservice = nameservice,
startDependentServices = start_dependent_services,
deployClientConfigs = deploy_client_configs,
)
if enable_quorum_storage:
if version < 2:
raise AttributeError("Quorum-based Storage is not supported prior to Cloudera Manager 4.1.")
else:
args['enableQuorumStorage'] = enable_quorum_storage
else:
if active_shared_path is None or standby_shared_path is None:
raise AttributeError("Active and standby shared paths must be specified if not enabling Quorum-based Storage")
args['activeSharedEditsPath'] = active_shared_path
args['standBySharedEditsPath'] = standby_shared_path
return self._cmd('hdfsEnableHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_nn_ha(self, active_name, snn_host_id, snn_check_point_dir_list, snn_name=None):
""" Disable high availability with automatic failover for an HDFS NameNode. @param active_name: Name of the NamdeNode role that is going to be active after High Availability is disabled. @param snn_host_id: Id of the host where the new SecondaryNameNode will be created. @param snn_check_point_dir_list : List of directories used for checkpointing by the new SecondaryNameNode. @param snn_name: Name of the new SecondaryNameNode role (Optional). @return: Reference to the submitted command. @since: API v6 """ |
args = dict(
activeNnName = active_name,
snnHostId = snn_host_id,
snnCheckpointDirList = snn_check_point_dir_list,
snnName = snn_name
)
return self._cmd('hdfsDisableNnHa', data=args, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_jt_ha(self, new_jt_host_id, force_init_znode=True, zk_service_name=None, new_jt_name=None, fc1_name=None, fc2_name=None):
""" Enable high availability for a MR JobTracker. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If MapReduce service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @param new_jt_host_id: id of the host where the second JobTracker will be added. @param force_init_znode: Initialize the ZNode used for auto-failover even if it already exists. This can happen if JobTracker HA was enabled before and then disabled. Disable operation doesn't delete this ZNode. Defaults to true. @param new_jt_name: Name of the second JobTracker role to be created. @param fc1_name: Name of the Failover Controller role that is co-located with the existing JobTracker. @param fc2_name: Name of the Failover Controller role that is co-located with the new JobTracker. @return: Reference to the submitted command. @since: API v5 """ |
args = dict(
newJtHostId = new_jt_host_id,
forceInitZNode = force_init_znode,
zkServiceName = zk_service_name,
newJtRoleName = new_jt_name,
fc1RoleName = fc1_name,
fc2RoleName = fc2_name
)
return self._cmd('enableJtHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_jt_ha(self, active_name):
""" Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be removed. @return: Reference to the submitted command. """ |
args = dict(
activeName = active_name,
)
return self._cmd('disableJtHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_rm_ha(self, new_rm_host_id, zk_service_name=None):
""" Enable high availability for a YARN ResourceManager. @param new_rm_host_id: id of the host where the second ResourceManager will be added. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If YARN service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @return: Reference to the submitted command. @since: API v6 """ |
args = dict(
newRmHostId = new_rm_host_id,
zkServiceName = zk_service_name
)
return self._cmd('enableRmHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_rm_ha(self, active_name):
""" Disable high availability for a YARN ResourceManager active-standby pair. @param active_name: name of the ResourceManager that will be active after the disable operation. The other ResourceManager will be removed. @return: Reference to the submitted command. @since: API v6 """ |
args = dict(
activeName = active_name
)
return self._cmd('disableRmHa', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_oozie_ha(self, new_oozie_server_host_ids, new_oozie_server_role_names=None, zk_service_name=None, load_balancer_host_port=None):
""" Enable high availability for Oozie. @param new_oozie_server_host_ids: List of IDs of the hosts on which new Oozie Servers will be added. @param new_oozie_server_role_names: List of names of the new Oozie Servers. This is an optional argument, but if provided, it should match the length of host IDs provided. @param zk_service_name: Name of the ZooKeeper service that will be used for Oozie HA. This is an optional parameter if the Oozie to ZooKeeper dependency is already set. @param load_balancer_host_port: Address and port of the load balancer used for Oozie HA. This is an optional parameter if this config is already set. @return: Reference to the submitted command. @since: API v6 """ |
args = dict(
newOozieServerHostIds = new_oozie_server_host_ids,
newOozieServerRoleNames = new_oozie_server_role_names,
zkServiceName = zk_service_name,
loadBalancerHostPort = load_balancer_host_port
)
return self._cmd('oozieEnableHa', data=args, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_oozie_ha(self, active_name):
""" Disable high availability for Oozie @param active_name: Name of the Oozie Server that will be active after High Availability is disabled. @return: Reference to the submitted command. @since: API v6 """ |
args = dict(
activeName = active_name
)
return self._cmd('oozieDisableHa', data=args, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def failover_hdfs(self, active_name, standby_name, force=False):
""" Initiate a failover of an HDFS NameNode HA pair. This will make the given stand-by NameNode active, and vice-versa. @param active_name: name of currently active NameNode. @param standby_name: name of NameNode currently in stand-by. @param force: whether to force failover. @return: Reference to the submitted command. """ |
params = { "force" : "true" and force or "false" }
args = { ApiList.LIST_KEY : [ active_name, standby_name ] }
return self._cmd('hdfsFailover', data=[ active_name, standby_name ],
params = { "force" : "true" and force or "false" }) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roll_edits_hdfs(self, nameservice=None):
""" Roll the edits of an HDFS NameNode or Nameservice. @param nameservice: Nameservice whose edits should be rolled. Required only with a federated HDFS. @return: Reference to the submitted command. @since: API v3 """ |
args = dict()
if nameservice:
args['nameservice'] = nameservice
return self._cmd('hdfsRollEdits', data=args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_hue_db(self, *servers):
""" Synchronize the Hue server's database. @param servers: Name of Hue Server roles to synchronize. Not required starting with API v10. @return: List of submitted commands. """ |
actual_version = self._get_resource_root().version
if actual_version < 10:
return self._role_cmd('hueSyncDb', servers)
return self._cmd('hueSyncDb', api_version=10) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_maintenance_mode(self):
""" Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2 """ |
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(_get_service(self._get_resource_root(), self._path()))
return cmd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_replication_schedule(self, start_time, end_time, interval_unit, interval, paused, arguments, alert_on_start=False, alert_on_success=False, alert_on_fail=False, alert_on_abort=False):
""" Create a new replication schedule for this service. The replication argument type varies per service type. The following types are recognized: - HDFS: ApiHdfsReplicationArguments - Hive: ApiHiveReplicationArguments @type start_time: datetime.datetime @param start_time: The time at which the schedule becomes active and first executes. @type end_time: datetime.datetime @param end_time: The time at which the schedule will expire. @type interval_unit: str @param interval_unit: The unit of time the `interval` represents. Ex. MINUTE, HOUR, DAY. See the server documentation for a full list of values. @type interval: int @param interval: The number of time units to wait until triggering the next replication. @type paused: bool @param paused: Should the schedule be paused? Useful for on-demand replication. @param arguments: service type-specific arguments for the replication job. @param alert_on_start: whether to generate alerts when the job is started. @param alert_on_success: whether to generate alerts when the job succeeds. @param alert_on_fail: whether to generate alerts when the job fails. @param alert_on_abort: whether to generate alerts when the job is aborted. @return: The newly created schedule. @since: API v3 """ |
schedule = ApiReplicationSchedule(self._get_resource_root(),
startTime=start_time, endTime=end_time, intervalUnit=interval_unit, interval=interval,
paused=paused, alertOnStart=alert_on_start, alertOnSuccess=alert_on_success,
alertOnFail=alert_on_fail, alertOnAbort=alert_on_abort)
if self.type == 'HDFS':
if isinstance(arguments, ApiHdfsCloudReplicationArguments):
schedule.hdfsCloudArguments = arguments
elif isinstance(arguments, ApiHdfsReplicationArguments):
schedule.hdfsArguments = arguments
else:
raise TypeError, 'Unexpected type for HDFS replication argument.'
elif self.type == 'HIVE':
if not isinstance(arguments, ApiHiveReplicationArguments):
raise TypeError, 'Unexpected type for Hive replication argument.'
schedule.hiveArguments = arguments
else:
raise TypeError, 'Replication is not supported for service type ' + self.type
return self._post("replications", ApiReplicationSchedule, True, [schedule],
api_version=3)[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_replication_schedule(self, schedule_id, schedule):
""" Update a replication schedule. @param schedule_id: The id of the schedule to update. @param schedule: The modified schedule. @return: The updated replication schedule. @since: API v3 """ |
return self._put("replications/%s" % schedule_id, ApiReplicationSchedule,
data=schedule, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_replication_command_history(self, schedule_id, limit=20, offset=0, view=None):
""" Retrieve a list of commands for a replication schedule. @param schedule_id: The id of the replication schedule. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands executed for a replication schedule. @since: API v4 """ |
params = {
'limit': limit,
'offset': offset,
}
if view:
params['view'] = view
return self._get("replications/%s/history" % schedule_id,
ApiReplicationCommand, True, params=params, api_version=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger_replication_schedule(self, schedule_id, dry_run=False):
""" Trigger replication immediately. Start and end dates on the schedule will be ignored. @param schedule_id: The id of the schedule to trigger. @param dry_run: Whether to execute a dry run. @return: The command corresponding to the replication job. @since: API v3 """ |
return self._post("replications/%s/run" % schedule_id, ApiCommand,
params=dict(dryRun=dry_run),
api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_snapshot_policies(self, view=None):
""" Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6 """ |
return self._get("snapshots/policies", ApiSnapshotPolicy, True,
params=view and dict(view=view) or None, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_snapshot_policy(self, name, view=None):
""" Retrieve a single snapshot policy. @param name: The name of the snapshot policy to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: The requested snapshot policy. @since: API v6 """ |
return self._get("snapshots/policies/%s" % name, ApiSnapshotPolicy,
params=view and dict(view=view) or None, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_snapshot_policy(self, name, policy):
""" Update a snapshot policy. @param name: The name of the snapshot policy to update. @param policy: The modified snapshot policy. @return: The updated snapshot policy. @since: API v6 """ |
return self._put("snapshots/policies/%s" % name, ApiSnapshotPolicy, data=policy,
api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_snapshot_command_history(self, name, limit=20, offset=0, view=None):
""" Retrieve a list of commands triggered by a snapshot policy. @param name: The name of the snapshot policy. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands triggered by a snapshot policy. @since: API v6 """ |
params = {
'limit': limit,
'offset': offset,
}
if view:
params['view'] = view
return self._get("snapshots/policies/%s/history" % name, ApiSnapshotCommand, True,
params=params, api_version=6) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_config(self, config):
""" Set the service configuration. @param config: A dictionary of config key/value """ |
if self.config is None:
self.config = { }
self.config.update(config_to_api_list(config)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_role_type_info(self, role_type, config):
""" Add a role type setup info. @param role_type: Role type @param config: A dictionary of role type configuration """ |
rt_config = config_to_api_list(config)
rt_config['roleType'] = role_type
if self.config is None:
self.config = { }
if not self.config.has_key(ROLETYPES_CFG_KEY):
self.config[ROLETYPES_CFG_KEY] = [ ]
self.config[ROLETYPES_CFG_KEY].append(rt_config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_role_info(self, role_name, role_type, host_id, config=None):
""" Add a role info. The role will be created along with the service setup. @param role_name: Role name @param role_type: Role type @param host_id: The host where the role should run @param config: (Optional) A dictionary of role config values """ |
if self.roles is None:
self.roles = [ ]
api_config_list = config is not None and config_to_api_list(config) or None
self.roles.append({
'name' : role_name,
'type' : role_type,
'hostRef' : { 'hostId' : host_id },
'config' : api_config_list }) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_host(resource_root, host_id, name, ipaddr, rack_id=None):
""" Create a host @param resource_root: The root Resource object. @param host_id: Host id @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None @return: An ApiHost object """ |
apihost = ApiHost(resource_root, host_id, name, ipaddr, rack_id)
return call(resource_root.post, HOSTS_PATH, ApiHost, True, data=[apihost])[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_hosts(resource_root, view=None):
""" Get all hosts @param resource_root: The root Resource object. @return: A list of ApiHost objects. """ |
return call(resource_root.get, HOSTS_PATH, ApiHost, True,
params=view and dict(view=view) or None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_maintenance_mode(self):
""" Put the host in maintenance mode. @return: Reference to the completed command. @since: API v2 """ |
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(get_host(self._get_resource_root(), self.hostId))
return cmd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate_roles(self, role_names_to_migrate, destination_host_id, clear_stale_role_data):
""" Migrate roles from this host to a different host. Currently, this command applies only to HDFS NameNode, JournalNode, and Failover Controller roles. In order to migrate these roles: - HDFS High Availability must be enabled, using quorum-based storage. - HDFS must not be configured to use a federated nameservice. I{B{Migrating a NameNode role requires cluster downtime.}} HDFS, along with all of its dependent services, will be stopped at the beginning of the migration process, and restarted at its conclusion. If the active NameNode is selected for migration, a manual failover will be performed before the role is migrated. The role will remain in standby mode after the migration is complete. When migrating a NameNode role, the co-located Failover Controller role must be migrated as well. The Failover Controller role name must be included in the list of role names to migrate specified in the arguments to this command (it will not be included implicitly). This command does not allow a Failover Controller role to be moved by itself, although it is possible to move a JournalNode independently. @param role_names_to_migrate: list of role names to migrate. @param destination_host_id: the id of the host to which the roles should be migrated. @param clear_stale_role_data: true to delete existing stale role data, if any. For example, when migrating a NameNode, if the destination host has stale data in the NameNode data directories (possibly because a NameNode role was previously located there), this stale data will be deleted before migrating the role. @return: Reference to the submitted command. @since: API v10 """ |
args = dict(
roleNamesToMigrate = role_names_to_migrate,
destinationHostId = destination_host_id,
clearStaleRoleData = clear_stale_role_data)
return self._cmd('migrateRoles', data=args, api_version=10) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_host_map(root):
''' Gets a mapping between CM hostId and Nagios host information
The key is the CM hostId
The value is an object containing the Nagios hostname and host address
'''
hosts_map = {}
for host in root.get_all_hosts():
hosts_map[host.hostId] = {"hostname": NAGIOS_HOSTNAME_FORMAT % (host.hostname,),
"address": host.ipAddress}
''' Also define "virtual hosts" for the CM clusters- they will be the hosts
to which CM services are mapped
'''
for cluster in root.get_all_clusters():
hosts_map[cluster.name] = {"hostname": cluster.name,
"address": quote(cluster.name)}
hosts_map[CM_DUMMY_HOST] = {"hostname": CM_DUMMY_HOST,
"address": CM_DUMMY_HOST}
return hosts_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_services(root, hosts_map, view=None):
''' Gets a list of objects representing the Nagios services.
Each object contains the Nagios hostname, service name, service display
name, and service health summary.
'''
services_list = []
mgmt_service = root.get_cloudera_manager().get_service()
services_list.append({"hostname": CM_DUMMY_HOST,
"name": mgmt_service.name,
"display_name": "CM Managed Service: %s" % (mgmt_service.name,),
"status": get_status(mgmt_service),
"url": mgmt_service.serviceUrl,
"health_summary": mgmt_service.healthSummary})
for cm_role in root.get_cloudera_manager().get_service().get_all_roles(view):
services_list.append({"hostname": hosts_map[cm_role.hostRef.hostId]["hostname"],
"name": cm_role.name,
"display_name": "CM Management Service: %s" % (cm_role.name,),
"status": get_status(cm_role),
"url": cm_role.roleUrl,
"health_summary": cm_role.healthSummary})
for cm_host in root.get_all_hosts(view):
services_list.append({"hostname": hosts_map[cm_host.hostId]["hostname"],
"name": "cm-host-%s" % (cm_host.hostname,),
"display_name": "CM Managed Host: %s" % (cm_host.hostname,),
"status": get_status(cm_host),
"url": cm_host.hostUrl,
"health_summary": cm_host.healthSummary})
for cluster in root.get_all_clusters(view):
for service in cluster.get_all_services(view):
services_list.append({"hostname": cluster.name,
"name": service.name,
"display_name": "CM Managed Service: %s" % (service.name,),
"status": get_status(service),
"url": service.serviceUrl,
"health_summary": service.healthSummary})
for role in service.get_all_roles(view):
services_list.append({"hostname": hosts_map[role.hostRef.hostId]["hostname"],
"name": role.name,
"display_name": "%s:%s" % (cluster.name, role.name,),
"status": get_status(role),
"url": role.roleUrl,
"health_summary": role.healthSummary})
return services_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file '%s'.\n"
"Make sure that the file exists and is writable." % (cmd_file,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invoke(self, method, relpath=None, params=None, data=None, headers=None):
""" Invoke an API method. @return: Raw body or JSON dictionary (if response content type is JSON). """ |
path = self._join_uri(relpath)
resp = self._client.execute(method,
path,
params=params,
data=data,
headers=headers)
try:
body = resp.read()
except Exception, ex:
raise Exception("Command '%s %s' failed: %s" %
(method, path, ex))
self._client.logger.debug(
"%s Got response: %s%s" %
(method, body[:32], len(body) > 32 and "..." or ""))
# Is the response application/json?
if len(body) != 0 and \
resp.info().getmaintype() == "application" and \
resp.info().getsubtype() == "json":
try:
json_dict = json.loads(body)
return json_dict
except Exception, ex:
self._client.logger.exception('JSON decode error: %s' % (body,))
raise ex
else:
return body |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_host_template(resource_root, name, cluster_name):
""" Create a host template. @param resource_root: The root Resource object. @param name: Host template name @param cluster_name: Cluster name @return: An ApiHostTemplate object for the created host template. @since: API v3 """ |
apitemplate = ApiHostTemplate(resource_root, name, [])
return call(resource_root.post,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, data=[apitemplate], api_version=3)[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_host_template(resource_root, name, cluster_name):
""" Lookup a host template by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: An ApiHostTemplate object. @since: API v3 """ |
return call(resource_root.get,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, api_version=3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_host_templates(resource_root, cluster_name="default"):
""" Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3 """ |
return call(resource_root.get,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, api_version=3) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.