repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dswah/pyGAM | pygam/terms.py | TermList.info | def info(self):
"""get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list
"""
info = {'term_type': 'term_list', 'verbose': self.verbose}
info.update({'terms':[term.info for term in self._terms]})
return info | python | def info(self):
"""get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list
"""
info = {'term_type': 'term_list', 'verbose': self.verbose}
info.update({'terms':[term.info for term in self._terms]})
return info | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"{",
"'term_type'",
":",
"'term_list'",
",",
"'verbose'",
":",
"self",
".",
"verbose",
"}",
"info",
".",
"update",
"(",
"{",
"'terms'",
":",
"[",
"term",
".",
"info",
"for",
"term",
"in",
"self",
"... | get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list | [
"get",
"information",
"about",
"the",
"terms",
"in",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1572-L1584 | train | 220,500 |
dswah/pyGAM | pygam/terms.py | TermList.build_from_info | def build_from_info(cls, info):
"""build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance
"""
info = deepcopy(info)
terms = []
for term_info in info['terms']:
terms.append(Term.build_from_info(term_info))
return cls(*terms) | python | def build_from_info(cls, info):
"""build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance
"""
info = deepcopy(info)
terms = []
for term_info in info['terms']:
terms.append(Term.build_from_info(term_info))
return cls(*terms) | [
"def",
"build_from_info",
"(",
"cls",
",",
"info",
")",
":",
"info",
"=",
"deepcopy",
"(",
"info",
")",
"terms",
"=",
"[",
"]",
"for",
"term_info",
"in",
"info",
"[",
"'terms'",
"]",
":",
"terms",
".",
"append",
"(",
"Term",
".",
"build_from_info",
"... | build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance | [
"build",
"a",
"TermList",
"instance",
"from",
"a",
"dict"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1587-L1605 | train | 220,501 |
dswah/pyGAM | pygam/terms.py | TermList.pop | def pop(self, i=None):
"""remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term
"""
if i == None:
i = len(self) - 1
if i >= len(self._terms) or i < 0:
raise ValueError('requested pop {}th term, but found only {} terms'\
.format(i, len(self._terms)))
term = self._terms[i]
self._terms = self._terms[:i] + self._terms[i+1:]
return term | python | def pop(self, i=None):
"""remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term
"""
if i == None:
i = len(self) - 1
if i >= len(self._terms) or i < 0:
raise ValueError('requested pop {}th term, but found only {} terms'\
.format(i, len(self._terms)))
term = self._terms[i]
self._terms = self._terms[:i] + self._terms[i+1:]
return term | [
"def",
"pop",
"(",
"self",
",",
"i",
"=",
"None",
")",
":",
"if",
"i",
"==",
"None",
":",
"i",
"=",
"len",
"(",
"self",
")",
"-",
"1",
"if",
"i",
">=",
"len",
"(",
"self",
".",
"_terms",
")",
"or",
"i",
"<",
"0",
":",
"raise",
"ValueError",... | remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term | [
"remove",
"the",
"ith",
"term",
"from",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1632-L1655 | train | 220,502 |
dswah/pyGAM | pygam/terms.py | TermList.get_coef_indices | def get_coef_indices(self, i=-1):
"""get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers
"""
if i == -1:
return list(range(self.n_coefs))
if i >= len(self._terms):
raise ValueError('requested {}th term, but found only {} terms'\
.format(i, len(self._terms)))
start = 0
for term in self._terms[:i]:
start += term.n_coefs
stop = start + self._terms[i].n_coefs
return list(range(start, stop)) | python | def get_coef_indices(self, i=-1):
"""get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers
"""
if i == -1:
return list(range(self.n_coefs))
if i >= len(self._terms):
raise ValueError('requested {}th term, but found only {} terms'\
.format(i, len(self._terms)))
start = 0
for term in self._terms[:i]:
start += term.n_coefs
stop = start + self._terms[i].n_coefs
return list(range(start, stop)) | [
"def",
"get_coef_indices",
"(",
"self",
",",
"i",
"=",
"-",
"1",
")",
":",
"if",
"i",
"==",
"-",
"1",
":",
"return",
"list",
"(",
"range",
"(",
"self",
".",
"n_coefs",
")",
")",
"if",
"i",
">=",
"len",
"(",
"self",
".",
"_terms",
")",
":",
"r... | get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers | [
"get",
"the",
"indices",
"for",
"the",
"coefficients",
"of",
"a",
"term",
"in",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1672-L1696 | train | 220,503 |
thoughtworksarts/EmoPy | EmoPy/src/csv_data_loader.py | CSVDataLoader.load_data | def load_data(self):
"""
Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data.
"""
print('Extracting training data from csv...')
images = list()
labels = list()
emotion_index_map = dict()
with open(self.datapath) as csv_file:
reader = csv.reader(csv_file, delimiter=',', quotechar='"')
for row in reader:
label_class = row[self.csv_label_col]
if label_class not in self.target_emotion_map.keys():
continue
label_class = self.target_emotion_map[label_class]
if label_class not in emotion_index_map.keys():
emotion_index_map[label_class] = len(emotion_index_map.keys())
labels.append(label_class)
image = np.asarray([int(pixel) for pixel in row[self.csv_image_col].split(' ')], dtype=np.uint8).reshape(self.image_dimensions)
image = self._reshape(image)
images.append(image)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | python | def load_data(self):
"""
Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data.
"""
print('Extracting training data from csv...')
images = list()
labels = list()
emotion_index_map = dict()
with open(self.datapath) as csv_file:
reader = csv.reader(csv_file, delimiter=',', quotechar='"')
for row in reader:
label_class = row[self.csv_label_col]
if label_class not in self.target_emotion_map.keys():
continue
label_class = self.target_emotion_map[label_class]
if label_class not in emotion_index_map.keys():
emotion_index_map[label_class] = len(emotion_index_map.keys())
labels.append(label_class)
image = np.asarray([int(pixel) for pixel in row[self.csv_image_col].split(' ')], dtype=np.uint8).reshape(self.image_dimensions)
image = self._reshape(image)
images.append(image)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | [
"def",
"load_data",
"(",
"self",
")",
":",
"print",
"(",
"'Extracting training data from csv...'",
")",
"images",
"=",
"list",
"(",
")",
"labels",
"=",
"list",
"(",
")",
"emotion_index_map",
"=",
"dict",
"(",
")",
"with",
"open",
"(",
"self",
".",
"datapat... | Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data. | [
"Loads",
"image",
"and",
"label",
"data",
"from",
"specified",
"csv",
"file",
"path",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/csv_data_loader.py#L26-L54 | train | 220,504 |
thoughtworksarts/EmoPy | EmoPy/src/data_loader.py | _DataLoader._load_dataset | def _load_dataset(self, images, labels, emotion_index_map):
"""
Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data.
"""
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=self.validation_split, random_state=42, stratify=labels)
dataset = Dataset(train_images, test_images, train_labels, test_labels, emotion_index_map, self.time_delay)
return dataset | python | def _load_dataset(self, images, labels, emotion_index_map):
"""
Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data.
"""
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=self.validation_split, random_state=42, stratify=labels)
dataset = Dataset(train_images, test_images, train_labels, test_labels, emotion_index_map, self.time_delay)
return dataset | [
"def",
"_load_dataset",
"(",
"self",
",",
"images",
",",
"labels",
",",
"emotion_index_map",
")",
":",
"train_images",
",",
"test_images",
",",
"train_labels",
",",
"test_labels",
"=",
"train_test_split",
"(",
"images",
",",
"labels",
",",
"test_size",
"=",
"s... | Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data. | [
"Loads",
"Dataset",
"object",
"with",
"images",
"labels",
"and",
"other",
"data",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/data_loader.py#L27-L39 | train | 220,505 |
thoughtworksarts/EmoPy | EmoPy/src/directory_data_loader.py | DirectoryDataLoader.load_data | def load_data(self):
"""
Loads image and label data from specified directory path.
:return: Dataset object containing image and label data.
"""
images = list()
labels = list()
emotion_index_map = dict()
label_directories = [dir for dir in os.listdir(self.datapath) if not dir.startswith('.')]
for label_directory in label_directories:
if self.target_emotion_map:
if label_directory not in self.target_emotion_map.keys(): continue
self._add_new_label_to_map(label_directory, emotion_index_map)
label_directory_path = self.datapath + '/' + label_directory
if self.time_delay:
self._load_series_for_single_emotion_directory(images, label_directory, label_directory_path, labels)
else:
image_files = [image_file for image_file in os.listdir(label_directory_path) if not image_file.startswith('.')]
self._load_images_from_directory_to_array(image_files, images, label_directory, label_directory_path, labels)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | python | def load_data(self):
"""
Loads image and label data from specified directory path.
:return: Dataset object containing image and label data.
"""
images = list()
labels = list()
emotion_index_map = dict()
label_directories = [dir for dir in os.listdir(self.datapath) if not dir.startswith('.')]
for label_directory in label_directories:
if self.target_emotion_map:
if label_directory not in self.target_emotion_map.keys(): continue
self._add_new_label_to_map(label_directory, emotion_index_map)
label_directory_path = self.datapath + '/' + label_directory
if self.time_delay:
self._load_series_for_single_emotion_directory(images, label_directory, label_directory_path, labels)
else:
image_files = [image_file for image_file in os.listdir(label_directory_path) if not image_file.startswith('.')]
self._load_images_from_directory_to_array(image_files, images, label_directory, label_directory_path, labels)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | [
"def",
"load_data",
"(",
"self",
")",
":",
"images",
"=",
"list",
"(",
")",
"labels",
"=",
"list",
"(",
")",
"emotion_index_map",
"=",
"dict",
"(",
")",
"label_directories",
"=",
"[",
"dir",
"for",
"dir",
"in",
"os",
".",
"listdir",
"(",
"self",
".",... | Loads image and label data from specified directory path.
:return: Dataset object containing image and label data. | [
"Loads",
"image",
"and",
"label",
"data",
"from",
"specified",
"directory",
"path",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/directory_data_loader.py#L23-L47 | train | 220,506 |
thoughtworksarts/EmoPy | EmoPy/src/directory_data_loader.py | DirectoryDataLoader._check_directory_arguments | def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.time_delay:
if self.time_delay < 1:
raise ValueError('Time step argument must be greater than 0, but gave: %i' % self.time_delay)
if not isinstance(self.time_delay, int):
raise ValueError('Time step argument must be an integer, but gave: %s' % str(self.time_delay)) | python | def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.time_delay:
if self.time_delay < 1:
raise ValueError('Time step argument must be greater than 0, but gave: %i' % self.time_delay)
if not isinstance(self.time_delay, int):
raise ValueError('Time step argument must be an integer, but gave: %s' % str(self.time_delay)) | [
"def",
"_check_directory_arguments",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"datapath",
")",
":",
"raise",
"(",
"NotADirectoryError",
"(",
"'Directory does not exist: %s'",
"%",
"self",
".",
"datapath",
")",
")... | Validates arguments for loading from directories, including static image and time series directories. | [
"Validates",
"arguments",
"for",
"loading",
"from",
"directories",
"including",
"static",
"image",
"and",
"time",
"series",
"directories",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/directory_data_loader.py#L86-L96 | train | 220,507 |
thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel.predict | def predict(self, image_file):
"""
Predicts discrete emotion for given image.
:param images: image file (jpg or png format)
"""
image = misc.imread(image_file)
gray_image = image
if len(image.shape) > 2:
gray_image = cv2.cvtColor(image, code=cv2.COLOR_BGR2GRAY)
resized_image = cv2.resize(gray_image, self.target_dimensions, interpolation=cv2.INTER_LINEAR)
final_image = np.array([np.array([resized_image]).reshape(list(self.target_dimensions)+[self.channels])])
prediction = self.model.predict(final_image)
# Return the dominant expression
dominant_expression = self._print_prediction(prediction[0])
return dominant_expression | python | def predict(self, image_file):
"""
Predicts discrete emotion for given image.
:param images: image file (jpg or png format)
"""
image = misc.imread(image_file)
gray_image = image
if len(image.shape) > 2:
gray_image = cv2.cvtColor(image, code=cv2.COLOR_BGR2GRAY)
resized_image = cv2.resize(gray_image, self.target_dimensions, interpolation=cv2.INTER_LINEAR)
final_image = np.array([np.array([resized_image]).reshape(list(self.target_dimensions)+[self.channels])])
prediction = self.model.predict(final_image)
# Return the dominant expression
dominant_expression = self._print_prediction(prediction[0])
return dominant_expression | [
"def",
"predict",
"(",
"self",
",",
"image_file",
")",
":",
"image",
"=",
"misc",
".",
"imread",
"(",
"image_file",
")",
"gray_image",
"=",
"image",
"if",
"len",
"(",
"image",
".",
"shape",
")",
">",
"2",
":",
"gray_image",
"=",
"cv2",
".",
"cvtColor... | Predicts discrete emotion for given image.
:param images: image file (jpg or png format) | [
"Predicts",
"discrete",
"emotion",
"for",
"given",
"image",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L47-L62 | train | 220,508 |
thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel._check_emotion_set_is_supported | def _check_emotion_set_is_supported(self):
"""
Validates set of user-supplied target emotions.
"""
supported_emotion_subsets = [
set(['anger', 'fear', 'surprise', 'calm']),
set(['happiness', 'disgust', 'surprise']),
set(['anger', 'fear', 'surprise']),
set(['anger', 'fear', 'calm']),
set(['anger', 'happiness', 'calm']),
set(['anger', 'fear', 'disgust']),
set(['calm', 'disgust', 'surprise']),
set(['sadness', 'disgust', 'surprise']),
set(['anger', 'happiness'])
]
if not set(self.target_emotions) in supported_emotion_subsets:
error_string = 'Target emotions must be a supported subset. '
error_string += 'Choose from one of the following emotion subset: \n'
possible_subset_string = ''
for emotion_set in supported_emotion_subsets:
possible_subset_string += ', '.join(emotion_set)
possible_subset_string += '\n'
error_string += possible_subset_string
raise ValueError(error_string) | python | def _check_emotion_set_is_supported(self):
"""
Validates set of user-supplied target emotions.
"""
supported_emotion_subsets = [
set(['anger', 'fear', 'surprise', 'calm']),
set(['happiness', 'disgust', 'surprise']),
set(['anger', 'fear', 'surprise']),
set(['anger', 'fear', 'calm']),
set(['anger', 'happiness', 'calm']),
set(['anger', 'fear', 'disgust']),
set(['calm', 'disgust', 'surprise']),
set(['sadness', 'disgust', 'surprise']),
set(['anger', 'happiness'])
]
if not set(self.target_emotions) in supported_emotion_subsets:
error_string = 'Target emotions must be a supported subset. '
error_string += 'Choose from one of the following emotion subset: \n'
possible_subset_string = ''
for emotion_set in supported_emotion_subsets:
possible_subset_string += ', '.join(emotion_set)
possible_subset_string += '\n'
error_string += possible_subset_string
raise ValueError(error_string) | [
"def",
"_check_emotion_set_is_supported",
"(",
"self",
")",
":",
"supported_emotion_subsets",
"=",
"[",
"set",
"(",
"[",
"'anger'",
",",
"'fear'",
",",
"'surprise'",
",",
"'calm'",
"]",
")",
",",
"set",
"(",
"[",
"'happiness'",
",",
"'disgust'",
",",
"'surpr... | Validates set of user-supplied target emotions. | [
"Validates",
"set",
"of",
"user",
"-",
"supplied",
"target",
"emotions",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L64-L87 | train | 220,509 |
thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel._choose_model_from_target_emotions | def _choose_model_from_target_emotions(self):
"""
Initializes pre-trained deep learning model for the set of target emotions supplied by user.
"""
model_indices = [self.emotion_index_map[emotion] for emotion in self.target_emotions]
sorted_indices = [str(idx) for idx in sorted(model_indices)]
model_suffix = ''.join(sorted_indices)
#Modify the path to choose the model file and the emotion map that you want to use
model_file = 'models/conv_model_%s.hdf5' % model_suffix
emotion_map_file = 'models/conv_emotion_map_%s.json' % model_suffix
emotion_map = json.loads(open(resource_filename('EmoPy', emotion_map_file)).read())
return load_model(resource_filename('EmoPy', model_file)), emotion_map | python | def _choose_model_from_target_emotions(self):
"""
Initializes pre-trained deep learning model for the set of target emotions supplied by user.
"""
model_indices = [self.emotion_index_map[emotion] for emotion in self.target_emotions]
sorted_indices = [str(idx) for idx in sorted(model_indices)]
model_suffix = ''.join(sorted_indices)
#Modify the path to choose the model file and the emotion map that you want to use
model_file = 'models/conv_model_%s.hdf5' % model_suffix
emotion_map_file = 'models/conv_emotion_map_%s.json' % model_suffix
emotion_map = json.loads(open(resource_filename('EmoPy', emotion_map_file)).read())
return load_model(resource_filename('EmoPy', model_file)), emotion_map | [
"def",
"_choose_model_from_target_emotions",
"(",
"self",
")",
":",
"model_indices",
"=",
"[",
"self",
".",
"emotion_index_map",
"[",
"emotion",
"]",
"for",
"emotion",
"in",
"self",
".",
"target_emotions",
"]",
"sorted_indices",
"=",
"[",
"str",
"(",
"idx",
")... | Initializes pre-trained deep learning model for the set of target emotions supplied by user. | [
"Initializes",
"pre",
"-",
"trained",
"deep",
"learning",
"model",
"for",
"the",
"set",
"of",
"target",
"emotions",
"supplied",
"by",
"user",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L89-L100 | train | 220,510 |
thoughtworksarts/EmoPy | EmoPy/library/image.py | apply_transform | def apply_transform(sample,
transform_matrix,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input.
"""
if sample.ndim == 4:
channel_axis = channel_axis - 1
transformed_frames = [transform(frame, transform_matrix, channel_axis, fill_mode, cval) for frame in sample]
return np.stack(transformed_frames, axis=0)
if sample.ndim == 3:
return transform(sample, transform_matrix, channel_axis, fill_mode, cval) | python | def apply_transform(sample,
transform_matrix,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input.
"""
if sample.ndim == 4:
channel_axis = channel_axis - 1
transformed_frames = [transform(frame, transform_matrix, channel_axis, fill_mode, cval) for frame in sample]
return np.stack(transformed_frames, axis=0)
if sample.ndim == 3:
return transform(sample, transform_matrix, channel_axis, fill_mode, cval) | [
"def",
"apply_transform",
"(",
"sample",
",",
"transform_matrix",
",",
"channel_axis",
"=",
"0",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
")",
":",
"if",
"sample",
".",
"ndim",
"==",
"4",
":",
"channel_axis",
"=",
"channel_axis",
"-",
... | Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input. | [
"Apply",
"the",
"image",
"transformation",
"specified",
"by",
"a",
"matrix",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L75-L101 | train | 220,511 |
thoughtworksarts/EmoPy | EmoPy/library/image.py | ImageDataGenerator.standardize | def standardize(self, x):
"""Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np.std(x, keepdims=True) + 1e-7
if self.featurewise_center:
if self.mean is not None:
x -= self.mean
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_center`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.featurewise_std_normalization:
if self.std is not None:
x /= (self.std + 1e-7)
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_std_normalization`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.zca_whitening:
if self.principal_components is not None:
flatx = np.reshape(x, (-1, np.prod(x.shape[-3:])))
whitex = np.dot(flatx, self.principal_components)
x = np.reshape(whitex, x.shape)
else:
warnings.warn('This ImageDataGenerator specifies '
'`zca_whitening`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
return x | python | def standardize(self, x):
"""Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np.std(x, keepdims=True) + 1e-7
if self.featurewise_center:
if self.mean is not None:
x -= self.mean
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_center`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.featurewise_std_normalization:
if self.std is not None:
x /= (self.std + 1e-7)
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_std_normalization`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.zca_whitening:
if self.principal_components is not None:
flatx = np.reshape(x, (-1, np.prod(x.shape[-3:])))
whitex = np.dot(flatx, self.principal_components)
x = np.reshape(whitex, x.shape)
else:
warnings.warn('This ImageDataGenerator specifies '
'`zca_whitening`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
return x | [
"def",
"standardize",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"preprocessing_function",
":",
"x",
"=",
"self",
".",
"preprocessing_function",
"(",
"x",
")",
"if",
"self",
".",
"rescale",
":",
"x",
"*=",
"self",
".",
"rescale",
"if",
"self",... | Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized. | [
"Apply",
"the",
"normalization",
"configuration",
"to",
"a",
"batch",
"of",
"inputs",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L247-L291 | train | 220,512 |
thoughtworksarts/EmoPy | EmoPy/library/image.py | ImageDataGenerator.fit | def fit(self, x,
augment=False,
rounds=1,
seed=None):
"""Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`.
"""
x = np.asarray(x, dtype=K.floatx())
if x.shape[self.channel_axis] not in {1, 3, 4}:
warnings.warn(
'Expected input to be images (as Numpy array) '
'following the data format convention "' + self.data_format + '" '
'(channels on axis ' + str(
self.channel_axis) + '), i.e. expected '
'either 1, 3 or 4 channels on axis ' + str(self.channel_axis) + '. '
'However, it was passed an array with shape ' + str(
x.shape) +
' (' + str(x.shape[self.channel_axis]) + ' channels).')
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if augment:
ax = np.zeros(tuple([rounds * x.shape[0]] + list(x.shape)[1:]), dtype=K.floatx())
for r in range(rounds):
for i in range(x.shape[0]):
ax[i + r * x.shape[0]] = self.random_transform(x[i])
x = ax
if self.featurewise_center:
self.mean = np.mean(x, axis=0)
x -= self.mean
if self.featurewise_std_normalization:
self.std = np.std(x, axis=0)
x /= (self.std + K.epsilon())
if self.zca_whitening:
flat_x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))
sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]
u, s, _ = linalg.svd(sigma)
self.principal_components = np.dot(np.dot(u, np.diag(1. / np.sqrt(s + self.zca_epsilon))), u.T) | python | def fit(self, x,
augment=False,
rounds=1,
seed=None):
"""Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`.
"""
x = np.asarray(x, dtype=K.floatx())
if x.shape[self.channel_axis] not in {1, 3, 4}:
warnings.warn(
'Expected input to be images (as Numpy array) '
'following the data format convention "' + self.data_format + '" '
'(channels on axis ' + str(
self.channel_axis) + '), i.e. expected '
'either 1, 3 or 4 channels on axis ' + str(self.channel_axis) + '. '
'However, it was passed an array with shape ' + str(
x.shape) +
' (' + str(x.shape[self.channel_axis]) + ' channels).')
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if augment:
ax = np.zeros(tuple([rounds * x.shape[0]] + list(x.shape)[1:]), dtype=K.floatx())
for r in range(rounds):
for i in range(x.shape[0]):
ax[i + r * x.shape[0]] = self.random_transform(x[i])
x = ax
if self.featurewise_center:
self.mean = np.mean(x, axis=0)
x -= self.mean
if self.featurewise_std_normalization:
self.std = np.std(x, axis=0)
x /= (self.std + K.epsilon())
if self.zca_whitening:
flat_x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))
sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]
u, s, _ = linalg.svd(sigma)
self.principal_components = np.dot(np.dot(u, np.diag(1. / np.sqrt(s + self.zca_epsilon))), u.T) | [
"def",
"fit",
"(",
"self",
",",
"x",
",",
"augment",
"=",
"False",
",",
"rounds",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"K",
".",
"floatx",
"(",
")",
")",
"if",
"x",
".",
... | Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`. | [
"Fits",
"internal",
"statistics",
"to",
"some",
"sample",
"data",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L404-L461 | train | 220,513 |
thoughtworksarts/EmoPy | EmoPy/library/image.py | NumpyArrayIterator.next | def next(self):
"""For python 2.x.
# Returns
The next batch.
"""
# Keeps under lock only the mechanism which advances
# the indexing of each batch.
with self.lock:
index_array = next(self.index_generator)
# The transformation of images is not under thread lock
# so it can be done in parallel
return self._get_batches_of_transformed_samples(index_array) | python | def next(self):
"""For python 2.x.
# Returns
The next batch.
"""
# Keeps under lock only the mechanism which advances
# the indexing of each batch.
with self.lock:
index_array = next(self.index_generator)
# The transformation of images is not under thread lock
# so it can be done in parallel
return self._get_batches_of_transformed_samples(index_array) | [
"def",
"next",
"(",
"self",
")",
":",
"# Keeps under lock only the mechanism which advances",
"# the indexing of each batch.",
"with",
"self",
".",
"lock",
":",
"index_array",
"=",
"next",
"(",
"self",
".",
"index_generator",
")",
"# The transformation of images is not unde... | For python 2.x.
# Returns
The next batch. | [
"For",
"python",
"2",
".",
"x",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L625-L637 | train | 220,514 |
thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | ConvolutionalLstmNN._init_model | def _init_model(self):
"""
Composes all layers of CNN.
"""
model = Sequential()
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=[self.time_delay] + list(self.image_size) + [self.channels],
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=(self.time_delay, self.channels) + self.image_size,
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation))
model.add(BatchNormalization())
model.add(Conv2D(filters=1, kernel_size=self.kernel_size, activation="sigmoid", data_format="channels_last"))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="sigmoid"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of CNN.
"""
model = Sequential()
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=[self.time_delay] + list(self.image_size) + [self.channels],
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=(self.time_delay, self.channels) + self.image_size,
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation))
model.add(BatchNormalization())
model.add(Conv2D(filters=1, kernel_size=self.kernel_size, activation="sigmoid", data_format="channels_last"))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="sigmoid"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"ConvLSTM2D",
"(",
"filters",
"=",
"self",
".",
"filters",
",",
"kernel_size",
"=",
"self",
".",
"kernel_size",
",",
"activation",
"=",
"self",
... | Composes all layers of CNN. | [
"Composes",
"all",
"layers",
"of",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L166-L186 | train | 220,515 |
thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | ConvolutionalNN._init_model | def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Conv2D",
"(",
"input_shape",
"=",
"list",
"(",
"self",
".",
"image_size",
")",
"+",
"[",
"self",
".",
"channels",
"]",
",",
"filters",
"=",
... | Composes all layers of 2D CNN. | [
"Composes",
"all",
"layers",
"of",
"2D",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L232-L252 | train | 220,516 |
thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | TimeDelayConvNN._init_model | def _init_model(self):
"""
Composes all layers of 3D CNN.
"""
model = Sequential()
model.add(Conv3D(input_shape=[self.time_delay] + list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of 3D CNN.
"""
model = Sequential()
model.add(Conv3D(input_shape=[self.time_delay] + list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Conv3D",
"(",
"input_shape",
"=",
"[",
"self",
".",
"time_delay",
"]",
"+",
"list",
"(",
"self",
".",
"image_size",
")",
"+",
"[",
"self",
... | Composes all layers of 3D CNN. | [
"Composes",
"all",
"layers",
"of",
"3D",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L300-L320 | train | 220,517 |
sosreport/sos | sos/plugins/foreman.py | Foreman.build_query_cmd | def build_query_cmd(self, query, csv=False):
"""
Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run
"""
_cmd = "su postgres -c %s"
if not csv:
_dbcmd = "psql foreman -c %s"
else:
_dbcmd = "psql foreman -A -F , -X -c %s"
dbq = _dbcmd % quote(query)
return _cmd % quote(dbq) | python | def build_query_cmd(self, query, csv=False):
"""
Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run
"""
_cmd = "su postgres -c %s"
if not csv:
_dbcmd = "psql foreman -c %s"
else:
_dbcmd = "psql foreman -A -F , -X -c %s"
dbq = _dbcmd % quote(query)
return _cmd % quote(dbq) | [
"def",
"build_query_cmd",
"(",
"self",
",",
"query",
",",
"csv",
"=",
"False",
")",
":",
"_cmd",
"=",
"\"su postgres -c %s\"",
"if",
"not",
"csv",
":",
"_dbcmd",
"=",
"\"psql foreman -c %s\"",
"else",
":",
"_dbcmd",
"=",
"\"psql foreman -A -F , -X -c %s\"",
"dbq... | Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run | [
"Builds",
"the",
"command",
"needed",
"to",
"invoke",
"the",
"pgsql",
"query",
"as",
"the",
"postgres",
"user",
".",
"The",
"query",
"requires",
"significant",
"quoting",
"work",
"to",
"satisfy",
"both",
"the",
"shell",
"and",
"postgres",
"parsing",
"requireme... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/foreman.py#L163-L177 | train | 220,518 |
sosreport/sos | sos/policies/__init__.py | InitSystem.is_enabled | def is_enabled(self, name):
"""Check if given service name is enabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'enabled'
return False | python | def is_enabled(self, name):
"""Check if given service name is enabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'enabled'
return False | [
"def",
"is_enabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'enabled'",
"return",
"False"
] | Check if given service name is enabled | [
"Check",
"if",
"given",
"service",
"name",
"is",
"enabled"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L70-L74 | train | 220,519 |
sosreport/sos | sos/policies/__init__.py | InitSystem.is_disabled | def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | python | def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | [
"def",
"is_disabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'disabled'",
"return",
"False"... | Check if a given service name is disabled | [
"Check",
"if",
"a",
"given",
"service",
"name",
"is",
"disabled"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L76-L80 | train | 220,520 |
sosreport/sos | sos/policies/__init__.py | InitSystem._query_service | def _query_service(self, name):
"""Query an individual service"""
if self.query_cmd:
try:
return sos_get_command_output("%s %s" % (self.query_cmd, name))
except Exception:
return None
return None | python | def _query_service(self, name):
"""Query an individual service"""
if self.query_cmd:
try:
return sos_get_command_output("%s %s" % (self.query_cmd, name))
except Exception:
return None
return None | [
"def",
"_query_service",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"query_cmd",
":",
"try",
":",
"return",
"sos_get_command_output",
"(",
"\"%s %s\"",
"%",
"(",
"self",
".",
"query_cmd",
",",
"name",
")",
")",
"except",
"Exception",
":",
"re... | Query an individual service | [
"Query",
"an",
"individual",
"service"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L106-L113 | train | 220,521 |
sosreport/sos | sos/policies/__init__.py | InitSystem.get_service_status | def get_service_status(self, name):
"""Returns the status for the given service name along with the output
of the query command
"""
svc = self._query_service(name)
if svc is not None:
return {'name': name,
'status': self.parse_query(svc['output']),
'output': svc['output']
}
else:
return {'name': name,
'status': 'missing',
'output': ''
} | python | def get_service_status(self, name):
"""Returns the status for the given service name along with the output
of the query command
"""
svc = self._query_service(name)
if svc is not None:
return {'name': name,
'status': self.parse_query(svc['output']),
'output': svc['output']
}
else:
return {'name': name,
'status': 'missing',
'output': ''
} | [
"def",
"get_service_status",
"(",
"self",
",",
"name",
")",
":",
"svc",
"=",
"self",
".",
"_query_service",
"(",
"name",
")",
"if",
"svc",
"is",
"not",
"None",
":",
"return",
"{",
"'name'",
":",
"name",
",",
"'status'",
":",
"self",
".",
"parse_query",... | Returns the status for the given service name along with the output
of the query command | [
"Returns",
"the",
"status",
"for",
"the",
"given",
"service",
"name",
"along",
"with",
"the",
"output",
"of",
"the",
"query",
"command"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L123-L137 | train | 220,522 |
sosreport/sos | sos/policies/__init__.py | PackageManager.all_pkgs_by_name_regex | def all_pkgs_by_name_regex(self, regex_name, flags=0):
"""
Return a list of packages that match regex_name.
"""
reg = re.compile(regex_name, flags)
return [pkg for pkg in self.all_pkgs().keys() if reg.match(pkg)] | python | def all_pkgs_by_name_regex(self, regex_name, flags=0):
"""
Return a list of packages that match regex_name.
"""
reg = re.compile(regex_name, flags)
return [pkg for pkg in self.all_pkgs().keys() if reg.match(pkg)] | [
"def",
"all_pkgs_by_name_regex",
"(",
"self",
",",
"regex_name",
",",
"flags",
"=",
"0",
")",
":",
"reg",
"=",
"re",
".",
"compile",
"(",
"regex_name",
",",
"flags",
")",
"return",
"[",
"pkg",
"for",
"pkg",
"in",
"self",
".",
"all_pkgs",
"(",
")",
".... | Return a list of packages that match regex_name. | [
"Return",
"a",
"list",
"of",
"packages",
"that",
"match",
"regex_name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L210-L215 | train | 220,523 |
sosreport/sos | sos/policies/__init__.py | PackageManager.pkg_by_name | def pkg_by_name(self, name):
"""
Return a single package that matches name.
"""
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | python | def pkg_by_name(self, name):
"""
Return a single package that matches name.
"""
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | [
"def",
"pkg_by_name",
"(",
"self",
",",
"name",
")",
":",
"pkgmatches",
"=",
"self",
".",
"all_pkgs_by_name",
"(",
"name",
")",
"if",
"(",
"len",
"(",
"pkgmatches",
")",
"!=",
"0",
")",
":",
"return",
"self",
".",
"all_pkgs_by_name",
"(",
"name",
")",
... | Return a single package that matches name. | [
"Return",
"a",
"single",
"package",
"that",
"matches",
"name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L217-L225 | train | 220,524 |
sosreport/sos | sos/policies/__init__.py | PackageManager.all_pkgs | def all_pkgs(self):
"""
Return a list of all packages.
"""
if not self.packages:
self.packages = self.get_pkg_list()
return self.packages | python | def all_pkgs(self):
"""
Return a list of all packages.
"""
if not self.packages:
self.packages = self.get_pkg_list()
return self.packages | [
"def",
"all_pkgs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"packages",
":",
"self",
".",
"packages",
"=",
"self",
".",
"get_pkg_list",
"(",
")",
"return",
"self",
".",
"packages"
] | Return a list of all packages. | [
"Return",
"a",
"list",
"of",
"all",
"packages",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L258-L264 | train | 220,525 |
sosreport/sos | sos/policies/__init__.py | PackageManager.all_files | def all_files(self):
"""
Returns a list of files known by the package manager
"""
if self.files_command and not self.files:
cmd = self.files_command
files = shell_out(cmd, timeout=0, chroot=self.chroot)
self.files = files.splitlines()
return self.files | python | def all_files(self):
"""
Returns a list of files known by the package manager
"""
if self.files_command and not self.files:
cmd = self.files_command
files = shell_out(cmd, timeout=0, chroot=self.chroot)
self.files = files.splitlines()
return self.files | [
"def",
"all_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"files_command",
"and",
"not",
"self",
".",
"files",
":",
"cmd",
"=",
"self",
".",
"files_command",
"files",
"=",
"shell_out",
"(",
"cmd",
",",
"timeout",
"=",
"0",
",",
"chroot",
"=",
"se... | Returns a list of files known by the package manager | [
"Returns",
"a",
"list",
"of",
"files",
"known",
"by",
"the",
"package",
"manager"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L272-L280 | train | 220,526 |
sosreport/sos | sos/policies/__init__.py | PresetDefaults.write | def write(self, presets_path):
"""Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written.
"""
if self.builtin:
raise TypeError("Cannot write built-in preset")
# Make dictionaries of PresetDefaults values
odict = self.opts.dict()
pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}
if not os.path.exists(presets_path):
os.makedirs(presets_path, mode=0o755)
with open(os.path.join(presets_path, self.name), "w") as pfile:
json.dump(pdict, pfile) | python | def write(self, presets_path):
"""Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written.
"""
if self.builtin:
raise TypeError("Cannot write built-in preset")
# Make dictionaries of PresetDefaults values
odict = self.opts.dict()
pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}
if not os.path.exists(presets_path):
os.makedirs(presets_path, mode=0o755)
with open(os.path.join(presets_path, self.name), "w") as pfile:
json.dump(pdict, pfile) | [
"def",
"write",
"(",
"self",
",",
"presets_path",
")",
":",
"if",
"self",
".",
"builtin",
":",
"raise",
"TypeError",
"(",
"\"Cannot write built-in preset\"",
")",
"# Make dictionaries of PresetDefaults values",
"odict",
"=",
"self",
".",
"opts",
".",
"dict",
"(",
... | Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written. | [
"Write",
"this",
"preset",
"to",
"disk",
"in",
"JSON",
"notation",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L374-L391 | train | 220,527 |
sosreport/sos | sos/policies/__init__.py | Policy.get_archive_name | def get_archive_name(self):
"""
This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime().
"""
name = self.get_local_name().split('.')[0]
case = self.case_id
label = self.commons['cmdlineopts'].label
date = ''
rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))
if self.name_pattern == 'legacy':
nstr = "sosreport-{name}{case}{date}"
case = '.' + case if case else ''
date = '-%Y%m%d%H%M%S'
elif self.name_pattern == 'friendly':
nstr = "sosreport-{name}{label}{case}{date}-{rand}"
case = '-' + case if case else ''
label = '-' + label if label else ''
date = '-%Y-%m-%d'
else:
nstr = self.name_pattern
nstr = nstr.format(
name=name,
label=label,
case=case,
date=date,
rand=rand
)
return self.sanitize_filename(time.strftime(nstr)) | python | def get_archive_name(self):
"""
This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime().
"""
name = self.get_local_name().split('.')[0]
case = self.case_id
label = self.commons['cmdlineopts'].label
date = ''
rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))
if self.name_pattern == 'legacy':
nstr = "sosreport-{name}{case}{date}"
case = '.' + case if case else ''
date = '-%Y%m%d%H%M%S'
elif self.name_pattern == 'friendly':
nstr = "sosreport-{name}{label}{case}{date}-{rand}"
case = '-' + case if case else ''
label = '-' + label if label else ''
date = '-%Y-%m-%d'
else:
nstr = self.name_pattern
nstr = nstr.format(
name=name,
label=label,
case=case,
date=date,
rand=rand
)
return self.sanitize_filename(time.strftime(nstr)) | [
"def",
"get_archive_name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"get_local_name",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"case",
"=",
"self",
".",
"case_id",
"label",
"=",
"self",
".",
"commons",
"[",
"'cmdlineopts'",
"]"... | This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime(). | [
"This",
"function",
"should",
"return",
"the",
"filename",
"of",
"the",
"archive",
"without",
"the",
"extension",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L496-L547 | train | 220,528 |
sosreport/sos | sos/policies/__init__.py | Policy.validate_plugin | def validate_plugin(self, plugin_class, experimental=False):
"""
Verifies that the plugin_class should execute under this policy
"""
valid_subclasses = [IndependentPlugin] + self.valid_subclasses
if experimental:
valid_subclasses += [ExperimentalPlugin]
return any(issubclass(plugin_class, class_) for
class_ in valid_subclasses) | python | def validate_plugin(self, plugin_class, experimental=False):
"""
Verifies that the plugin_class should execute under this policy
"""
valid_subclasses = [IndependentPlugin] + self.valid_subclasses
if experimental:
valid_subclasses += [ExperimentalPlugin]
return any(issubclass(plugin_class, class_) for
class_ in valid_subclasses) | [
"def",
"validate_plugin",
"(",
"self",
",",
"plugin_class",
",",
"experimental",
"=",
"False",
")",
":",
"valid_subclasses",
"=",
"[",
"IndependentPlugin",
"]",
"+",
"self",
".",
"valid_subclasses",
"if",
"experimental",
":",
"valid_subclasses",
"+=",
"[",
"Expe... | Verifies that the plugin_class should execute under this policy | [
"Verifies",
"that",
"the",
"plugin_class",
"should",
"execute",
"under",
"this",
"policy"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L591-L599 | train | 220,529 |
sosreport/sos | sos/policies/__init__.py | Policy._print | def _print(self, msg=None, always=False):
"""A wrapper around print that only prints if we are not running in
quiet mode"""
if always or not self.commons['cmdlineopts'].quiet:
if msg:
print_(msg)
else:
print_() | python | def _print(self, msg=None, always=False):
"""A wrapper around print that only prints if we are not running in
quiet mode"""
if always or not self.commons['cmdlineopts'].quiet:
if msg:
print_(msg)
else:
print_() | [
"def",
"_print",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"always",
"=",
"False",
")",
":",
"if",
"always",
"or",
"not",
"self",
".",
"commons",
"[",
"'cmdlineopts'",
"]",
".",
"quiet",
":",
"if",
"msg",
":",
"print_",
"(",
"msg",
")",
"else",
... | A wrapper around print that only prints if we are not running in
quiet mode | [
"A",
"wrapper",
"around",
"print",
"that",
"only",
"prints",
"if",
"we",
"are",
"not",
"running",
"in",
"quiet",
"mode"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L671-L678 | train | 220,530 |
sosreport/sos | sos/policies/__init__.py | Policy.get_msg | def get_msg(self):
"""This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated."""
width = 72
_msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,
'vendor_url': self.vendor_url,
'vendor_text': self.vendor_text,
'tmpdir': self.commons['tmpdir']}
_fmt = ""
for line in _msg.splitlines():
_fmt = _fmt + fill(line, width, replace_whitespace=False) + '\n'
return _fmt | python | def get_msg(self):
"""This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated."""
width = 72
_msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,
'vendor_url': self.vendor_url,
'vendor_text': self.vendor_text,
'tmpdir': self.commons['tmpdir']}
_fmt = ""
for line in _msg.splitlines():
_fmt = _fmt + fill(line, width, replace_whitespace=False) + '\n'
return _fmt | [
"def",
"get_msg",
"(",
"self",
")",
":",
"width",
"=",
"72",
"_msg",
"=",
"self",
".",
"msg",
"%",
"{",
"'distro'",
":",
"self",
".",
"distro",
",",
"'vendor'",
":",
"self",
".",
"vendor",
",",
"'vendor_url'",
":",
"self",
".",
"vendor_url",
",",
"... | This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated. | [
"This",
"method",
"is",
"used",
"to",
"prepare",
"the",
"preamble",
"text",
"to",
"display",
"to",
"the",
"user",
"in",
"non",
"-",
"batch",
"mode",
".",
"If",
"your",
"policy",
"sets",
"self",
".",
"distro",
"that",
"text",
"will",
"be",
"substituted",
... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L680-L693 | train | 220,531 |
sosreport/sos | sos/policies/__init__.py | Policy.register_presets | def register_presets(self, presets, replace=False):
"""Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets.
"""
if replace:
self.presets = {}
self.presets.update(presets) | python | def register_presets(self, presets, replace=False):
"""Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets.
"""
if replace:
self.presets = {}
self.presets.update(presets) | [
"def",
"register_presets",
"(",
"self",
",",
"presets",
",",
"replace",
"=",
"False",
")",
":",
"if",
"replace",
":",
"self",
".",
"presets",
"=",
"{",
"}",
"self",
".",
"presets",
".",
"update",
"(",
"presets",
")"
] | Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets. | [
"Add",
"new",
"presets",
"to",
"this",
"policy",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L695-L711 | train | 220,532 |
sosreport/sos | sos/policies/__init__.py | Policy.find_preset | def find_preset(self, preset):
"""Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile.
"""
# FIXME: allow fuzzy matching?
for match in self.presets.keys():
if match == preset:
return self.presets[match]
return None | python | def find_preset(self, preset):
"""Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile.
"""
# FIXME: allow fuzzy matching?
for match in self.presets.keys():
if match == preset:
return self.presets[match]
return None | [
"def",
"find_preset",
"(",
"self",
",",
"preset",
")",
":",
"# FIXME: allow fuzzy matching?",
"for",
"match",
"in",
"self",
".",
"presets",
".",
"keys",
"(",
")",
":",
"if",
"match",
"==",
"preset",
":",
"return",
"self",
".",
"presets",
"[",
"match",
"]... | Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile. | [
"Find",
"a",
"preset",
"profile",
"matching",
"the",
"specified",
"preset",
"string",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L713-L724 | train | 220,533 |
sosreport/sos | sos/policies/__init__.py | Policy.load_presets | def load_presets(self, presets_path=None):
"""Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets.
"""
presets_path = presets_path or self.presets_path
if not os.path.exists(presets_path):
return
for preset_path in os.listdir(presets_path):
preset_path = os.path.join(presets_path, preset_path)
try:
preset_data = json.load(open(preset_path))
except ValueError:
continue
for preset in preset_data.keys():
pd = PresetDefaults(preset, opts=SoSOptions())
data = preset_data[preset]
pd.desc = data[DESC] if DESC in data else ""
pd.note = data[NOTE] if NOTE in data else ""
if OPTS in data:
for arg in _arg_names:
if arg in data[OPTS]:
setattr(pd.opts, arg, data[OPTS][arg])
pd.builtin = False
self.presets[preset] = pd | python | def load_presets(self, presets_path=None):
"""Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets.
"""
presets_path = presets_path or self.presets_path
if not os.path.exists(presets_path):
return
for preset_path in os.listdir(presets_path):
preset_path = os.path.join(presets_path, preset_path)
try:
preset_data = json.load(open(preset_path))
except ValueError:
continue
for preset in preset_data.keys():
pd = PresetDefaults(preset, opts=SoSOptions())
data = preset_data[preset]
pd.desc = data[DESC] if DESC in data else ""
pd.note = data[NOTE] if NOTE in data else ""
if OPTS in data:
for arg in _arg_names:
if arg in data[OPTS]:
setattr(pd.opts, arg, data[OPTS][arg])
pd.builtin = False
self.presets[preset] = pd | [
"def",
"load_presets",
"(",
"self",
",",
"presets_path",
"=",
"None",
")",
":",
"presets_path",
"=",
"presets_path",
"or",
"self",
".",
"presets_path",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"presets_path",
")",
":",
"return",
"for",
"preset_p... | Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets. | [
"Load",
"presets",
"from",
"disk",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L735-L765 | train | 220,534 |
sosreport/sos | sos/policies/__init__.py | Policy.add_preset | def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
"""
presets_path = self.presets_path
if not name:
raise ValueError("Preset name cannot be empty")
if name in self.presets.keys():
raise ValueError("A preset with name '%s' already exists" % name)
preset = PresetDefaults(name=name, desc=desc, note=note, opts=opts)
preset.builtin = False
self.presets[preset.name] = preset
preset.write(presets_path) | python | def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
"""
presets_path = self.presets_path
if not name:
raise ValueError("Preset name cannot be empty")
if name in self.presets.keys():
raise ValueError("A preset with name '%s' already exists" % name)
preset = PresetDefaults(name=name, desc=desc, note=note, opts=opts)
preset.builtin = False
self.presets[preset.name] = preset
preset.write(presets_path) | [
"def",
"add_preset",
"(",
"self",
",",
"name",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"note",
"=",
"None",
",",
"opts",
"=",
"SoSOptions",
"(",
")",
")",
":",
"presets_path",
"=",
"self",
".",
"presets_path",
"if",
"not",
"name",
":",
"raise",
... | Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add | [
"Add",
"a",
"new",
"on",
"-",
"disk",
"preset",
"and",
"write",
"it",
"to",
"the",
"configured",
"presets",
"path",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L767-L784 | train | 220,535 |
sosreport/sos | sos/policies/__init__.py | LinuxPolicy.lsmod | def lsmod(self):
"""Return a list of kernel module names as strings.
"""
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | python | def lsmod(self):
"""Return a list of kernel module names as strings.
"""
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | [
"def",
"lsmod",
"(",
"self",
")",
":",
"lines",
"=",
"shell_out",
"(",
"\"lsmod\"",
",",
"timeout",
"=",
"0",
")",
".",
"splitlines",
"(",
")",
"return",
"[",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"line",
... | Return a list of kernel module names as strings. | [
"Return",
"a",
"list",
"of",
"kernel",
"module",
"names",
"as",
"strings",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L873-L877 | train | 220,536 |
sosreport/sos | sos/plugins/lvm2.py | Lvm2.do_lvmdump | def do_lvmdump(self, metadata=False):
"""Collects an lvmdump in standard format with optional metadata
archives for each physical volume present.
"""
lvmdump_path = self.get_cmd_output_path(name="lvmdump", make=False)
lvmdump_cmd = "lvmdump %s -d '%s'"
lvmdump_opts = ""
if metadata:
lvmdump_opts = "-a -m"
cmd = lvmdump_cmd % (lvmdump_opts, lvmdump_path)
self.add_cmd_output(cmd, chroot=self.tmp_in_sysroot()) | python | def do_lvmdump(self, metadata=False):
"""Collects an lvmdump in standard format with optional metadata
archives for each physical volume present.
"""
lvmdump_path = self.get_cmd_output_path(name="lvmdump", make=False)
lvmdump_cmd = "lvmdump %s -d '%s'"
lvmdump_opts = ""
if metadata:
lvmdump_opts = "-a -m"
cmd = lvmdump_cmd % (lvmdump_opts, lvmdump_path)
self.add_cmd_output(cmd, chroot=self.tmp_in_sysroot()) | [
"def",
"do_lvmdump",
"(",
"self",
",",
"metadata",
"=",
"False",
")",
":",
"lvmdump_path",
"=",
"self",
".",
"get_cmd_output_path",
"(",
"name",
"=",
"\"lvmdump\"",
",",
"make",
"=",
"False",
")",
"lvmdump_cmd",
"=",
"\"lvmdump %s -d '%s'\"",
"lvmdump_opts",
"... | Collects an lvmdump in standard format with optional metadata
archives for each physical volume present. | [
"Collects",
"an",
"lvmdump",
"in",
"standard",
"format",
"with",
"optional",
"metadata",
"archives",
"for",
"each",
"physical",
"volume",
"present",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/lvm2.py#L24-L37 | train | 220,537 |
sosreport/sos | sos/__init__.py | SoSOptions.__str | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | python | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | [
"def",
"__str",
"(",
"self",
",",
"quote",
"=",
"False",
",",
"sep",
"=",
"\" \"",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"args",
"=",
"prefix",
"arg_fmt",
"=",
"\"=%s\"",
"for",
"arg",
"in",
"_arg_names",
":",
"args",
"+... | Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals | [
"Format",
"a",
"SoSOptions",
"object",
"as",
"a",
"human",
"or",
"machine",
"readable",
"string",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L111-L136 | train | 220,538 |
sosreport/sos | sos/__init__.py | SoSOptions.from_args | def from_args(cls, args):
"""Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions
"""
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | python | def from_args(cls, args):
"""Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions
"""
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | [
"def",
"from_args",
"(",
"cls",
",",
"args",
")",
":",
"opts",
"=",
"SoSOptions",
"(",
")",
"opts",
".",
"_merge_opts",
"(",
"args",
",",
"True",
")",
"return",
"opts"
] | Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions | [
"Initialise",
"a",
"new",
"SoSOptions",
"object",
"from",
"a",
"Namespace",
"obtained",
"by",
"parsing",
"command",
"line",
"arguments",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L201-L211 | train | 220,539 |
sosreport/sos | sos/__init__.py | SoSOptions.merge | def merge(self, src, skip_default=True):
"""Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set.
"""
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | python | def merge(self, src, skip_default=True):
"""Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set.
"""
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | [
"def",
"merge",
"(",
"self",
",",
"src",
",",
"skip_default",
"=",
"True",
")",
":",
"for",
"arg",
"in",
"_arg_names",
":",
"if",
"not",
"hasattr",
"(",
"src",
",",
"arg",
")",
":",
"continue",
"if",
"getattr",
"(",
"src",
",",
"arg",
")",
"is",
... | Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set. | [
"Merge",
"another",
"set",
"of",
"SoSOptions",
"into",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L272-L285 | train | 220,540 |
sosreport/sos | sos/__init__.py | SoSOptions.dict | def dict(self):
"""Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values.
"""
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | python | def dict(self):
"""Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values.
"""
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | [
"def",
"dict",
"(",
"self",
")",
":",
"odict",
"=",
"{",
"}",
"for",
"arg",
"in",
"_arg_names",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"arg",
")",
"# Do not attempt to store preset option values in presets",
"if",
"arg",
"in",
"(",
"'add_preset'",
"... | Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values. | [
"Return",
"this",
"SoSOptions",
"option",
"values",
"as",
"a",
"dictionary",
"of",
"argument",
"name",
"to",
"value",
"mappings",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L287-L300 | train | 220,541 |
sosreport/sos | sos/__init__.py | SoSOptions.to_args | def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | python | def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | [
"def",
"to_args",
"(",
"self",
")",
":",
"def",
"has_value",
"(",
"name",
",",
"value",
")",
":",
"\"\"\" Test for non-null option values.\n \"\"\"",
"null_values",
"=",
"(",
"\"False\"",
",",
"\"None\"",
",",
"\"[]\"",
",",
"'\"\"'",
",",
"\"''\"",
"... | Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]`` | [
"Return",
"command",
"arguments",
"for",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L302-L350 | train | 220,542 |
sosreport/sos | sos/plugins/autofs.py | Autofs.checkdebug | def checkdebug(self):
""" testing if autofs debug has been enabled anywhere
"""
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | python | def checkdebug(self):
""" testing if autofs debug has been enabled anywhere
"""
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | [
"def",
"checkdebug",
"(",
"self",
")",
":",
"# Global debugging",
"opt",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"opt1",
"in",
"opt",
":",
"for",
"opt2",
"in",
"opt1",
".",... | testing if autofs debug has been enabled anywhere | [
"testing",
"if",
"autofs",
"debug",
"has",
"been",
"enabled",
"anywhere"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L24-L34 | train | 220,543 |
sosreport/sos | sos/plugins/autofs.py | Autofs.getdaemondebug | def getdaemondebug(self):
""" capture daemon debug output
"""
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | python | def getdaemondebug(self):
""" capture daemon debug output
"""
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | [
"def",
"getdaemondebug",
"(",
"self",
")",
":",
"debugout",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(daemon.*)\\s+(\\/var\\/log\\/.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"i",
"in",
"debugout",
":",
"return",
"i",
"[",
"1",
"]"
] | capture daemon debug output | [
"capture",
"daemon",
"debug",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L36-L42 | train | 220,544 |
sosreport/sos | sos/plugins/jars.py | Jars.is_jar | def is_jar(path):
"""Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'.
"""
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | python | def is_jar(path):
"""Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'.
"""
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | [
"def",
"is_jar",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"zipfile",
".",
"is_zipfile",
"(",
"path",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"f",
":",
"if",
... | Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'. | [
"Check",
"whether",
"given",
"file",
"is",
"a",
"JAR",
"file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L84-L97 | train | 220,545 |
sosreport/sos | sos/plugins/jars.py | Jars.get_maven_id | def get_maven_id(jar_path):
"""Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there.
"""
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | python | def get_maven_id(jar_path):
"""Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there.
"""
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | [
"def",
"get_maven_id",
"(",
"jar_path",
")",
":",
"props",
"=",
"{",
"}",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"jar_path",
")",
"as",
"f",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"\"META-INF/maven/[^/]+/[^/]+/pom.properties$\"",
")",
"resu... | Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there. | [
"Extract",
"Maven",
"coordinates",
"from",
"a",
"given",
"JAR",
"file",
"if",
"possible",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L100-L127 | train | 220,546 |
sosreport/sos | sos/plugins/jars.py | Jars.get_jar_id | def get_jar_id(jar_path):
"""Compute JAR id.
Returns sha1 hash of a given JAR file.
"""
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | python | def get_jar_id(jar_path):
"""Compute JAR id.
Returns sha1 hash of a given JAR file.
"""
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | [
"def",
"get_jar_id",
"(",
"jar_path",
")",
":",
"jar_id",
"=",
"\"\"",
"try",
":",
"with",
"open",
"(",
"jar_path",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"f",
":",
"m",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"buf",
"in",
"iter",
"(",
"par... | Compute JAR id.
Returns sha1 hash of a given JAR file. | [
"Compute",
"JAR",
"id",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L130-L144 | train | 220,547 |
sosreport/sos | sos/plugins/qpid.py | Qpid.setup | def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | python | def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"amqps_prefix",
"=",
"\"\"",
"# set amqps:// when SSL is used",
"if",
"self",
".",
"get_option",
"(",
"\"ssl\"",
")",
":",
"amqps_prefix",
"=",
"\"amqps://\"",
"# for either present option, add --option=va... | performs data collection for qpid broker | [
"performs",
"data",
"collection",
"for",
"qpid",
"broker"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid.py#L27-L80 | train | 220,548 |
sosreport/sos | sos/sosreport.py | SoSReport._exception | def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | python | def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | [
"def",
"_exception",
"(",
"etype",
",",
"eval_",
",",
"etrace",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'ps1'",
")",
"or",
"not",
"sys",
".",
"stderr",
".",
"isatty",
"(",
")",
":",
"# we are in interactive mode or we don't have a tty-like",
"# device, so... | Wrap exception in debugger if not in tty | [
"Wrap",
"exception",
"in",
"debugger",
"if",
"not",
"in",
"tty"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L404-L416 | train | 220,549 |
sosreport/sos | sos/sosreport.py | SoSReport.add_preset | def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | python | def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | [
"def",
"add_preset",
"(",
"self",
",",
"name",
",",
"desc",
"=",
"\"\"",
",",
"note",
"=",
"\"\"",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
... | Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise | [
"Add",
"a",
"new",
"command",
"line",
"preset",
"for",
"the",
"current",
"options",
"with",
"the",
"specified",
"name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L802-L829 | train | 220,550 |
sosreport/sos | sos/sosreport.py | SoSReport.del_preset | def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | python | def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | [
"def",
"del_preset",
"(",
"self",
",",
"name",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"not",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
"\"Preset '%s' not found\"",
"%",
"name",
")",
"r... | Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise | [
"Delete",
"a",
"named",
"command",
"line",
"preset",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L831-L849 | train | 220,551 |
sosreport/sos | sos/sosreport.py | SoSReport.version | def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | python | def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | [
"def",
"version",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"versions",
".",
"append",
"(",
"\"sosreport: %s\"",
"%",
"__version__",
")",
"for",
"plugname",
",",
"plug",
"in",
"self",
".",
"loaded_plugins",
":",
"versions",
".",
"append",
"(",
"\... | Fetch version information from all plugins and store in the report
version file | [
"Fetch",
"version",
"information",
"from",
"all",
"plugins",
"and",
"store",
"in",
"the",
"report",
"version",
"file"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L949-L960 | train | 220,552 |
sosreport/sos | sos/plugins/navicli.py | Navicli.get_navicli_SP_info | def get_navicli_SP_info(self, SP_address):
""" EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands
"""
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | python | def get_navicli_SP_info(self, SP_address):
""" EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands
"""
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | [
"def",
"get_navicli_SP_info",
"(",
"self",
",",
"SP_address",
")",
":",
"self",
".",
"add_cmd_output",
"(",
"[",
"\"navicli -h %s getall\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spa\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spb\"",
"%",
"SP_... | EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands | [
"EMC",
"Navisphere",
"Host",
"Agent",
"NAVICLI",
"specific",
"information",
"-",
"CLARiiON",
"-",
"commands"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/navicli.py#L41-L60 | train | 220,553 |
sosreport/sos | sos/plugins/origin.py | OpenShiftOrigin.is_static_etcd | def is_static_etcd(self):
'''Determine if we are on a node running etcd'''
return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml")) | python | def is_static_etcd(self):
'''Determine if we are on a node running etcd'''
return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml")) | [
"def",
"is_static_etcd",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"static_pod_dir",
",",
"\"etcd.yaml\"",
")",
")"
] | Determine if we are on a node running etcd | [
"Determine",
"if",
"we",
"are",
"on",
"a",
"node",
"running",
"etcd"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/origin.py#L78-L80 | train | 220,554 |
sosreport/sos | sos/plugins/networking.py | Networking.get_ip_netns | def get_ip_netns(self, ip_netns_file):
"""Returns a list for which items are namespaces in the output of
ip netns stored in the ip_netns_file.
"""
out = []
try:
ip_netns_out = open(ip_netns_file).read()
except IOError:
return out
for line in ip_netns_out.splitlines():
# If there's no namespaces, no need to continue
if line.startswith("Object \"netns\" is unknown") \
or line.isspace() \
or line[:1].isspace():
return out
out.append(line.partition(' ')[0])
return out | python | def get_ip_netns(self, ip_netns_file):
"""Returns a list for which items are namespaces in the output of
ip netns stored in the ip_netns_file.
"""
out = []
try:
ip_netns_out = open(ip_netns_file).read()
except IOError:
return out
for line in ip_netns_out.splitlines():
# If there's no namespaces, no need to continue
if line.startswith("Object \"netns\" is unknown") \
or line.isspace() \
or line[:1].isspace():
return out
out.append(line.partition(' ')[0])
return out | [
"def",
"get_ip_netns",
"(",
"self",
",",
"ip_netns_file",
")",
":",
"out",
"=",
"[",
"]",
"try",
":",
"ip_netns_out",
"=",
"open",
"(",
"ip_netns_file",
")",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"return",
"out",
"for",
"line",
"in",
"ip_net... | Returns a list for which items are namespaces in the output of
ip netns stored in the ip_netns_file. | [
"Returns",
"a",
"list",
"for",
"which",
"items",
"are",
"namespaces",
"in",
"the",
"output",
"of",
"ip",
"netns",
"stored",
"in",
"the",
"ip_netns_file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L28-L44 | train | 220,555 |
sosreport/sos | sos/plugins/networking.py | Networking.collect_iptable | def collect_iptable(self, tablename):
""" When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table """
modname = "iptable_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "iptables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | python | def collect_iptable(self, tablename):
""" When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table """
modname = "iptable_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "iptables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | [
"def",
"collect_iptable",
"(",
"self",
",",
"tablename",
")",
":",
"modname",
"=",
"\"iptable_\"",
"+",
"tablename",
"if",
"self",
".",
"check_ext_prog",
"(",
"\"grep -q %s /proc/modules\"",
"%",
"modname",
")",
":",
"cmd",
"=",
"\"iptables -t \"",
"+",
"tablena... | When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table | [
"When",
"running",
"the",
"iptables",
"command",
"it",
"unfortunately",
"auto",
"-",
"loads",
"the",
"modules",
"before",
"trying",
"to",
"get",
"output",
".",
"Some",
"people",
"explicitly",
"don",
"t",
"want",
"this",
"so",
"check",
"if",
"the",
"modules",... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L46-L56 | train | 220,556 |
sosreport/sos | sos/plugins/networking.py | Networking.collect_ip6table | def collect_ip6table(self, tablename):
""" Same as function above, but for ipv6 """
modname = "ip6table_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "ip6tables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | python | def collect_ip6table(self, tablename):
""" Same as function above, but for ipv6 """
modname = "ip6table_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "ip6tables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | [
"def",
"collect_ip6table",
"(",
"self",
",",
"tablename",
")",
":",
"modname",
"=",
"\"ip6table_\"",
"+",
"tablename",
"if",
"self",
".",
"check_ext_prog",
"(",
"\"grep -q %s /proc/modules\"",
"%",
"modname",
")",
":",
"cmd",
"=",
"\"ip6tables -t \"",
"+",
"tabl... | Same as function above, but for ipv6 | [
"Same",
"as",
"function",
"above",
"but",
"for",
"ipv6"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L58-L64 | train | 220,557 |
sosreport/sos | sos/plugins/ovirt.py | Ovirt.postproc | def postproc(self):
"""
Obfuscate sensitive keys.
"""
self.do_file_sub(
"/etc/ovirt-engine/engine-config/engine-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
self.do_file_sub(
"/etc/rhevm/rhevm-config/rhevm-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
engine_files = (
'ovirt-engine.xml',
'ovirt-engine_history/current/ovirt-engine.v1.xml',
'ovirt-engine_history/ovirt-engine.boot.xml',
'ovirt-engine_history/ovirt-engine.initial.xml',
'ovirt-engine_history/ovirt-engine.last.xml',
)
for filename in engine_files:
self.do_file_sub(
"/var/tmp/ovirt-engine/config/%s" % filename,
r"<password>(.*)</password>",
r"<password>********</password>"
)
self.do_file_sub(
"/etc/ovirt-engine/redhatsupportplugin.conf",
r"proxyPassword=(.*)",
r"proxyPassword=********"
)
passwd_files = [
"logcollector.conf",
"imageuploader.conf",
"isouploader.conf"
]
for conf_file in passwd_files:
conf_path = os.path.join("/etc/ovirt-engine", conf_file)
self.do_file_sub(
conf_path,
r"passwd=(.*)",
r"passwd=********"
)
self.do_file_sub(
conf_path,
r"pg-pass=(.*)",
r"pg-pass=********"
)
sensitive_keys = self.DEFAULT_SENSITIVE_KEYS
# Handle --alloptions case which set this to True.
keys_opt = self.get_option('sensitive_keys')
if keys_opt and keys_opt is not True:
sensitive_keys = keys_opt
key_list = [x for x in sensitive_keys.split(':') if x]
for key in key_list:
self.do_path_regex_sub(
self.DB_PASS_FILES,
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# Answer files contain passwords
for key in (
'OVESETUP_CONFIG/adminPassword',
'OVESETUP_CONFIG/remoteEngineHostRootPassword',
'OVESETUP_DWH_DB/password',
'OVESETUP_DB/password',
'OVESETUP_REPORTS_CONFIG/adminPassword',
'OVESETUP_REPORTS_DB/password',
):
self.do_path_regex_sub(
r'/var/lib/ovirt-engine/setup/answers/.*',
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# aaa profiles contain passwords
protect_keys = [
"vars.password",
"pool.default.auth.simple.password",
"pool.default.ssl.truststore.password",
"config.datasource.dbpassword"
]
regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp,
r"\1*********") | python | def postproc(self):
"""
Obfuscate sensitive keys.
"""
self.do_file_sub(
"/etc/ovirt-engine/engine-config/engine-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
self.do_file_sub(
"/etc/rhevm/rhevm-config/rhevm-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
engine_files = (
'ovirt-engine.xml',
'ovirt-engine_history/current/ovirt-engine.v1.xml',
'ovirt-engine_history/ovirt-engine.boot.xml',
'ovirt-engine_history/ovirt-engine.initial.xml',
'ovirt-engine_history/ovirt-engine.last.xml',
)
for filename in engine_files:
self.do_file_sub(
"/var/tmp/ovirt-engine/config/%s" % filename,
r"<password>(.*)</password>",
r"<password>********</password>"
)
self.do_file_sub(
"/etc/ovirt-engine/redhatsupportplugin.conf",
r"proxyPassword=(.*)",
r"proxyPassword=********"
)
passwd_files = [
"logcollector.conf",
"imageuploader.conf",
"isouploader.conf"
]
for conf_file in passwd_files:
conf_path = os.path.join("/etc/ovirt-engine", conf_file)
self.do_file_sub(
conf_path,
r"passwd=(.*)",
r"passwd=********"
)
self.do_file_sub(
conf_path,
r"pg-pass=(.*)",
r"pg-pass=********"
)
sensitive_keys = self.DEFAULT_SENSITIVE_KEYS
# Handle --alloptions case which set this to True.
keys_opt = self.get_option('sensitive_keys')
if keys_opt and keys_opt is not True:
sensitive_keys = keys_opt
key_list = [x for x in sensitive_keys.split(':') if x]
for key in key_list:
self.do_path_regex_sub(
self.DB_PASS_FILES,
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# Answer files contain passwords
for key in (
'OVESETUP_CONFIG/adminPassword',
'OVESETUP_CONFIG/remoteEngineHostRootPassword',
'OVESETUP_DWH_DB/password',
'OVESETUP_DB/password',
'OVESETUP_REPORTS_CONFIG/adminPassword',
'OVESETUP_REPORTS_DB/password',
):
self.do_path_regex_sub(
r'/var/lib/ovirt-engine/setup/answers/.*',
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# aaa profiles contain passwords
protect_keys = [
"vars.password",
"pool.default.auth.simple.password",
"pool.default.ssl.truststore.password",
"config.datasource.dbpassword"
]
regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp,
r"\1*********") | [
"def",
"postproc",
"(",
"self",
")",
":",
"self",
".",
"do_file_sub",
"(",
"\"/etc/ovirt-engine/engine-config/engine-config.properties\"",
",",
"r\"Password.type=(.*)\"",
",",
"r\"Password.type=********\"",
")",
"self",
".",
"do_file_sub",
"(",
"\"/etc/rhevm/rhevm-config/rhev... | Obfuscate sensitive keys. | [
"Obfuscate",
"sensitive",
"keys",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/ovirt.py#L135-L226 | train | 220,558 |
sosreport/sos | sos/plugins/watchdog.py | Watchdog.get_log_dir | def get_log_dir(self, conf_file):
"""Get watchdog log directory.
Get watchdog log directory path configured in ``conf_file``.
:returns: The watchdog log directory path.
:returntype: str.
:raises: IOError if ``conf_file`` is not readable.
"""
log_dir = None
with open(conf_file, 'r') as conf_f:
for line in conf_f:
line = line.split('#')[0].strip()
try:
(key, value) = line.split('=', 1)
if key.strip() == 'log-dir':
log_dir = value.strip()
except ValueError:
pass
return log_dir | python | def get_log_dir(self, conf_file):
"""Get watchdog log directory.
Get watchdog log directory path configured in ``conf_file``.
:returns: The watchdog log directory path.
:returntype: str.
:raises: IOError if ``conf_file`` is not readable.
"""
log_dir = None
with open(conf_file, 'r') as conf_f:
for line in conf_f:
line = line.split('#')[0].strip()
try:
(key, value) = line.split('=', 1)
if key.strip() == 'log-dir':
log_dir = value.strip()
except ValueError:
pass
return log_dir | [
"def",
"get_log_dir",
"(",
"self",
",",
"conf_file",
")",
":",
"log_dir",
"=",
"None",
"with",
"open",
"(",
"conf_file",
",",
"'r'",
")",
"as",
"conf_f",
":",
"for",
"line",
"in",
"conf_f",
":",
"line",
"=",
"line",
".",
"split",
"(",
"'#'",
")",
"... | Get watchdog log directory.
Get watchdog log directory path configured in ``conf_file``.
:returns: The watchdog log directory path.
:returntype: str.
:raises: IOError if ``conf_file`` is not readable. | [
"Get",
"watchdog",
"log",
"directory",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L27-L49 | train | 220,559 |
sosreport/sos | sos/plugins/watchdog.py | Watchdog.setup | def setup(self):
"""Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs.
"""
conf_file = self.get_option('conf_file')
log_dir = '/var/log/watchdog'
# Get service configuration and sysconfig files
self.add_copy_spec([
conf_file,
'/etc/sysconfig/watchdog',
])
# Get custom executables
self.add_copy_spec([
'/etc/watchdog.d',
'/usr/libexec/watchdog/scripts',
])
# Get logs
try:
res = self.get_log_dir(conf_file)
if res:
log_dir = res
except IOError as ex:
self._log_warn("Could not read %s: %s" % (conf_file, ex))
if self.get_option('all_logs'):
log_files = glob(os.path.join(log_dir, '*'))
else:
log_files = (glob(os.path.join(log_dir, '*.stdout')) +
glob(os.path.join(log_dir, '*.stderr')))
self.add_copy_spec(log_files)
# Get output of "wdctl <device>" for each /dev/watchdog*
for dev in glob('/dev/watchdog*'):
self.add_cmd_output("wdctl %s" % dev) | python | def setup(self):
"""Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs.
"""
conf_file = self.get_option('conf_file')
log_dir = '/var/log/watchdog'
# Get service configuration and sysconfig files
self.add_copy_spec([
conf_file,
'/etc/sysconfig/watchdog',
])
# Get custom executables
self.add_copy_spec([
'/etc/watchdog.d',
'/usr/libexec/watchdog/scripts',
])
# Get logs
try:
res = self.get_log_dir(conf_file)
if res:
log_dir = res
except IOError as ex:
self._log_warn("Could not read %s: %s" % (conf_file, ex))
if self.get_option('all_logs'):
log_files = glob(os.path.join(log_dir, '*'))
else:
log_files = (glob(os.path.join(log_dir, '*.stdout')) +
glob(os.path.join(log_dir, '*.stderr')))
self.add_copy_spec(log_files)
# Get output of "wdctl <device>" for each /dev/watchdog*
for dev in glob('/dev/watchdog*'):
self.add_cmd_output("wdctl %s" % dev) | [
"def",
"setup",
"(",
"self",
")",
":",
"conf_file",
"=",
"self",
".",
"get_option",
"(",
"'conf_file'",
")",
"log_dir",
"=",
"'/var/log/watchdog'",
"# Get service configuration and sysconfig files",
"self",
".",
"add_copy_spec",
"(",
"[",
"conf_file",
",",
"'/etc/sy... | Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs. | [
"Collect",
"watchdog",
"information",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L51-L90 | train | 220,560 |
sosreport/sos | sos/plugins/gluster.py | Gluster.get_volume_names | def get_volume_names(self, volume_file):
"""Return a dictionary for which key are volume names according to the
output of gluster volume info stored in volume_file.
"""
out = []
fp = open(volume_file, 'r')
for line in fp.readlines():
if not line.startswith("Volume Name:"):
continue
volname = line[12:-1]
out.append(volname)
fp.close()
return out | python | def get_volume_names(self, volume_file):
"""Return a dictionary for which key are volume names according to the
output of gluster volume info stored in volume_file.
"""
out = []
fp = open(volume_file, 'r')
for line in fp.readlines():
if not line.startswith("Volume Name:"):
continue
volname = line[12:-1]
out.append(volname)
fp.close()
return out | [
"def",
"get_volume_names",
"(",
"self",
",",
"volume_file",
")",
":",
"out",
"=",
"[",
"]",
"fp",
"=",
"open",
"(",
"volume_file",
",",
"'r'",
")",
"for",
"line",
"in",
"fp",
".",
"readlines",
"(",
")",
":",
"if",
"not",
"line",
".",
"startswith",
... | Return a dictionary for which key are volume names according to the
output of gluster volume info stored in volume_file. | [
"Return",
"a",
"dictionary",
"for",
"which",
"key",
"are",
"volume",
"names",
"according",
"to",
"the",
"output",
"of",
"gluster",
"volume",
"info",
"stored",
"in",
"volume_file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/gluster.py#L29-L41 | train | 220,561 |
sosreport/sos | sos/policies/ubuntu.py | UbuntuPolicy.dist_version | def dist_version(self):
""" Returns the version stated in DISTRIB_RELEASE
"""
try:
with open('/etc/lsb-release', 'r') as fp:
lines = fp.readlines()
for line in lines:
if "DISTRIB_RELEASE" in line:
return line.split("=")[1].strip()
return False
except IOError:
return False | python | def dist_version(self):
""" Returns the version stated in DISTRIB_RELEASE
"""
try:
with open('/etc/lsb-release', 'r') as fp:
lines = fp.readlines()
for line in lines:
if "DISTRIB_RELEASE" in line:
return line.split("=")[1].strip()
return False
except IOError:
return False | [
"def",
"dist_version",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/etc/lsb-release'",
",",
"'r'",
")",
"as",
"fp",
":",
"lines",
"=",
"fp",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"\"DISTRIB_RELEASE\"",
"in",... | Returns the version stated in DISTRIB_RELEASE | [
"Returns",
"the",
"version",
"stated",
"in",
"DISTRIB_RELEASE"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/ubuntu.py#L26-L37 | train | 220,562 |
sosreport/sos | sos/archive.py | FileCacheArchive._make_leading_paths | def _make_leading_paths(self, src, mode=0o700):
"""Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: The source path in the host file system for which
leading components should be created, or the path
to an sos_* virtual directory inside the archive.
Host paths must be absolute (initial '/'), and
sos_* directory paths must be a path relative to
the root of the archive.
:param mode: An optional mode to be used when creating path
components.
:returns: A rewritten destination path in the case that one
or more symbolic links in intermediate components
of the path have altered the path destination.
"""
self.log_debug("Making leading paths for %s" % src)
root = self._archive_root
dest = src
def in_archive(path):
"""Test whether path ``path`` is inside the archive.
"""
return path.startswith(os.path.join(root, ""))
if not src.startswith("/"):
# Sos archive path (sos_commands, sos_logs etc.)
src_dir = src
else:
# Host file path
src_dir = src if os.path.isdir(src) else os.path.split(src)[0]
# Build a list of path components in root-to-leaf order.
path = src_dir
path_comps = []
while path != '/' and path != '':
head, tail = os.path.split(path)
path_comps.append(tail)
path = head
path_comps.reverse()
abs_path = root
src_path = "/"
# Check and create components as needed
for comp in path_comps:
abs_path = os.path.join(abs_path, comp)
# Do not create components that are above the archive root.
if not in_archive(abs_path):
continue
src_path = os.path.join(src_path, comp)
if not os.path.exists(abs_path):
self.log_debug("Making path %s" % abs_path)
if os.path.islink(src_path) and os.path.isdir(src_path):
target = os.readlink(src_path)
# The directory containing the source in the host fs,
# adjusted for the current level of path creation.
target_dir = os.path.split(src_path)[0]
# The source path of the target in the host fs to be
# recursively copied.
target_src = os.path.join(target_dir, target)
# Recursively create leading components of target
dest = self._make_leading_paths(target_src, mode=mode)
dest = os.path.normpath(dest)
self.log_debug("Making symlink '%s' -> '%s'" %
(abs_path, target))
os.symlink(target, abs_path)
else:
self.log_debug("Making directory %s" % abs_path)
os.mkdir(abs_path, mode)
dest = src_path
return dest | python | def _make_leading_paths(self, src, mode=0o700):
"""Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: The source path in the host file system for which
leading components should be created, or the path
to an sos_* virtual directory inside the archive.
Host paths must be absolute (initial '/'), and
sos_* directory paths must be a path relative to
the root of the archive.
:param mode: An optional mode to be used when creating path
components.
:returns: A rewritten destination path in the case that one
or more symbolic links in intermediate components
of the path have altered the path destination.
"""
self.log_debug("Making leading paths for %s" % src)
root = self._archive_root
dest = src
def in_archive(path):
"""Test whether path ``path`` is inside the archive.
"""
return path.startswith(os.path.join(root, ""))
if not src.startswith("/"):
# Sos archive path (sos_commands, sos_logs etc.)
src_dir = src
else:
# Host file path
src_dir = src if os.path.isdir(src) else os.path.split(src)[0]
# Build a list of path components in root-to-leaf order.
path = src_dir
path_comps = []
while path != '/' and path != '':
head, tail = os.path.split(path)
path_comps.append(tail)
path = head
path_comps.reverse()
abs_path = root
src_path = "/"
# Check and create components as needed
for comp in path_comps:
abs_path = os.path.join(abs_path, comp)
# Do not create components that are above the archive root.
if not in_archive(abs_path):
continue
src_path = os.path.join(src_path, comp)
if not os.path.exists(abs_path):
self.log_debug("Making path %s" % abs_path)
if os.path.islink(src_path) and os.path.isdir(src_path):
target = os.readlink(src_path)
# The directory containing the source in the host fs,
# adjusted for the current level of path creation.
target_dir = os.path.split(src_path)[0]
# The source path of the target in the host fs to be
# recursively copied.
target_src = os.path.join(target_dir, target)
# Recursively create leading components of target
dest = self._make_leading_paths(target_src, mode=mode)
dest = os.path.normpath(dest)
self.log_debug("Making symlink '%s' -> '%s'" %
(abs_path, target))
os.symlink(target, abs_path)
else:
self.log_debug("Making directory %s" % abs_path)
os.mkdir(abs_path, mode)
dest = src_path
return dest | [
"def",
"_make_leading_paths",
"(",
"self",
",",
"src",
",",
"mode",
"=",
"0o700",
")",
":",
"self",
".",
"log_debug",
"(",
"\"Making leading paths for %s\"",
"%",
"src",
")",
"root",
"=",
"self",
".",
"_archive_root",
"dest",
"=",
"src",
"def",
"in_archive",... | Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: The source path in the host file system for which
leading components should be created, or the path
to an sos_* virtual directory inside the archive.
Host paths must be absolute (initial '/'), and
sos_* directory paths must be a path relative to
the root of the archive.
:param mode: An optional mode to be used when creating path
components.
:returns: A rewritten destination path in the case that one
or more symbolic links in intermediate components
of the path have altered the path destination. | [
"Create",
"leading",
"path",
"components"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L159-L243 | train | 220,563 |
sosreport/sos | sos/archive.py | FileCacheArchive._check_path | def _check_path(self, src, path_type, dest=None, force=False):
"""Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for the actual presence of a
path, since it was impossible for another `Archive` client to
enter the class while another method invocation was being
dispatched.
Deal with this by implementing a locking scheme for operations
that modify the path structure of the archive, and by testing
explicitly for conflicts with any existing content at the
specified destination path.
It is not an error to attempt to create a path that already
exists in the archive so long as the type of the object to be
added matches the type of object already found at the path.
It is an error to attempt to re-create an existing path with
a different path type (for example, creating a symbolic link
at a path already occupied by a regular file).
:param src: the source path to be copied to the archive
:param path_type: the type of object to be copied
:param dest: an optional destination path
:param force: force file creation even if the path exists
:returns: An absolute destination path if the path should be
copied now or `None` otherwise
"""
dest = dest or self.dest_path(src)
if path_type == P_DIR:
dest_dir = dest
else:
dest_dir = os.path.split(dest)[0]
if not dest_dir:
return dest
# Check containing directory presence and path type
if os.path.exists(dest_dir) and not os.path.isdir(dest_dir):
raise ValueError("path '%s' exists and is not a directory" %
dest_dir)
elif not os.path.exists(dest_dir):
src_dir = src if path_type == P_DIR else os.path.split(src)[0]
self._make_leading_paths(src_dir)
def is_special(mode):
return any([
stat.S_ISBLK(mode),
stat.S_ISCHR(mode),
stat.S_ISFIFO(mode),
stat.S_ISSOCK(mode)
])
if force:
return dest
# Check destination path presence and type
if os.path.exists(dest):
# Use lstat: we care about the current object, not the referent.
st = os.lstat(dest)
ve_msg = "path '%s' exists and is not a %s"
if path_type == P_FILE and not stat.S_ISREG(st.st_mode):
raise ValueError(ve_msg % (dest, "regular file"))
if path_type == P_LINK and not stat.S_ISLNK(st.st_mode):
raise ValueError(ve_msg % (dest, "symbolic link"))
if path_type == P_NODE and not is_special(st.st_mode):
raise ValueError(ve_msg % (dest, "special file"))
if path_type == P_DIR and not stat.S_ISDIR(st.st_mode):
raise ValueError(ve_msg % (dest, "directory"))
# Path has already been copied: skip
return None
return dest | python | def _check_path(self, src, path_type, dest=None, force=False):
"""Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for the actual presence of a
path, since it was impossible for another `Archive` client to
enter the class while another method invocation was being
dispatched.
Deal with this by implementing a locking scheme for operations
that modify the path structure of the archive, and by testing
explicitly for conflicts with any existing content at the
specified destination path.
It is not an error to attempt to create a path that already
exists in the archive so long as the type of the object to be
added matches the type of object already found at the path.
It is an error to attempt to re-create an existing path with
a different path type (for example, creating a symbolic link
at a path already occupied by a regular file).
:param src: the source path to be copied to the archive
:param path_type: the type of object to be copied
:param dest: an optional destination path
:param force: force file creation even if the path exists
:returns: An absolute destination path if the path should be
copied now or `None` otherwise
"""
dest = dest or self.dest_path(src)
if path_type == P_DIR:
dest_dir = dest
else:
dest_dir = os.path.split(dest)[0]
if not dest_dir:
return dest
# Check containing directory presence and path type
if os.path.exists(dest_dir) and not os.path.isdir(dest_dir):
raise ValueError("path '%s' exists and is not a directory" %
dest_dir)
elif not os.path.exists(dest_dir):
src_dir = src if path_type == P_DIR else os.path.split(src)[0]
self._make_leading_paths(src_dir)
def is_special(mode):
return any([
stat.S_ISBLK(mode),
stat.S_ISCHR(mode),
stat.S_ISFIFO(mode),
stat.S_ISSOCK(mode)
])
if force:
return dest
# Check destination path presence and type
if os.path.exists(dest):
# Use lstat: we care about the current object, not the referent.
st = os.lstat(dest)
ve_msg = "path '%s' exists and is not a %s"
if path_type == P_FILE and not stat.S_ISREG(st.st_mode):
raise ValueError(ve_msg % (dest, "regular file"))
if path_type == P_LINK and not stat.S_ISLNK(st.st_mode):
raise ValueError(ve_msg % (dest, "symbolic link"))
if path_type == P_NODE and not is_special(st.st_mode):
raise ValueError(ve_msg % (dest, "special file"))
if path_type == P_DIR and not stat.S_ISDIR(st.st_mode):
raise ValueError(ve_msg % (dest, "directory"))
# Path has already been copied: skip
return None
return dest | [
"def",
"_check_path",
"(",
"self",
",",
"src",
",",
"path_type",
",",
"dest",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"dest",
"=",
"dest",
"or",
"self",
".",
"dest_path",
"(",
"src",
")",
"if",
"path_type",
"==",
"P_DIR",
":",
"dest_dir",
... | Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for the actual presence of a
path, since it was impossible for another `Archive` client to
enter the class while another method invocation was being
dispatched.
Deal with this by implementing a locking scheme for operations
that modify the path structure of the archive, and by testing
explicitly for conflicts with any existing content at the
specified destination path.
It is not an error to attempt to create a path that already
exists in the archive so long as the type of the object to be
added matches the type of object already found at the path.
It is an error to attempt to re-create an existing path with
a different path type (for example, creating a symbolic link
at a path already occupied by a regular file).
:param src: the source path to be copied to the archive
:param path_type: the type of object to be copied
:param dest: an optional destination path
:param force: force file creation even if the path exists
:returns: An absolute destination path if the path should be
copied now or `None` otherwise | [
"Check",
"a",
"new",
"destination",
"path",
"in",
"the",
"archive",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L245-L318 | train | 220,564 |
sosreport/sos | sos/archive.py | FileCacheArchive.makedirs | def makedirs(self, path, mode=0o700):
"""Create path, including leading components.
Used by sos.sosreport to set up sos_* directories.
"""
os.makedirs(os.path.join(self._archive_root, path), mode=mode)
self.log_debug("created directory at '%s' in FileCacheArchive '%s'"
% (path, self._archive_root)) | python | def makedirs(self, path, mode=0o700):
"""Create path, including leading components.
Used by sos.sosreport to set up sos_* directories.
"""
os.makedirs(os.path.join(self._archive_root, path), mode=mode)
self.log_debug("created directory at '%s' in FileCacheArchive '%s'"
% (path, self._archive_root)) | [
"def",
"makedirs",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"0o700",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_archive_root",
",",
"path",
")",
",",
"mode",
"=",
"mode",
")",
"self",
".",
"log_de... | Create path, including leading components.
Used by sos.sosreport to set up sos_* directories. | [
"Create",
"path",
"including",
"leading",
"components",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L510-L517 | train | 220,565 |
sosreport/sos | sos/archive.py | FileCacheArchive._encrypt | def _encrypt(self, archive):
"""Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive.
Returns the name of the encrypted archive, or raises an exception to
signal that encryption failed and the unencrypted archive name should
be used.
"""
arc_name = archive.replace("sosreport-", "secured-sosreport-")
arc_name += ".gpg"
enc_cmd = "gpg --batch -o %s " % arc_name
env = None
if self.enc_opts["key"]:
# need to assume a trusted key here to be able to encrypt the
# archive non-interactively
enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"]
enc_cmd += archive
if self.enc_opts["password"]:
# prevent change of gpg options using a long password, but also
# prevent the addition of quote characters to the passphrase
passwd = "%s" % self.enc_opts["password"].replace('\'"', '')
env = {"sos_gpg": passwd}
enc_cmd += "-c --passphrase-fd 0 "
enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd
enc_cmd += archive
r = sos_get_command_output(enc_cmd, timeout=0, env=env)
if r["status"] == 0:
return arc_name
elif r["status"] == 2:
if self.enc_opts["key"]:
msg = "Specified key not in keyring"
else:
msg = "Could not read passphrase"
else:
# TODO: report the actual error from gpg. Currently, we cannot as
# sos_get_command_output() does not capture stderr
msg = "gpg exited with code %s" % r["status"]
raise Exception(msg) | python | def _encrypt(self, archive):
"""Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive.
Returns the name of the encrypted archive, or raises an exception to
signal that encryption failed and the unencrypted archive name should
be used.
"""
arc_name = archive.replace("sosreport-", "secured-sosreport-")
arc_name += ".gpg"
enc_cmd = "gpg --batch -o %s " % arc_name
env = None
if self.enc_opts["key"]:
# need to assume a trusted key here to be able to encrypt the
# archive non-interactively
enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"]
enc_cmd += archive
if self.enc_opts["password"]:
# prevent change of gpg options using a long password, but also
# prevent the addition of quote characters to the passphrase
passwd = "%s" % self.enc_opts["password"].replace('\'"', '')
env = {"sos_gpg": passwd}
enc_cmd += "-c --passphrase-fd 0 "
enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd
enc_cmd += archive
r = sos_get_command_output(enc_cmd, timeout=0, env=env)
if r["status"] == 0:
return arc_name
elif r["status"] == 2:
if self.enc_opts["key"]:
msg = "Specified key not in keyring"
else:
msg = "Could not read passphrase"
else:
# TODO: report the actual error from gpg. Currently, we cannot as
# sos_get_command_output() does not capture stderr
msg = "gpg exited with code %s" % r["status"]
raise Exception(msg) | [
"def",
"_encrypt",
"(",
"self",
",",
"archive",
")",
":",
"arc_name",
"=",
"archive",
".",
"replace",
"(",
"\"sosreport-\"",
",",
"\"secured-sosreport-\"",
")",
"arc_name",
"+=",
"\".gpg\"",
"enc_cmd",
"=",
"\"gpg --batch -o %s \"",
"%",
"arc_name",
"env",
"=",
... | Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive.
Returns the name of the encrypted archive, or raises an exception to
signal that encryption failed and the unencrypted archive name should
be used. | [
"Encrypts",
"the",
"compressed",
"archive",
"using",
"GPG",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L552-L593 | train | 220,566 |
sosreport/sos | sos/utilities.py | tail | def tail(filename, number_of_bytes):
"""Returns the last number_of_bytes of filename"""
with open(filename, "rb") as f:
if os.stat(filename).st_size > number_of_bytes:
f.seek(-number_of_bytes, 2)
return f.read() | python | def tail(filename, number_of_bytes):
"""Returns the last number_of_bytes of filename"""
with open(filename, "rb") as f:
if os.stat(filename).st_size > number_of_bytes:
f.seek(-number_of_bytes, 2)
return f.read() | [
"def",
"tail",
"(",
"filename",
",",
"number_of_bytes",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"if",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size",
">",
"number_of_bytes",
":",
"f",
".",
"seek",
"(",
... | Returns the last number_of_bytes of filename | [
"Returns",
"the",
"last",
"number_of_bytes",
"of",
"filename"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L29-L34 | train | 220,567 |
sosreport/sos | sos/utilities.py | fileobj | def fileobj(path_or_file, mode='r'):
"""Returns a file-like object that can be used as a context manager"""
if isinstance(path_or_file, six.string_types):
try:
return open(path_or_file, mode)
except IOError:
log = logging.getLogger('sos')
log.debug("fileobj: %s could not be opened" % path_or_file)
return closing(six.StringIO())
else:
return closing(path_or_file) | python | def fileobj(path_or_file, mode='r'):
"""Returns a file-like object that can be used as a context manager"""
if isinstance(path_or_file, six.string_types):
try:
return open(path_or_file, mode)
except IOError:
log = logging.getLogger('sos')
log.debug("fileobj: %s could not be opened" % path_or_file)
return closing(six.StringIO())
else:
return closing(path_or_file) | [
"def",
"fileobj",
"(",
"path_or_file",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"isinstance",
"(",
"path_or_file",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"return",
"open",
"(",
"path_or_file",
",",
"mode",
")",
"except",
"IOError",
":",
... | Returns a file-like object that can be used as a context manager | [
"Returns",
"a",
"file",
"-",
"like",
"object",
"that",
"can",
"be",
"used",
"as",
"a",
"context",
"manager"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L37-L47 | train | 220,568 |
sosreport/sos | sos/utilities.py | convert_bytes | def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
"""Converts a number of bytes to a shorter, more human friendly format"""
fn = float(bytes_)
if bytes_ >= T:
return '%.1fT' % (fn / T)
elif bytes_ >= G:
return '%.1fG' % (fn / G)
elif bytes_ >= M:
return '%.1fM' % (fn / M)
elif bytes_ >= K:
return '%.1fK' % (fn / K)
else:
return '%d' % bytes_ | python | def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
"""Converts a number of bytes to a shorter, more human friendly format"""
fn = float(bytes_)
if bytes_ >= T:
return '%.1fT' % (fn / T)
elif bytes_ >= G:
return '%.1fG' % (fn / G)
elif bytes_ >= M:
return '%.1fM' % (fn / M)
elif bytes_ >= K:
return '%.1fK' % (fn / K)
else:
return '%d' % bytes_ | [
"def",
"convert_bytes",
"(",
"bytes_",
",",
"K",
"=",
"1",
"<<",
"10",
",",
"M",
"=",
"1",
"<<",
"20",
",",
"G",
"=",
"1",
"<<",
"30",
",",
"T",
"=",
"1",
"<<",
"40",
")",
":",
"fn",
"=",
"float",
"(",
"bytes_",
")",
"if",
"bytes_",
">=",
... | Converts a number of bytes to a shorter, more human friendly format | [
"Converts",
"a",
"number",
"of",
"bytes",
"to",
"a",
"shorter",
"more",
"human",
"friendly",
"format"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L50-L62 | train | 220,569 |
sosreport/sos | sos/utilities.py | grep | def grep(pattern, *files_or_paths):
"""Returns lines matched in fnames, where fnames can either be pathnames to
files to grep through or open file objects to grep through line by line"""
matches = []
for fop in files_or_paths:
with fileobj(fop) as fo:
matches.extend((line for line in fo if re.match(pattern, line)))
return matches | python | def grep(pattern, *files_or_paths):
"""Returns lines matched in fnames, where fnames can either be pathnames to
files to grep through or open file objects to grep through line by line"""
matches = []
for fop in files_or_paths:
with fileobj(fop) as fo:
matches.extend((line for line in fo if re.match(pattern, line)))
return matches | [
"def",
"grep",
"(",
"pattern",
",",
"*",
"files_or_paths",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"fop",
"in",
"files_or_paths",
":",
"with",
"fileobj",
"(",
"fop",
")",
"as",
"fo",
":",
"matches",
".",
"extend",
"(",
"(",
"line",
"for",
"line",
... | Returns lines matched in fnames, where fnames can either be pathnames to
files to grep through or open file objects to grep through line by line | [
"Returns",
"lines",
"matched",
"in",
"fnames",
"where",
"fnames",
"can",
"either",
"be",
"pathnames",
"to",
"files",
"to",
"grep",
"through",
"or",
"open",
"file",
"objects",
"to",
"grep",
"through",
"line",
"by",
"line"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L87-L96 | train | 220,570 |
sosreport/sos | sos/utilities.py | is_executable | def is_executable(command):
"""Returns if a command matches an executable on the PATH"""
paths = os.environ.get("PATH", "").split(os.path.pathsep)
candidates = [command] + [os.path.join(p, command) for p in paths]
return any(os.access(path, os.X_OK) for path in candidates) | python | def is_executable(command):
"""Returns if a command matches an executable on the PATH"""
paths = os.environ.get("PATH", "").split(os.path.pathsep)
candidates = [command] + [os.path.join(p, command) for p in paths]
return any(os.access(path, os.X_OK) for path in candidates) | [
"def",
"is_executable",
"(",
"command",
")",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PATH\"",
",",
"\"\"",
")",
".",
"split",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
"candidates",
"=",
"[",
"command",
"]",
"+",
"[",
"os",
... | Returns if a command matches an executable on the PATH | [
"Returns",
"if",
"a",
"command",
"matches",
"an",
"executable",
"on",
"the",
"PATH"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L99-L104 | train | 220,571 |
sosreport/sos | sos/utilities.py | sos_get_command_output | def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
"""Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command.
"""
# Change root or cwd for child only. Exceptions in the prexec_fn
# closure are caught in the parent (chroot and chdir are bound from
# the enclosing scope).
def _child_prep_fn():
if (chroot):
os.chroot(chroot)
if (chdir):
os.chdir(chdir)
cmd_env = os.environ.copy()
# ensure consistent locale for collected command output
cmd_env['LC_ALL'] = 'C'
# optionally add an environment change for the command
if env:
for key, value in env.items():
if value:
cmd_env[key] = value
else:
cmd_env.pop(key, None)
# use /usr/bin/timeout to implement a timeout
if timeout and is_executable("timeout"):
command = "timeout %ds %s" % (timeout, command)
# shlex.split() reacts badly to unicode on older python runtimes.
if not six.PY3:
command = command.encode('utf-8', 'ignore')
args = shlex.split(command)
# Expand arguments that are wildcard paths.
expanded_args = []
for arg in args:
expanded_arg = glob.glob(arg)
if expanded_arg:
expanded_args.extend(expanded_arg)
else:
expanded_args.append(arg)
try:
p = Popen(expanded_args, shell=False, stdout=PIPE,
stderr=STDOUT if stderr else PIPE,
bufsize=-1, env=cmd_env, close_fds=True,
preexec_fn=_child_prep_fn)
reader = AsyncReader(p.stdout, sizelimit, binary)
if poller:
while reader.running:
if poller():
p.terminate()
raise SoSTimeoutError
stdout = reader.get_contents()
while p.poll() is None:
pass
except OSError as e:
if e.errno == errno.ENOENT:
return {'status': 127, 'output': ""}
else:
raise e
if p.returncode == 126 or p.returncode == 127:
stdout = six.binary_type(b"")
return {
'status': p.returncode,
'output': stdout
} | python | def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
"""Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command.
"""
# Change root or cwd for child only. Exceptions in the prexec_fn
# closure are caught in the parent (chroot and chdir are bound from
# the enclosing scope).
def _child_prep_fn():
if (chroot):
os.chroot(chroot)
if (chdir):
os.chdir(chdir)
cmd_env = os.environ.copy()
# ensure consistent locale for collected command output
cmd_env['LC_ALL'] = 'C'
# optionally add an environment change for the command
if env:
for key, value in env.items():
if value:
cmd_env[key] = value
else:
cmd_env.pop(key, None)
# use /usr/bin/timeout to implement a timeout
if timeout and is_executable("timeout"):
command = "timeout %ds %s" % (timeout, command)
# shlex.split() reacts badly to unicode on older python runtimes.
if not six.PY3:
command = command.encode('utf-8', 'ignore')
args = shlex.split(command)
# Expand arguments that are wildcard paths.
expanded_args = []
for arg in args:
expanded_arg = glob.glob(arg)
if expanded_arg:
expanded_args.extend(expanded_arg)
else:
expanded_args.append(arg)
try:
p = Popen(expanded_args, shell=False, stdout=PIPE,
stderr=STDOUT if stderr else PIPE,
bufsize=-1, env=cmd_env, close_fds=True,
preexec_fn=_child_prep_fn)
reader = AsyncReader(p.stdout, sizelimit, binary)
if poller:
while reader.running:
if poller():
p.terminate()
raise SoSTimeoutError
stdout = reader.get_contents()
while p.poll() is None:
pass
except OSError as e:
if e.errno == errno.ENOENT:
return {'status': 127, 'output': ""}
else:
raise e
if p.returncode == 126 or p.returncode == 127:
stdout = six.binary_type(b"")
return {
'status': p.returncode,
'output': stdout
} | [
"def",
"sos_get_command_output",
"(",
"command",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"False",
",",
"chroot",
"=",
"None",
",",
"chdir",
"=",
"None",
",",
"env",
"=",
"None",
",",
"binary",
"=",
"False",
",",
"sizelimit",
"=",
"None",
",",
... | Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command. | [
"Execute",
"a",
"command",
"and",
"return",
"a",
"dictionary",
"of",
"status",
"and",
"output",
"optionally",
"changing",
"root",
"or",
"current",
"working",
"directory",
"before",
"executing",
"command",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L107-L177 | train | 220,572 |
sosreport/sos | sos/utilities.py | import_module | def import_module(module_fqname, superclasses=None):
"""Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes."""
module_name = module_fqname.rpartition(".")[-1]
module = __import__(module_fqname, globals(), locals(), [module_name])
modules = [class_ for cname, class_ in
inspect.getmembers(module, inspect.isclass)
if class_.__module__ == module_fqname]
if superclasses:
modules = [m for m in modules if issubclass(m, superclasses)]
return modules | python | def import_module(module_fqname, superclasses=None):
"""Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes."""
module_name = module_fqname.rpartition(".")[-1]
module = __import__(module_fqname, globals(), locals(), [module_name])
modules = [class_ for cname, class_ in
inspect.getmembers(module, inspect.isclass)
if class_.__module__ == module_fqname]
if superclasses:
modules = [m for m in modules if issubclass(m, superclasses)]
return modules | [
"def",
"import_module",
"(",
"module_fqname",
",",
"superclasses",
"=",
"None",
")",
":",
"module_name",
"=",
"module_fqname",
".",
"rpartition",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"module",
"=",
"__import__",
"(",
"module_fqname",
",",
"globals",
"(",
... | Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes. | [
"Imports",
"the",
"module",
"module_fqname",
"and",
"returns",
"a",
"list",
"of",
"defined",
"classes",
"from",
"that",
"module",
".",
"If",
"superclasses",
"is",
"defined",
"then",
"the",
"classes",
"returned",
"will",
"be",
"subclasses",
"of",
"the",
"specif... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L180-L193 | train | 220,573 |
sosreport/sos | sos/utilities.py | shell_out | def shell_out(cmd, timeout=30, chroot=None, runat=None):
"""Shell out to an external command and return the output or the empty
string in case of error.
"""
return sos_get_command_output(cmd, timeout=timeout,
chroot=chroot, chdir=runat)['output'] | python | def shell_out(cmd, timeout=30, chroot=None, runat=None):
"""Shell out to an external command and return the output or the empty
string in case of error.
"""
return sos_get_command_output(cmd, timeout=timeout,
chroot=chroot, chdir=runat)['output'] | [
"def",
"shell_out",
"(",
"cmd",
",",
"timeout",
"=",
"30",
",",
"chroot",
"=",
"None",
",",
"runat",
"=",
"None",
")",
":",
"return",
"sos_get_command_output",
"(",
"cmd",
",",
"timeout",
"=",
"timeout",
",",
"chroot",
"=",
"chroot",
",",
"chdir",
"=",... | Shell out to an external command and return the output or the empty
string in case of error. | [
"Shell",
"out",
"to",
"an",
"external",
"command",
"and",
"return",
"the",
"output",
"or",
"the",
"empty",
"string",
"in",
"case",
"of",
"error",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L196-L201 | train | 220,574 |
sosreport/sos | sos/utilities.py | AsyncReader.get_contents | def get_contents(self):
'''Returns the contents of the deque as a string'''
# block until command completes or timesout (separate from the plugin
# hitting a timeout)
while self.running:
pass
if not self.binary:
return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque)
else:
return b''.join(ln for ln in self.deque) | python | def get_contents(self):
'''Returns the contents of the deque as a string'''
# block until command completes or timesout (separate from the plugin
# hitting a timeout)
while self.running:
pass
if not self.binary:
return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque)
else:
return b''.join(ln for ln in self.deque) | [
"def",
"get_contents",
"(",
"self",
")",
":",
"# block until command completes or timesout (separate from the plugin",
"# hitting a timeout)",
"while",
"self",
".",
"running",
":",
"pass",
"if",
"not",
"self",
".",
"binary",
":",
"return",
"''",
".",
"join",
"(",
"l... | Returns the contents of the deque as a string | [
"Returns",
"the",
"contents",
"of",
"the",
"deque",
"as",
"a",
"string"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L246-L255 | train | 220,575 |
sosreport/sos | sos/utilities.py | ImporterHelper._plugin_name | def _plugin_name(self, path):
"Returns the plugin module name given the path"
base = os.path.basename(path)
name, ext = os.path.splitext(base)
return name | python | def _plugin_name(self, path):
"Returns the plugin module name given the path"
base = os.path.basename(path)
name, ext = os.path.splitext(base)
return name | [
"def",
"_plugin_name",
"(",
"self",
",",
"path",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"base",
")",
"return",
"name"
] | Returns the plugin module name given the path | [
"Returns",
"the",
"plugin",
"module",
"name",
"given",
"the",
"path"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L270-L274 | train | 220,576 |
sosreport/sos | sos/utilities.py | ImporterHelper.get_modules | def get_modules(self):
"""Returns the list of importable modules in the configured python
package. """
plugins = []
for path in self.package.__path__:
if os.path.isdir(path):
plugins.extend(self._find_plugins_in_dir(path))
return plugins | python | def get_modules(self):
"""Returns the list of importable modules in the configured python
package. """
plugins = []
for path in self.package.__path__:
if os.path.isdir(path):
plugins.extend(self._find_plugins_in_dir(path))
return plugins | [
"def",
"get_modules",
"(",
"self",
")",
":",
"plugins",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"package",
".",
"__path__",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"plugins",
".",
"extend",
"(",
"self",
".",
"_... | Returns the list of importable modules in the configured python
package. | [
"Returns",
"the",
"list",
"of",
"importable",
"modules",
"in",
"the",
"configured",
"python",
"package",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L292-L300 | train | 220,577 |
sosreport/sos | sos/policies/redhat.py | RedHatPolicy.check_usrmove | def check_usrmove(self, pkgs):
"""Test whether the running system implements UsrMove.
If the 'filesystem' package is present, it will check that the
version is greater than 3. If the package is not present the
'/bin' and '/sbin' paths are checked and UsrMove is assumed
if both are symbolic links.
:param pkgs: a packages dictionary
"""
if 'filesystem' not in pkgs:
return os.path.islink('/bin') and os.path.islink('/sbin')
else:
filesys_version = pkgs['filesystem']['version']
return True if filesys_version[0] == '3' else False | python | def check_usrmove(self, pkgs):
"""Test whether the running system implements UsrMove.
If the 'filesystem' package is present, it will check that the
version is greater than 3. If the package is not present the
'/bin' and '/sbin' paths are checked and UsrMove is assumed
if both are symbolic links.
:param pkgs: a packages dictionary
"""
if 'filesystem' not in pkgs:
return os.path.islink('/bin') and os.path.islink('/sbin')
else:
filesys_version = pkgs['filesystem']['version']
return True if filesys_version[0] == '3' else False | [
"def",
"check_usrmove",
"(",
"self",
",",
"pkgs",
")",
":",
"if",
"'filesystem'",
"not",
"in",
"pkgs",
":",
"return",
"os",
".",
"path",
".",
"islink",
"(",
"'/bin'",
")",
"and",
"os",
".",
"path",
".",
"islink",
"(",
"'/sbin'",
")",
"else",
":",
"... | Test whether the running system implements UsrMove.
If the 'filesystem' package is present, it will check that the
version is greater than 3. If the package is not present the
'/bin' and '/sbin' paths are checked and UsrMove is assumed
if both are symbolic links.
:param pkgs: a packages dictionary | [
"Test",
"whether",
"the",
"running",
"system",
"implements",
"UsrMove",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L100-L114 | train | 220,578 |
sosreport/sos | sos/policies/redhat.py | RedHatPolicy.mangle_package_path | def mangle_package_path(self, files):
"""Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the list of package managed files
"""
paths = []
def transform_path(path):
# Some packages actually own paths in /bin: in this case,
# duplicate the path as both the / and /usr version.
skip_paths = ["/bin/rpm", "/bin/mailx"]
if path in skip_paths:
return (path, os.path.join("/usr", path[1:]))
return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),)
if self.usrmove:
for f in files:
paths.extend(transform_path(f))
return paths
else:
return files | python | def mangle_package_path(self, files):
"""Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the list of package managed files
"""
paths = []
def transform_path(path):
# Some packages actually own paths in /bin: in this case,
# duplicate the path as both the / and /usr version.
skip_paths = ["/bin/rpm", "/bin/mailx"]
if path in skip_paths:
return (path, os.path.join("/usr", path[1:]))
return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),)
if self.usrmove:
for f in files:
paths.extend(transform_path(f))
return paths
else:
return files | [
"def",
"mangle_package_path",
"(",
"self",
",",
"files",
")",
":",
"paths",
"=",
"[",
"]",
"def",
"transform_path",
"(",
"path",
")",
":",
"# Some packages actually own paths in /bin: in this case,",
"# duplicate the path as both the / and /usr version.",
"skip_paths",
"=",... | Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the list of package managed files | [
"Mangle",
"paths",
"for",
"post",
"-",
"UsrMove",
"systems",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L116-L140 | train | 220,579 |
sosreport/sos | sos/policies/redhat.py | RedHatPolicy._container_init | def _container_init(self):
"""Check if sos is running in a container and perform container
specific initialisation based on ENV_HOST_SYSROOT.
"""
if ENV_CONTAINER in os.environ:
if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
self._in_container = True
if ENV_HOST_SYSROOT in os.environ:
self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
use_sysroot = self._in_container and self._host_sysroot != '/'
if use_sysroot:
host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
self._tmp_dir = host_tmp_dir
return self._host_sysroot if use_sysroot else None | python | def _container_init(self):
"""Check if sos is running in a container and perform container
specific initialisation based on ENV_HOST_SYSROOT.
"""
if ENV_CONTAINER in os.environ:
if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
self._in_container = True
if ENV_HOST_SYSROOT in os.environ:
self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
use_sysroot = self._in_container and self._host_sysroot != '/'
if use_sysroot:
host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
self._tmp_dir = host_tmp_dir
return self._host_sysroot if use_sysroot else None | [
"def",
"_container_init",
"(",
"self",
")",
":",
"if",
"ENV_CONTAINER",
"in",
"os",
".",
"environ",
":",
"if",
"os",
".",
"environ",
"[",
"ENV_CONTAINER",
"]",
"in",
"[",
"'docker'",
",",
"'oci'",
"]",
":",
"self",
".",
"_in_container",
"=",
"True",
"i... | Check if sos is running in a container and perform container
specific initialisation based on ENV_HOST_SYSROOT. | [
"Check",
"if",
"sos",
"is",
"running",
"in",
"a",
"container",
"and",
"perform",
"container",
"specific",
"initialisation",
"based",
"on",
"ENV_HOST_SYSROOT",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L142-L155 | train | 220,580 |
sosreport/sos | sos/policies/redhat.py | RHELPolicy.check | def check(cls):
"""Test to see if the running host is a RHEL installation.
Checks for the presence of the "Red Hat Enterprise Linux"
release string at the beginning of the NAME field in the
`/etc/os-release` file and returns ``True`` if it is
found, and ``False`` otherwise.
:returns: ``True`` if the host is running RHEL or ``False``
otherwise.
"""
if not os.path.exists(OS_RELEASE):
return False
with open(OS_RELEASE, "r") as f:
for line in f:
if line.startswith("NAME"):
(name, value) = line.split("=")
value = value.strip("\"'")
if value.startswith(cls.distro):
return True
return False | python | def check(cls):
"""Test to see if the running host is a RHEL installation.
Checks for the presence of the "Red Hat Enterprise Linux"
release string at the beginning of the NAME field in the
`/etc/os-release` file and returns ``True`` if it is
found, and ``False`` otherwise.
:returns: ``True`` if the host is running RHEL or ``False``
otherwise.
"""
if not os.path.exists(OS_RELEASE):
return False
with open(OS_RELEASE, "r") as f:
for line in f:
if line.startswith("NAME"):
(name, value) = line.split("=")
value = value.strip("\"'")
if value.startswith(cls.distro):
return True
return False | [
"def",
"check",
"(",
"cls",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"OS_RELEASE",
")",
":",
"return",
"False",
"with",
"open",
"(",
"OS_RELEASE",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line"... | Test to see if the running host is a RHEL installation.
Checks for the presence of the "Red Hat Enterprise Linux"
release string at the beginning of the NAME field in the
`/etc/os-release` file and returns ``True`` if it is
found, and ``False`` otherwise.
:returns: ``True`` if the host is running RHEL or ``False``
otherwise. | [
"Test",
"to",
"see",
"if",
"the",
"running",
"host",
"is",
"a",
"RHEL",
"installation",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L274-L295 | train | 220,581 |
sosreport/sos | sos/plugins/lustre.py | Lustre.get_params | def get_params(self, name, param_list):
'''Use lctl get_param to collect a selection of parameters into a
file.
'''
self.add_cmd_output("lctl get_param %s" % " ".join(param_list),
suggest_filename="params-%s" % name,
stderr=False) | python | def get_params(self, name, param_list):
'''Use lctl get_param to collect a selection of parameters into a
file.
'''
self.add_cmd_output("lctl get_param %s" % " ".join(param_list),
suggest_filename="params-%s" % name,
stderr=False) | [
"def",
"get_params",
"(",
"self",
",",
"name",
",",
"param_list",
")",
":",
"self",
".",
"add_cmd_output",
"(",
"\"lctl get_param %s\"",
"%",
"\" \"",
".",
"join",
"(",
"param_list",
")",
",",
"suggest_filename",
"=",
"\"params-%s\"",
"%",
"name",
",",
"stde... | Use lctl get_param to collect a selection of parameters into a
file. | [
"Use",
"lctl",
"get_param",
"to",
"collect",
"a",
"selection",
"of",
"parameters",
"into",
"a",
"file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/lustre.py#L19-L26 | train | 220,582 |
sosreport/sos | sos/plugins/qpid_dispatch.py | QpidDispatch.setup | def setup(self):
""" performs data collection for qpid dispatch router """
options = ""
if self.get_option("port"):
options = (options + " -b " + gethostname() +
":%s" % (self.get_option("port")))
# gethostname() is due to DISPATCH-156
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]:
if self.get_option(option):
options = (options + " --%s=" % (option) +
self.get_option(option))
self.add_cmd_output([
"qdstat -a" + options, # Show Router Addresses
"qdstat -n" + options, # Show Router Nodes
"qdstat -c" + options, # Show Connections
"qdstat -m" + options # Show Broker Memory Stats
])
self.add_copy_spec([
"/etc/qpid-dispatch/qdrouterd.conf"
]) | python | def setup(self):
""" performs data collection for qpid dispatch router """
options = ""
if self.get_option("port"):
options = (options + " -b " + gethostname() +
":%s" % (self.get_option("port")))
# gethostname() is due to DISPATCH-156
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]:
if self.get_option(option):
options = (options + " --%s=" % (option) +
self.get_option(option))
self.add_cmd_output([
"qdstat -a" + options, # Show Router Addresses
"qdstat -n" + options, # Show Router Nodes
"qdstat -c" + options, # Show Connections
"qdstat -m" + options # Show Broker Memory Stats
])
self.add_copy_spec([
"/etc/qpid-dispatch/qdrouterd.conf"
]) | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"if",
"self",
".",
"get_option",
"(",
"\"port\"",
")",
":",
"options",
"=",
"(",
"options",
"+",
"\" -b \"",
"+",
"gethostname",
"(",
")",
"+",
"\":%s\"",
"%",
"(",
"self",
".",
"get_opti... | performs data collection for qpid dispatch router | [
"performs",
"data",
"collection",
"for",
"qpid",
"dispatch",
"router"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid_dispatch.py#L30-L53 | train | 220,583 |
sosreport/sos | sos/plugins/__init__.py | SoSPredicate.__str | def __str(self, quote=False, prefix="", suffix=""):
"""Return a string representation of this SoSPredicate with
optional prefix, suffix and value quoting.
"""
quotes = '"%s"'
pstr = "dry_run=%s, " % self._dry_run
kmods = self._kmods
kmods = [quotes % k for k in kmods] if quote else kmods
pstr += "kmods=[%s], " % (",".join(kmods))
services = self._services
services = [quotes % s for s in services] if quote else services
pstr += "services=[%s]" % (",".join(services))
return prefix + pstr + suffix | python | def __str(self, quote=False, prefix="", suffix=""):
"""Return a string representation of this SoSPredicate with
optional prefix, suffix and value quoting.
"""
quotes = '"%s"'
pstr = "dry_run=%s, " % self._dry_run
kmods = self._kmods
kmods = [quotes % k for k in kmods] if quote else kmods
pstr += "kmods=[%s], " % (",".join(kmods))
services = self._services
services = [quotes % s for s in services] if quote else services
pstr += "services=[%s]" % (",".join(services))
return prefix + pstr + suffix | [
"def",
"__str",
"(",
"self",
",",
"quote",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"quotes",
"=",
"'\"%s\"'",
"pstr",
"=",
"\"dry_run=%s, \"",
"%",
"self",
".",
"_dry_run",
"kmods",
"=",
"self",
".",
"_kmods",
... | Return a string representation of this SoSPredicate with
optional prefix, suffix and value quoting. | [
"Return",
"a",
"string",
"representation",
"of",
"this",
"SoSPredicate",
"with",
"optional",
"prefix",
"suffix",
"and",
"value",
"quoting",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L117-L132 | train | 220,584 |
sosreport/sos | sos/plugins/__init__.py | Plugin.do_file_sub | def do_file_sub(self, srcpath, regexp, subst):
'''Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made.
'''
try:
path = self._get_dest_for_srcpath(srcpath)
self._log_debug("substituting scrpath '%s'" % srcpath)
self._log_debug("substituting '%s' for '%s' in '%s'"
% (subst, regexp, path))
if not path:
return 0
readable = self.archive.open_file(path)
content = readable.read()
if not isinstance(content, six.string_types):
content = content.decode('utf8', 'ignore')
result, replacements = re.subn(regexp, subst, content)
if replacements:
self.archive.add_string(result, srcpath)
else:
replacements = 0
except (OSError, IOError) as e:
# if trying to regexp a nonexisting file, dont log it as an
# error to stdout
if e.errno == errno.ENOENT:
msg = "file '%s' not collected, substitution skipped"
self._log_debug(msg % path)
else:
msg = "regex substitution failed for '%s' with: '%s'"
self._log_error(msg % (path, e))
replacements = 0
return replacements | python | def do_file_sub(self, srcpath, regexp, subst):
'''Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made.
'''
try:
path = self._get_dest_for_srcpath(srcpath)
self._log_debug("substituting scrpath '%s'" % srcpath)
self._log_debug("substituting '%s' for '%s' in '%s'"
% (subst, regexp, path))
if not path:
return 0
readable = self.archive.open_file(path)
content = readable.read()
if not isinstance(content, six.string_types):
content = content.decode('utf8', 'ignore')
result, replacements = re.subn(regexp, subst, content)
if replacements:
self.archive.add_string(result, srcpath)
else:
replacements = 0
except (OSError, IOError) as e:
# if trying to regexp a nonexisting file, dont log it as an
# error to stdout
if e.errno == errno.ENOENT:
msg = "file '%s' not collected, substitution skipped"
self._log_debug(msg % path)
else:
msg = "regex substitution failed for '%s' with: '%s'"
self._log_error(msg % (path, e))
replacements = 0
return replacements | [
"def",
"do_file_sub",
"(",
"self",
",",
"srcpath",
",",
"regexp",
",",
"subst",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"_get_dest_for_srcpath",
"(",
"srcpath",
")",
"self",
".",
"_log_debug",
"(",
"\"substituting scrpath '%s'\"",
"%",
"srcpath",
")"... | Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made. | [
"Apply",
"a",
"regexp",
"substitution",
"to",
"a",
"file",
"archived",
"by",
"sosreport",
".",
"srcpath",
"is",
"the",
"path",
"in",
"the",
"archive",
"where",
"the",
"file",
"can",
"be",
"found",
".",
"regexp",
"can",
"be",
"a",
"regexp",
"string",
"or"... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L482-L516 | train | 220,585 |
sosreport/sos | sos/plugins/__init__.py | Plugin.do_path_regex_sub | def do_path_regex_sub(self, pathexp, regexp, subst):
'''Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst.'''
if not hasattr(pathexp, "match"):
pathexp = re.compile(pathexp)
match = pathexp.match
file_list = [f for f in self.copied_files if match(f['srcpath'])]
for file in file_list:
self.do_file_sub(file['srcpath'], regexp, subst) | python | def do_path_regex_sub(self, pathexp, regexp, subst):
'''Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst.'''
if not hasattr(pathexp, "match"):
pathexp = re.compile(pathexp)
match = pathexp.match
file_list = [f for f in self.copied_files if match(f['srcpath'])]
for file in file_list:
self.do_file_sub(file['srcpath'], regexp, subst) | [
"def",
"do_path_regex_sub",
"(",
"self",
",",
"pathexp",
",",
"regexp",
",",
"subst",
")",
":",
"if",
"not",
"hasattr",
"(",
"pathexp",
",",
"\"match\"",
")",
":",
"pathexp",
"=",
"re",
".",
"compile",
"(",
"pathexp",
")",
"match",
"=",
"pathexp",
".",... | Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst. | [
"Apply",
"a",
"regexp",
"substituation",
"to",
"a",
"set",
"of",
"files",
"archived",
"by",
"sos",
".",
"The",
"set",
"of",
"files",
"to",
"be",
"substituted",
"is",
"generated",
"by",
"matching",
"collected",
"file",
"pathnames",
"against",
"pathexp",
"whic... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L518-L530 | train | 220,586 |
sosreport/sos | sos/plugins/__init__.py | Plugin._do_copy_path | def _do_copy_path(self, srcpath, dest=None):
'''Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report.
'''
if self._is_forbidden_path(srcpath):
self._log_debug("skipping forbidden path '%s'" % srcpath)
return ''
if not dest:
dest = srcpath
if self.use_sysroot():
dest = self.strip_sysroot(dest)
try:
st = os.lstat(srcpath)
except (OSError, IOError):
self._log_info("failed to stat '%s'" % srcpath)
return
if stat.S_ISLNK(st.st_mode):
self._copy_symlink(srcpath)
return
else:
if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK):
self._copy_dir(srcpath)
return
# handle special nodes (block, char, fifo, socket)
if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
ntype = _node_type(st)
self._log_debug("creating %s node at archive:'%s'"
% (ntype, dest))
self._copy_node(srcpath, st)
return
# if we get here, it's definitely a regular file (not a symlink or dir)
self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest))
# if not readable(srcpath)
if not st.st_mode & 0o444:
# FIXME: reflect permissions in archive
self.archive.add_string("", dest)
else:
self.archive.add_file(srcpath, dest)
self.copied_files.append({
'srcpath': srcpath,
'dstpath': dest,
'symlink': "no"
}) | python | def _do_copy_path(self, srcpath, dest=None):
'''Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report.
'''
if self._is_forbidden_path(srcpath):
self._log_debug("skipping forbidden path '%s'" % srcpath)
return ''
if not dest:
dest = srcpath
if self.use_sysroot():
dest = self.strip_sysroot(dest)
try:
st = os.lstat(srcpath)
except (OSError, IOError):
self._log_info("failed to stat '%s'" % srcpath)
return
if stat.S_ISLNK(st.st_mode):
self._copy_symlink(srcpath)
return
else:
if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK):
self._copy_dir(srcpath)
return
# handle special nodes (block, char, fifo, socket)
if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
ntype = _node_type(st)
self._log_debug("creating %s node at archive:'%s'"
% (ntype, dest))
self._copy_node(srcpath, st)
return
# if we get here, it's definitely a regular file (not a symlink or dir)
self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest))
# if not readable(srcpath)
if not st.st_mode & 0o444:
# FIXME: reflect permissions in archive
self.archive.add_string("", dest)
else:
self.archive.add_file(srcpath, dest)
self.copied_files.append({
'srcpath': srcpath,
'dstpath': dest,
'symlink': "no"
}) | [
"def",
"_do_copy_path",
"(",
"self",
",",
"srcpath",
",",
"dest",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_forbidden_path",
"(",
"srcpath",
")",
":",
"self",
".",
"_log_debug",
"(",
"\"skipping forbidden path '%s'\"",
"%",
"srcpath",
")",
"return",
"''... | Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report. | [
"Copy",
"file",
"or",
"directory",
"to",
"the",
"destination",
"tree",
".",
"If",
"a",
"directory",
"then",
"everything",
"below",
"it",
"is",
"recursively",
"copied",
".",
"A",
"list",
"of",
"copied",
"files",
"are",
"saved",
"for",
"use",
"later",
"in",
... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L627-L678 | train | 220,587 |
sosreport/sos | sos/plugins/__init__.py | Plugin.set_option | def set_option(self, optionname, value):
"""Set the named option to value. Ensure the original type
of the option value is preserved.
"""
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
# FIXME: ensure that the resulting type of the set option
# matches that of the default value. This prevents a string
# option from being coerced to int simply because it holds
# a numeric value (e.g. a password).
# See PR #1526 and Issue #1597
defaulttype = type(parms['enabled'])
if defaulttype != type(value) and defaulttype != type(None):
value = (defaulttype)(value)
parms['enabled'] = value
return True
else:
return False | python | def set_option(self, optionname, value):
"""Set the named option to value. Ensure the original type
of the option value is preserved.
"""
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
# FIXME: ensure that the resulting type of the set option
# matches that of the default value. This prevents a string
# option from being coerced to int simply because it holds
# a numeric value (e.g. a password).
# See PR #1526 and Issue #1597
defaulttype = type(parms['enabled'])
if defaulttype != type(value) and defaulttype != type(None):
value = (defaulttype)(value)
parms['enabled'] = value
return True
else:
return False | [
"def",
"set_option",
"(",
"self",
",",
"optionname",
",",
"value",
")",
":",
"for",
"name",
",",
"parms",
"in",
"zip",
"(",
"self",
".",
"opt_names",
",",
"self",
".",
"opt_parms",
")",
":",
"if",
"name",
"==",
"optionname",
":",
"# FIXME: ensure that th... | Set the named option to value. Ensure the original type
of the option value is preserved. | [
"Set",
"the",
"named",
"option",
"to",
"value",
".",
"Ensure",
"the",
"original",
"type",
"of",
"the",
"option",
"value",
"is",
"preserved",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L699-L716 | train | 220,588 |
sosreport/sos | sos/plugins/__init__.py | Plugin.get_option | def get_option(self, optionname, default=0):
"""Returns the first value that matches 'optionname' in parameters
passed in via the command line or set via set_option or via the
global_plugin_options dictionary, in that order.
optionaname may be iterable, in which case the first option that
matches any of the option names is returned.
"""
global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout')
if optionname in global_options:
return getattr(self.commons['cmdlineopts'], optionname)
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
val = parms['enabled']
if val is not None:
return val
return default | python | def get_option(self, optionname, default=0):
"""Returns the first value that matches 'optionname' in parameters
passed in via the command line or set via set_option or via the
global_plugin_options dictionary, in that order.
optionaname may be iterable, in which case the first option that
matches any of the option names is returned.
"""
global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout')
if optionname in global_options:
return getattr(self.commons['cmdlineopts'], optionname)
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
val = parms['enabled']
if val is not None:
return val
return default | [
"def",
"get_option",
"(",
"self",
",",
"optionname",
",",
"default",
"=",
"0",
")",
":",
"global_options",
"=",
"(",
"'verify'",
",",
"'all_logs'",
",",
"'log_size'",
",",
"'plugin_timeout'",
")",
"if",
"optionname",
"in",
"global_options",
":",
"return",
"g... | Returns the first value that matches 'optionname' in parameters
passed in via the command line or set via set_option or via the
global_plugin_options dictionary, in that order.
optionaname may be iterable, in which case the first option that
matches any of the option names is returned. | [
"Returns",
"the",
"first",
"value",
"that",
"matches",
"optionname",
"in",
"parameters",
"passed",
"in",
"via",
"the",
"command",
"line",
"or",
"set",
"via",
"set_option",
"or",
"via",
"the",
"global_plugin_options",
"dictionary",
"in",
"that",
"order",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L718-L738 | train | 220,589 |
sosreport/sos | sos/plugins/__init__.py | Plugin.get_option_as_list | def get_option_as_list(self, optionname, delimiter=",", default=None):
'''Will try to return the option as a list separated by the
delimiter.
'''
option = self.get_option(optionname)
try:
opt_list = [opt.strip() for opt in option.split(delimiter)]
return list(filter(None, opt_list))
except Exception:
return default | python | def get_option_as_list(self, optionname, delimiter=",", default=None):
'''Will try to return the option as a list separated by the
delimiter.
'''
option = self.get_option(optionname)
try:
opt_list = [opt.strip() for opt in option.split(delimiter)]
return list(filter(None, opt_list))
except Exception:
return default | [
"def",
"get_option_as_list",
"(",
"self",
",",
"optionname",
",",
"delimiter",
"=",
"\",\"",
",",
"default",
"=",
"None",
")",
":",
"option",
"=",
"self",
".",
"get_option",
"(",
"optionname",
")",
"try",
":",
"opt_list",
"=",
"[",
"opt",
".",
"strip",
... | Will try to return the option as a list separated by the
delimiter. | [
"Will",
"try",
"to",
"return",
"the",
"option",
"as",
"a",
"list",
"separated",
"by",
"the",
"delimiter",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L740-L749 | train | 220,590 |
sosreport/sos | sos/plugins/__init__.py | Plugin.add_copy_spec | def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
"""Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit.
"""
if not self.test_predicate(pred=pred):
self._log_info("skipped copy spec '%s' due to predicate (%s)" %
(copyspecs, self.get_predicate(pred=pred)))
return
if sizelimit is None:
sizelimit = self.get_option("log_size")
if self.get_option('all_logs'):
sizelimit = None
if sizelimit:
sizelimit *= 1024 * 1024 # in MB
if not copyspecs:
return False
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
for copyspec in copyspecs:
if not (copyspec and len(copyspec)):
return False
if self.use_sysroot():
copyspec = self.join_sysroot(copyspec)
files = self._expand_copy_spec(copyspec)
if len(files) == 0:
continue
# Files hould be sorted in most-recently-modified order, so that
# we collect the newest data first before reaching the limit.
def getmtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
files.sort(key=getmtime, reverse=True)
current_size = 0
limit_reached = False
_file = None
for _file in files:
if self._is_forbidden_path(_file):
self._log_debug("skipping forbidden path '%s'" % _file)
continue
try:
current_size += os.stat(_file)[stat.ST_SIZE]
except OSError:
self._log_info("failed to stat '%s'" % _file)
if sizelimit and current_size > sizelimit:
limit_reached = True
break
self._add_copy_paths([_file])
if limit_reached and tailit and not _file_is_compressed(_file):
file_name = _file
if file_name[0] == os.sep:
file_name = file_name.lstrip(os.sep)
strfile = file_name.replace(os.path.sep, ".") + ".tailed"
self.add_string_as_file(tail(_file, sizelimit), strfile)
rel_path = os.path.relpath('/', os.path.dirname(_file))
link_path = os.path.join(rel_path, 'sos_strings',
self.name(), strfile)
self.archive.add_link(link_path, _file) | python | def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
"""Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit.
"""
if not self.test_predicate(pred=pred):
self._log_info("skipped copy spec '%s' due to predicate (%s)" %
(copyspecs, self.get_predicate(pred=pred)))
return
if sizelimit is None:
sizelimit = self.get_option("log_size")
if self.get_option('all_logs'):
sizelimit = None
if sizelimit:
sizelimit *= 1024 * 1024 # in MB
if not copyspecs:
return False
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
for copyspec in copyspecs:
if not (copyspec and len(copyspec)):
return False
if self.use_sysroot():
copyspec = self.join_sysroot(copyspec)
files = self._expand_copy_spec(copyspec)
if len(files) == 0:
continue
# Files hould be sorted in most-recently-modified order, so that
# we collect the newest data first before reaching the limit.
def getmtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
files.sort(key=getmtime, reverse=True)
current_size = 0
limit_reached = False
_file = None
for _file in files:
if self._is_forbidden_path(_file):
self._log_debug("skipping forbidden path '%s'" % _file)
continue
try:
current_size += os.stat(_file)[stat.ST_SIZE]
except OSError:
self._log_info("failed to stat '%s'" % _file)
if sizelimit and current_size > sizelimit:
limit_reached = True
break
self._add_copy_paths([_file])
if limit_reached and tailit and not _file_is_compressed(_file):
file_name = _file
if file_name[0] == os.sep:
file_name = file_name.lstrip(os.sep)
strfile = file_name.replace(os.path.sep, ".") + ".tailed"
self.add_string_as_file(tail(_file, sizelimit), strfile)
rel_path = os.path.relpath('/', os.path.dirname(_file))
link_path = os.path.join(rel_path, 'sos_strings',
self.name(), strfile)
self.archive.add_link(link_path, _file) | [
"def",
"add_copy_spec",
"(",
"self",
",",
"copyspecs",
",",
"sizelimit",
"=",
"None",
",",
"tailit",
"=",
"True",
",",
"pred",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"test_predicate",
"(",
"pred",
"=",
"pred",
")",
":",
"self",
".",
"_log_i... | Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit. | [
"Add",
"a",
"file",
"or",
"glob",
"but",
"limit",
"it",
"to",
"sizelimit",
"megabytes",
".",
"If",
"fname",
"is",
"a",
"single",
"file",
"the",
"file",
"will",
"be",
"tailed",
"to",
"meet",
"sizelimit",
".",
"If",
"the",
"first",
"file",
"in",
"a",
"... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L754-L827 | train | 220,591 |
sosreport/sos | sos/plugins/__init__.py | Plugin.call_ext_prog | def call_ext_prog(self, prog, timeout=300, stderr=True,
chroot=True, runat=None):
"""Execute a command independantly of the output gathering part of
sosreport.
"""
return self.get_command_output(prog, timeout=timeout, stderr=stderr,
chroot=chroot, runat=runat) | python | def call_ext_prog(self, prog, timeout=300, stderr=True,
chroot=True, runat=None):
"""Execute a command independantly of the output gathering part of
sosreport.
"""
return self.get_command_output(prog, timeout=timeout, stderr=stderr,
chroot=chroot, runat=runat) | [
"def",
"call_ext_prog",
"(",
"self",
",",
"prog",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_command_output",
"(",
"prog",
",",
"timeout",
"=",
... | Execute a command independantly of the output gathering part of
sosreport. | [
"Execute",
"a",
"command",
"independantly",
"of",
"the",
"output",
"gathering",
"part",
"of",
"sosreport",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L862-L868 | train | 220,592 |
sosreport/sos | sos/plugins/__init__.py | Plugin._add_cmd_output | def _add_cmd_output(self, cmd, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Internal helper to add a single command to the collection list."""
cmdt = (
cmd, suggest_filename,
root_symlink, timeout, stderr,
chroot, runat, env, binary, sizelimit
)
_tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', "
"'%s')")
_logstr = "packed command tuple: " + _tuplefmt
self._log_debug(_logstr % cmdt)
if self.test_predicate(cmd=True, pred=pred):
self.collect_cmds.append(cmdt)
self._log_info("added cmd output '%s'" % cmd)
else:
self._log_info("skipped cmd output '%s' due to predicate (%s)" %
(cmd, self.get_predicate(cmd=True, pred=pred))) | python | def _add_cmd_output(self, cmd, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Internal helper to add a single command to the collection list."""
cmdt = (
cmd, suggest_filename,
root_symlink, timeout, stderr,
chroot, runat, env, binary, sizelimit
)
_tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', "
"'%s')")
_logstr = "packed command tuple: " + _tuplefmt
self._log_debug(_logstr % cmdt)
if self.test_predicate(cmd=True, pred=pred):
self.collect_cmds.append(cmdt)
self._log_info("added cmd output '%s'" % cmd)
else:
self._log_info("skipped cmd output '%s' due to predicate (%s)" %
(cmd, self.get_predicate(cmd=True, pred=pred))) | [
"def",
"_add_cmd_output",
"(",
"self",
",",
"cmd",
",",
"suggest_filename",
"=",
"None",
",",
"root_symlink",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
",",
"env",
"=",
... | Internal helper to add a single command to the collection list. | [
"Internal",
"helper",
"to",
"add",
"a",
"single",
"command",
"to",
"the",
"collection",
"list",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L877-L896 | train | 220,593 |
sosreport/sos | sos/plugins/__init__.py | Plugin.add_cmd_output | def add_cmd_output(self, cmds, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Run a program or a list of programs and collect the output"""
if isinstance(cmds, six.string_types):
cmds = [cmds]
if len(cmds) > 1 and (suggest_filename or root_symlink):
self._log_warn("ambiguous filename or symlink for command list")
if sizelimit is None:
sizelimit = self.get_option("log_size")
for cmd in cmds:
self._add_cmd_output(cmd, suggest_filename=suggest_filename,
root_symlink=root_symlink, timeout=timeout,
stderr=stderr, chroot=chroot, runat=runat,
env=env, binary=binary, sizelimit=sizelimit,
pred=pred) | python | def add_cmd_output(self, cmds, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Run a program or a list of programs and collect the output"""
if isinstance(cmds, six.string_types):
cmds = [cmds]
if len(cmds) > 1 and (suggest_filename or root_symlink):
self._log_warn("ambiguous filename or symlink for command list")
if sizelimit is None:
sizelimit = self.get_option("log_size")
for cmd in cmds:
self._add_cmd_output(cmd, suggest_filename=suggest_filename,
root_symlink=root_symlink, timeout=timeout,
stderr=stderr, chroot=chroot, runat=runat,
env=env, binary=binary, sizelimit=sizelimit,
pred=pred) | [
"def",
"add_cmd_output",
"(",
"self",
",",
"cmds",
",",
"suggest_filename",
"=",
"None",
",",
"root_symlink",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
",",
"env",
"=",
... | Run a program or a list of programs and collect the output | [
"Run",
"a",
"program",
"or",
"a",
"list",
"of",
"programs",
"and",
"collect",
"the",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L898-L914 | train | 220,594 |
sosreport/sos | sos/plugins/__init__.py | Plugin.get_cmd_output_path | def get_cmd_output_path(self, name=None, make=True):
"""Return a path into which this module should store collected
command output
"""
cmd_output_path = os.path.join(self.archive.get_tmp_dir(),
'sos_commands', self.name())
if name:
cmd_output_path = os.path.join(cmd_output_path, name)
if make:
os.makedirs(cmd_output_path)
return cmd_output_path | python | def get_cmd_output_path(self, name=None, make=True):
"""Return a path into which this module should store collected
command output
"""
cmd_output_path = os.path.join(self.archive.get_tmp_dir(),
'sos_commands', self.name())
if name:
cmd_output_path = os.path.join(cmd_output_path, name)
if make:
os.makedirs(cmd_output_path)
return cmd_output_path | [
"def",
"get_cmd_output_path",
"(",
"self",
",",
"name",
"=",
"None",
",",
"make",
"=",
"True",
")",
":",
"cmd_output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive",
".",
"get_tmp_dir",
"(",
")",
",",
"'sos_commands'",
",",
"sel... | Return a path into which this module should store collected
command output | [
"Return",
"a",
"path",
"into",
"which",
"this",
"module",
"should",
"store",
"collected",
"command",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L916-L927 | train | 220,595 |
sosreport/sos | sos/plugins/__init__.py | Plugin._make_command_filename | def _make_command_filename(self, exe):
"""The internal function to build up a filename based on a command."""
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
# check for collisions
if os.path.exists(outfn):
inc = 2
while True:
newfn = "%s_%d" % (outfn, inc)
if not os.path.exists(newfn):
outfn = newfn
break
inc += 1
return outfn | python | def _make_command_filename(self, exe):
"""The internal function to build up a filename based on a command."""
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
# check for collisions
if os.path.exists(outfn):
inc = 2
while True:
newfn = "%s_%d" % (outfn, inc)
if not os.path.exists(newfn):
outfn = newfn
break
inc += 1
return outfn | [
"def",
"_make_command_filename",
"(",
"self",
",",
"exe",
")",
":",
"outfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"commons",
"[",
"'cmddir'",
"]",
",",
"self",
".",
"name",
"(",
")",
",",
"self",
".",
"_mangle_command",
"(",
"exe",
... | The internal function to build up a filename based on a command. | [
"The",
"internal",
"function",
"to",
"build",
"up",
"a",
"filename",
"based",
"on",
"a",
"command",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L940-L956 | train | 220,596 |
sosreport/sos | sos/plugins/__init__.py | Plugin.add_string_as_file | def add_string_as_file(self, content, filename, pred=None):
"""Add a string to the archive as a file named `filename`"""
# Generate summary string for logging
summary = content.splitlines()[0] if content else ''
if not isinstance(summary, six.string_types):
summary = content.decode('utf8', 'ignore')
if not self.test_predicate(cmd=False, pred=pred):
self._log_info("skipped string ...'%s' due to predicate (%s)" %
(summary, self.get_predicate(pred=pred)))
return
self.copy_strings.append((content, filename))
self._log_debug("added string ...'%s' as '%s'" % (summary, filename)) | python | def add_string_as_file(self, content, filename, pred=None):
"""Add a string to the archive as a file named `filename`"""
# Generate summary string for logging
summary = content.splitlines()[0] if content else ''
if not isinstance(summary, six.string_types):
summary = content.decode('utf8', 'ignore')
if not self.test_predicate(cmd=False, pred=pred):
self._log_info("skipped string ...'%s' due to predicate (%s)" %
(summary, self.get_predicate(pred=pred)))
return
self.copy_strings.append((content, filename))
self._log_debug("added string ...'%s' as '%s'" % (summary, filename)) | [
"def",
"add_string_as_file",
"(",
"self",
",",
"content",
",",
"filename",
",",
"pred",
"=",
"None",
")",
":",
"# Generate summary string for logging",
"summary",
"=",
"content",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"if",
"content",
"else",
"''",
"if"... | Add a string to the archive as a file named `filename` | [
"Add",
"a",
"string",
"to",
"the",
"archive",
"as",
"a",
"file",
"named",
"filename"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L958-L972 | train | 220,597 |
sosreport/sos | sos/plugins/__init__.py | Plugin.add_journal | def add_journal(self, units=None, boot=None, since=None, until=None,
lines=None, allfields=False, output=None, timeout=None,
identifier=None, catalog=None, sizelimit=None, pred=None):
"""Collect journald logs from one of more units.
:param units: A string, or list of strings specifying the
systemd units for which journal entries will be
collected.
:param boot: A string selecting a boot index using the
journalctl syntax. The special values 'this' and
'last' are also accepted.
:param since: A string representation of the start time for
journal messages.
:param until: A string representation of the end time for
journal messages.
:param lines: The maximum number of lines to be collected.
:param allfields: A bool. Include all journal fields
regardless of size or non-printable
characters.
:param output: A journalctl output control string, for
example "verbose".
:param timeout: An optional timeout in seconds.
:param identifier: An optional message identifier.
:param catalog: Bool. If True, augment lines with descriptions
from the system catalog.
:param sizelimit: Limit to the size of output returned in MB.
Defaults to the value of --log-size.
"""
journal_cmd = "journalctl --no-pager "
unit_opt = " --unit %s"
boot_opt = " --boot %s"
since_opt = " --since %s"
until_opt = " --until %s"
lines_opt = " --lines %s"
output_opt = " --output %s"
identifier_opt = " --identifier %s"
catalog_opt = " --catalog"
journal_size = 100
all_logs = self.get_option("all_logs")
log_size = sizelimit or self.get_option("log_size")
log_size = max(log_size, journal_size) if not all_logs else 0
if isinstance(units, six.string_types):
units = [units]
if units:
for unit in units:
journal_cmd += unit_opt % unit
if identifier:
journal_cmd += identifier_opt % identifier
if catalog:
journal_cmd += catalog_opt
if allfields:
journal_cmd += " --all"
if boot:
if boot == "this":
boot = ""
if boot == "last":
boot = "-1"
journal_cmd += boot_opt % boot
if since:
journal_cmd += since_opt % since
if until:
journal_cmd += until_opt % until
if lines:
journal_cmd += lines_opt % lines
if output:
journal_cmd += output_opt % output
self._log_debug("collecting journal: %s" % journal_cmd)
self._add_cmd_output(journal_cmd, timeout=timeout,
sizelimit=log_size, pred=pred) | python | def add_journal(self, units=None, boot=None, since=None, until=None,
lines=None, allfields=False, output=None, timeout=None,
identifier=None, catalog=None, sizelimit=None, pred=None):
"""Collect journald logs from one of more units.
:param units: A string, or list of strings specifying the
systemd units for which journal entries will be
collected.
:param boot: A string selecting a boot index using the
journalctl syntax. The special values 'this' and
'last' are also accepted.
:param since: A string representation of the start time for
journal messages.
:param until: A string representation of the end time for
journal messages.
:param lines: The maximum number of lines to be collected.
:param allfields: A bool. Include all journal fields
regardless of size or non-printable
characters.
:param output: A journalctl output control string, for
example "verbose".
:param timeout: An optional timeout in seconds.
:param identifier: An optional message identifier.
:param catalog: Bool. If True, augment lines with descriptions
from the system catalog.
:param sizelimit: Limit to the size of output returned in MB.
Defaults to the value of --log-size.
"""
journal_cmd = "journalctl --no-pager "
unit_opt = " --unit %s"
boot_opt = " --boot %s"
since_opt = " --since %s"
until_opt = " --until %s"
lines_opt = " --lines %s"
output_opt = " --output %s"
identifier_opt = " --identifier %s"
catalog_opt = " --catalog"
journal_size = 100
all_logs = self.get_option("all_logs")
log_size = sizelimit or self.get_option("log_size")
log_size = max(log_size, journal_size) if not all_logs else 0
if isinstance(units, six.string_types):
units = [units]
if units:
for unit in units:
journal_cmd += unit_opt % unit
if identifier:
journal_cmd += identifier_opt % identifier
if catalog:
journal_cmd += catalog_opt
if allfields:
journal_cmd += " --all"
if boot:
if boot == "this":
boot = ""
if boot == "last":
boot = "-1"
journal_cmd += boot_opt % boot
if since:
journal_cmd += since_opt % since
if until:
journal_cmd += until_opt % until
if lines:
journal_cmd += lines_opt % lines
if output:
journal_cmd += output_opt % output
self._log_debug("collecting journal: %s" % journal_cmd)
self._add_cmd_output(journal_cmd, timeout=timeout,
sizelimit=log_size, pred=pred) | [
"def",
"add_journal",
"(",
"self",
",",
"units",
"=",
"None",
",",
"boot",
"=",
"None",
",",
"since",
"=",
"None",
",",
"until",
"=",
"None",
",",
"lines",
"=",
"None",
",",
"allfields",
"=",
"False",
",",
"output",
"=",
"None",
",",
"timeout",
"="... | Collect journald logs from one of more units.
:param units: A string, or list of strings specifying the
systemd units for which journal entries will be
collected.
:param boot: A string selecting a boot index using the
journalctl syntax. The special values 'this' and
'last' are also accepted.
:param since: A string representation of the start time for
journal messages.
:param until: A string representation of the end time for
journal messages.
:param lines: The maximum number of lines to be collected.
:param allfields: A bool. Include all journal fields
regardless of size or non-printable
characters.
:param output: A journalctl output control string, for
example "verbose".
:param timeout: An optional timeout in seconds.
:param identifier: An optional message identifier.
:param catalog: Bool. If True, augment lines with descriptions
from the system catalog.
:param sizelimit: Limit to the size of output returned in MB.
Defaults to the value of --log-size. | [
"Collect",
"journald",
"logs",
"from",
"one",
"of",
"more",
"units",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1046-L1133 | train | 220,598 |
sosreport/sos | sos/plugins/__init__.py | Plugin.add_udev_info | def add_udev_info(self, device, attrs=False):
"""Collect udevadm info output for a given device
:param device: A string or list of strings of device names or sysfs
paths. E.G. either '/sys/class/scsi_host/host0' or
'/dev/sda' is valid.
:param attrs: If True, run udevadm with the --attribute-walk option.
"""
udev_cmd = 'udevadm info'
if attrs:
udev_cmd += ' -a'
if isinstance(device, six.string_types):
device = [device]
for dev in device:
self._log_debug("collecting udev info for: %s" % dev)
self._add_cmd_output('%s %s' % (udev_cmd, dev)) | python | def add_udev_info(self, device, attrs=False):
"""Collect udevadm info output for a given device
:param device: A string or list of strings of device names or sysfs
paths. E.G. either '/sys/class/scsi_host/host0' or
'/dev/sda' is valid.
:param attrs: If True, run udevadm with the --attribute-walk option.
"""
udev_cmd = 'udevadm info'
if attrs:
udev_cmd += ' -a'
if isinstance(device, six.string_types):
device = [device]
for dev in device:
self._log_debug("collecting udev info for: %s" % dev)
self._add_cmd_output('%s %s' % (udev_cmd, dev)) | [
"def",
"add_udev_info",
"(",
"self",
",",
"device",
",",
"attrs",
"=",
"False",
")",
":",
"udev_cmd",
"=",
"'udevadm info'",
"if",
"attrs",
":",
"udev_cmd",
"+=",
"' -a'",
"if",
"isinstance",
"(",
"device",
",",
"six",
".",
"string_types",
")",
":",
"dev... | Collect udevadm info output for a given device
:param device: A string or list of strings of device names or sysfs
paths. E.G. either '/sys/class/scsi_host/host0' or
'/dev/sda' is valid.
:param attrs: If True, run udevadm with the --attribute-walk option. | [
"Collect",
"udevadm",
"info",
"output",
"for",
"a",
"given",
"device"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1135-L1152 | train | 220,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.