filename
stringlengths
4
198
content
stringlengths
25
939k
environment
sequence
variablearg
sequence
constarg
sequence
variableargjson
stringclasses
1 value
constargjson
stringlengths
2
3.9k
lang
stringclasses
3 values
constargcount
float64
0
129
variableargcount
float64
0
0
sentence
stringclasses
1 value
pycode/tinyflow/Scheduler.py
import copy from enum import Enum import multiprocessing import numpy as np from functools import cmp_to_key import plotly as py import plotly.figure_factory as ff import plotly.graph_objects as go from plotly.subplots import make_subplots import plotly from collections import defaultdict import os from pynvml import * import time import matplotlib # matplotlib.use('Agg') import pickle import numpy as np from pynvml import * from keras.models import Sequential, load_model from keras.layers import Dense, Conv1D, MaxPool1D, Dropout, Flatten from matplotlib import cm from tensorboard.plugins.hparams import keras from line_profiler import LineProfiler from typing import List def get_PCIE_bandwidth(): # if not debug_mod: # PCIE_bandwidth = nvmlDeviceGetPcieThroughput(handle, NVML_PCIE_UTIL_COUNT) # KB/s => MB/ms # PCIE_bandwidth /= 1000000 # else: PCIE_bandwidth = 12 return PCIE_bandwidth GPU = int(os.environ['CUDA_VISIBLE_DEVICES']) debug_mod = False if not debug_mod: nvmlInit() handle = nvmlDeviceGetHandleByIndex(GPU) pyplt = py.offline.plot PCIE_bandwidth = get_PCIE_bandwidth() load_list = ['convolution_2d_forward_VALID', 'convolution_backward_filter_2d_VALID', 'convolution_backward_data_2d_VALID', 'convolution_2d_forward_SAME', 'convolution_backward_filter_2d_SAME', 'convolution_backward_data_2d_SAME', 'dropout_forward', 'dropout_backward', 'broadcast_to_NHWC', 'broadcast_to_NCHW', 'reduce_sum_new_NHWC', 'reduce_sum_new_NCHW', 'bn_forward_pre_activation', 'bn_backward_pre_activation', 'activation_forward_relu', 'activation_backward_relu', 'activation_forward_softmax', 'activation_backward_softmax', 'pooling_2d_forward_max', 'pooling_2d_backward_max', 'pooling_2d_forward_mean', 'pooling_2d_backward_mean', 'matrix_multiply', 'matrix_elementwise_multiply_by_const', 'matrix_elementwise_add', 'array_set', 'concat_forward', 'concat_a_backward', 'concat_b_backward', 'sgd_update', 'cross', 'cross_backward', 'adam_mv', 'adam_compute'] optimizer_op = ['AdamOp'] class TaskType(Enum): swap_out = 0 swap_in = 1 class AccessType(Enum): output = 0 input = 1 class Tensor: def __init__(self, tensor_id, job_id, size, shape, recomputation_time, source_tensors=None, is_parameter=False, is_input_or_output=False): self.tensor_id = tensor_id self.job_id = job_id self.size = size self.swap_time = self.size / PCIE_bandwidth self.source_tensors = source_tensors if source_tensors is not None else [] self.recomputation_time = recomputation_time self.recomputation_metric = self.size / self.recomputation_time self.is_parameter = is_parameter self.shape = shape if self.is_parameter or is_input_or_output: self.in_gpu_at_beginning = True else: self.in_gpu_at_beginning = False def __repr__(self): return f'tensor_id:{self.tensor_id}, job_id":{self.job_id}, size:{self.size}' def update_swap_time(self): PCIE_bandwidth = get_PCIE_bandwidth() # print(f'PCIE_bandwidth:{PCIE_bandwidth}') self.swap_time = self.size / PCIE_bandwidth class TensorAccess: def __init__(self, tensor, time, run_time, access_type, operation_id, operation_name): self.tensor = tensor self.access_id = None self.start_time = None self.end_time = None self.time = time self.run_time = run_time self.access_type = access_type if self.access_type == AccessType.output: self.end_time = self.time self.start_time = self.time - self.run_time else: self.start_time = self.time self.end_time = self.time + self.run_time self.release_flag = False self.operation_id = operation_id self.operation_name = operation_name self.release_for_recomputation = [] def to_tuple(self): return (self.tensor.tensor_id, self.time) def __repr__(self): return f'id={self.tensor.tensor_id}, start_time={self.start_time}, end_time={self.end_time}, time={self.time}, access_type={self.access_type}, release_flag={self.release_flag}' class SwapTask(object): '''Date weighted interval''' def __init__(self, tensor, time, time_cost, task_type: TaskType, front_boundary=None, back_boundary=None): self.tensor = tensor self.time_cost = time_cost self.data_type = np.float64 self.task_type = task_type self.swap_task_id = None assert not (front_boundary is None and back_boundary is None) # 最早开始时间 self.front_boundary = front_boundary # 最晚结束时间 self.back_boundary = back_boundary self.time = time self.execute_time = None self.execute_ref = None self.start_time_ = None self.end_time_ = None @property def start_time(self): return self.start_time_ @start_time.setter def start_time(self, value): self.start_time_ = value if self.task_type == TaskType.swap_out: self.time = self.start_time_ @property def end_time(self): return self.end_time_ @end_time.setter def end_time(self, value): self.end_time_ = value if self.task_type == TaskType.swap_in: self.time = self.end_time_ @classmethod def from_access(cls, access: TensorAccess, weight, task_type, front_boundary=None, back_boundary=None): return cls(access.tensor, weight, access.time, access.tensor.swap_time, task_type, front_boundary=front_boundary, back_boundary=back_boundary) def __repr__(self): return f'id={self.tensor}, type={self.task_type}, start_time={self.start_time}, end_time={self.end_time}, time={self.time}' def numpy_ewma_vectorized(data, window): alpha = 2 / (window + 1.0) alpha_rev = 1 - alpha n = data.shape[0] pows = alpha_rev ** (np.arange(n + 1)) scale_arr = 1 / pows[:-1] offset = data[0] * pows[1:] pw0 = alpha * alpha_rev ** (n - 1) mult = data * pw0 * scale_arr cumsums = mult.cumsum() out = offset + cumsums * scale_arr[::-1] return out debug_num = 0 def create_model(n): model = Sequential() model.add(Dense(units=2048, activation='tanh', input_dim=n)) model.add(Dense(units=2048, activation='tanh')) model.add(Dense(units=1, activation='relu')) return model def load(opname, n): model = create_model(n) model.load_weights('model_parameter/' + opname + '_model.hdf5', by_name=True, skip_mismatch=True) return model def get_predicted_execution_time(op_name, inputs_of_model, logged_time: list): return logged_time[0] def liveness_analysis(tensor_access_list): global tensor_access_by_tensor # 活跃性分析结果生成 for job_id in range(len(tensor_access_list)): tmp = set() for i in range(len(tensor_access_list[job_id]) - 1, -1, -1): tensor_access = tensor_access_list[job_id][i] accesses_of_tensor = tensor_access_by_tensor[tensor_access.tensor.job_id][tensor_access.tensor] if tensor_access.tensor not in tmp and len(accesses_of_tensor) > 1 and tensor_access == accesses_of_tensor[-1]: # 参数不会释放 if not tensor_access.tensor.is_parameter: tmp.add(tensor_access.tensor) tensor_access.release_flag = True def is_overlap(task: SwapTask, target: SwapTask): return task != target and ( target.start_time < task.end_time < target.end_time or target.start_time < task.start_time < target.end_time or task.start_time < target.end_time < task.end_time or task.start_time < target.start_time < task.end_time) def get_free_intervals(target_task, swap_schedule, access_of_target_tensor, key=0, asc=True): target_task.tensor.update_swap_time() # 列出在可行区间内的所有空白时间区间,并按区间排序 if target_task.back_boundary - target_task.front_boundary < target_task.time_cost: return [] intervals = [] for task in swap_schedule: # if target_task.back_boundary < task.start_time: # continue # elif task.end_time < target_task.front_boundary: # break if target_task.front_boundary <= task.start_time < task.end_time <= target_task.back_boundary: intervals.append((task.start_time, task.end_time)) elif task.start_time < target_task.front_boundary < task.end_time < target_task.back_boundary: intervals.append((target_task.front_boundary, task.end_time)) elif target_task.front_boundary < task.start_time < target_task.back_boundary < task.end_time: intervals.append((task.start_time, target_task.back_boundary)) elif task.start_time < target_task.front_boundary < target_task.back_boundary < task.end_time: return [] intervals = sorted(intervals, key=lambda x: x[0]) # 区间融合,确保区间之间无交集 occupied_intervals = [] i = 0 while i < len(intervals): interval = intervals[i] l = interval[0] r = interval[1] flag = False while i < len(intervals) - 1 and intervals[i + 1][0] <= r: r = max(r, intervals[i + 1][1]) flag = True i += 1 occupied_intervals.append((l, r)) if not flag: i += 1 not_occupied_intervals = [] s = target_task.front_boundary for interval in occupied_intervals: if s < interval[0]: not_occupied_intervals.append((s, interval[0])) s = interval[1] if s < target_task.back_boundary: not_occupied_intervals.append((s, target_task.back_boundary)) if len(not_occupied_intervals) == 0: return [] i = 0 j = 0 # 按照区间起点排序 not_occupied_intervals = sorted(not_occupied_intervals, key=lambda x: x[key], reverse=False) # 防止区间与被调度张量的access重合 while j < len(access_of_target_tensor): if i >= len(not_occupied_intervals): break access = access_of_target_tensor[j] start, end = not_occupied_intervals[i] if start < access.start_time < end <= access.end_time: not_occupied_intervals[i] = (start, access.start_time) i += 1 elif start < access.start_time < access.end_time < end: not_occupied_intervals[i] = (start, access.start_time) not_occupied_intervals.insert(i + 1, (access.end_time, end)) i += 1 j += 1 elif start == access.start_time < end < access.end_time: not_occupied_intervals.pop(i) j += 1 elif access.start_time <= start < access.end_time < end: not_occupied_intervals[i] = (access.end_time, end) j += 1 elif access.start_time <= start < end <= access.end_time: not_occupied_intervals.pop(i) else: j += 1 # 按照区间终点排序 if not asc: not_occupied_intervals = sorted(not_occupied_intervals, key=lambda x: x[key], reverse=not asc) return not_occupied_intervals def generate_swap_recomputation_release_order(tensor_access_by_tensor, swap_scheduler, recomputations, job_num): swap_orders = defaultdict(list) release_orders = defaultdict(list) recomp_orders = defaultdict(list) for job_id in range(job_num): # 按id排序 tensor_accesses = sorted([i for tmp in tensor_access_by_tensor[job_id].values() for i in tmp], key=lambda x: x.tensor.tensor_id) # 按起始时间排序 swap_tasks = sorted(swap_scheduler[job_id], key=lambda x: x.start_time) for i in range(len(swap_tasks)): swap_tasks[i].swap_task_id = i releases = [] swaps = [] recomps = [] for access in tensor_accesses: if access.release_flag: releases.append((access.operation_id, access.tensor.tensor_id)) release_orders[job_id] = releases for access in recomputations: recomps.append((access.operation_id, access.tensor.tensor_id, access.release_for_recomputation)) recomp_orders[job_id] = recomps for task in swap_tasks: # if task.task_type==TaskType.swap_out: # (task_id, node_id(tensor_id), start_time, start_node, move_to_gpu, start_node_type) ref = task.execute_ref.operation_id swaps.append([task.tensor.tensor_id, task.execute_time, ref, 0 if task.task_type == TaskType.swap_out else 1, 1, task.start_time]) swap_orders[job_id] = list(map(lambda x: x[:-1], sorted(swaps, key=lambda x: x[-1]))) return release_orders, swap_orders, recomp_orders def draw_all_task(tensor_access_by_tensor, swap_scheduler, job_num): for job_id in range(job_num): tmp = list(tensor_access_by_tensor[job_id].values()) res = [] for sub_list in tmp: res.extend(sub_list) draw(sorted(res, key=lambda x: x.start_time), swap_scheduler[job_id]) class MemoryAnalyzer: def __init__(self, tensor_access_list, tensors): self.tensor_access_list = tensor_access_list self.tensors = tensors self.next_swap_tasks_index = 0 def insert_sort(self, list_with_order: list, list_b: list, cmp): # 升序 for obj_b in list_b: i = 0 mid = 0 j = len(list_with_order) - 1 while i < j: mid = (i + j) // 2 obj_mid = list_with_order[mid] flag = cmp(obj_mid, obj_b) if flag == -1: # mid<b if mid == i: # i=mid<=j, mid<b, 比较b和j flag2 = cmp(list_with_order[j], obj_b) if flag2 == -1: # i=mid<=j<b, 插入位置在j+1 mid = j elif flag2 == 1: # i=mid<b<j, 插入位置在j mid = j - 1 else: # i=mid<=j=b, 插入位置在j+1 mid = j break i = mid elif flag == 1: # b<mid if mid == j: # i<=mid=j, b<mid, 比较i和b flag2 = cmp(list_with_order[i], obj_b) if flag2 == -1: # i<b<mid=j, 插入位置在i+1 mid = i elif flag2 == 1: # b<i<mid=j, 插入位置在i mid = i - 1 else: # i=b<mid=j, 插入位置在i+1 mid = i break j = mid elif flag == 0: # b==mid,插入位置在mid+1 break list_with_order.insert(mid + 1, obj_b) return list_with_order def custom_cmp(self, x, y): if x.time < y.time: return -1 elif x.time > y.time: return 1 else: if x.start_time < y.start_time: return -1 elif x.start_time > y.start_time: return 1 else: # if isinstance(x,TensorAccess) and isinstance(y, SwapTask): # return 1 # elif isinstance(x, SwapTask) and isinstance(y, TensorAccess): # return -1 return 0 def custom_cmp_end_time(self, x, y): if x.end_time < y.end_time: return -1 elif x.end_time > y.end_time: return 1 else: return 0 def get_max_memory_used(self, swap_tasks, swapped_out_tensor): delta = len(swap_tasks) if self.next_swap_tasks_index == 0: # 初始化时间轴 tmp = copy.copy(self.tensor_access_list) tmp.extend(swap_tasks) self.time_axis = sorted(tmp, key=cmp_to_key(self.custom_cmp)) self.end_time_axis = sorted(copy.copy(tmp), key=cmp_to_key(self.custom_cmp_end_time)) # self.last_unused_swap_tasks = copy.copy(swap_tasks) else: # 更新时间轴 # assert swap_tasks[:self.next_swap_tasks_index] == self.last_unused_swap_tasks # self.last_unused_swap_tasks = copy.copy(swap_tasks) swap_tasks = swap_tasks[self.next_swap_tasks_index:] self.time_axis = self.insert_sort(self.time_axis, swap_tasks, self.custom_cmp) self.end_time_axis = self.insert_sort(self.end_time_axis, swap_tasks, self.custom_cmp_end_time) self.index_of_end_time_axis = {self.end_time_axis[i]: i for i in range(len(self.end_time_axis))} # 计算显存开销 # occupied by handle, cudnn, cuda stream and cudart memory_used = 0 max_memory_actual = float('-inf') in_gpu_tensors = set() max_memory_tensors = set() last_input_tensor_access = None max_last_access = None wait_to_be_released = [] max_time = None # foot_print = {} # 首先把输入的x,y以及所有没被swap out的参数载入显存,因为他们从上轮迭代结束时就一直在显存里面 for tensor in self.tensors: if tensor.in_gpu_at_beginning and tensor not in swapped_out_tensor: in_gpu_tensors.add(tensor) memory_used += tensor.size for time_index, event in enumerate(self.time_axis): i = len(wait_to_be_released) - 1 while i >= 0: access = wait_to_be_released[i] # 如果此刻时间已经过了释放时间,则释放该访问的附带影响 if event.time >= access.end_time: wait_to_be_released.pop(i) memory_used -= access.tensor.size in_gpu_tensors.remove(access.tensor) i -= 1 if isinstance(event, TensorAccess): if event.access_type == AccessType.output: if event.tensor not in in_gpu_tensors: # 新参数不额外占用空间 if event.operation_name not in optimizer_op: memory_used += event.tensor.size in_gpu_tensors.add(event.tensor) else: # 用完即释放的 # input本身并不增加gpu使用,swap in增加 if event.release_flag: wait_to_be_released.append(event) else: last_input_tensor_access = event elif isinstance(event, SwapTask): # 使用按照结束时间排序的时间轴进行倒序查找 last_event = None # idx = end_time_axis.index(event) idx = self.index_of_end_time_axis[event] for j in range(idx - 1, -1, -1): if isinstance(self.end_time_axis[j], TensorAccess) and self.end_time_axis[j].end_time <= event.start_time: last_event = self.end_time_axis[j] break if last_event is None: last_event = self.tensor_access_list[0] event.execute_ref = last_event event.execute_time = event.start_time - last_event.end_time if event.task_type == TaskType.swap_in: memory_used += event.tensor.size in_gpu_tensors.add(event.tensor) else: memory_used -= event.tensor.size in_gpu_tensors.remove(event.tensor) # foot_print[time] = memory_used if memory_used > max_memory_actual: # max_memory_actual与是否有考虑价值无关,单纯计量峰值 max_memory_actual = memory_used max_memory_tensors = copy.copy(in_gpu_tensors) max_last_access = last_input_tensor_access max_time = event.time self.next_swap_tasks_index = delta return max_memory_actual, max_memory_tensors, max_last_access, max_time, self.time_axis def run_global_memory_analysis(swap_tasks, swapped_out_tensor): global job_num global global_memory_analyzer max_memory = 0 max_memory_tensors = [] last_input_accesses = [] max_time = [] # foot_prints = [] time_axis = [] for job_id in range(job_num): job_max_memory, job_max_memory_tensors, last_input_access, now_time, t_axis = global_memory_analyzer[job_id].get_max_memory_used(swap_tasks[job_id], swapped_out_tensor) time_axis.append(t_axis) # foot_prints.append(foot_print) max_memory_tensors.extend(job_max_memory_tensors) last_input_accesses.append(last_input_access) max_time.append(now_time) max_memory += job_max_memory return max_memory, max_memory_tensors, last_input_accesses, max_time, time_axis def draw(tensor_access_list, swap_schedule): df = [] id_color = {'OTA': 'rgb(255, 0, 102)', 'ITA': 'rgb(68, 114, 196)', 'Swap In': 'rgb(237, 137, 69)', 'Swap Out': 'rgb(112, 173, 71)'} for tensor_access in tensor_access_list: # input 蓝色,output红色 df.append(dict(Task=f'tensor_id:{tensor_access.tensor.tensor_id}, size:{tensor_access.tensor.size}', Start=tensor_access.start_time, Finish=tensor_access.end_time, Resource='OTA' if tensor_access.access_type == AccessType.output else 'ITA')) for task in swap_schedule: df.append(dict(Task=f'tensor_id:{task.tensor.tensor_id}, size:{task.tensor.size}', Start=task.start_time, Finish=task.end_time, Resource='Swap In' if task.task_type == TaskType.swap_in else 'Swap Out')) fig = ff.create_gantt(df, colors=id_color, index_col='Resource', group_tasks=True, show_colorbar=True, showgrid_x=True, showgrid_y=True, title=f'ratio={ratio}') fig['layout']['xaxis'].update({'type': None}) fig.update_layout( height=900, width=1600, ) pyplt(fig, filename=f'../../pic/job{tensor_access_list[0].tensor.job_id}.html', auto_open=True) def try_swap_in(swap_in_task: SwapTask, swap_scheduler, access_of_target_tensor): # swap_in越晚越好,按结束时间降序排序 free_intervals = get_free_intervals(swap_in_task, swap_scheduler[swap_in_task.tensor.job_id], access_of_target_tensor, 1, asc=False) succeed = False for interval in free_intervals: if interval[1] - interval[0] >= swap_in_task.time_cost: swap_in_task.end_time = interval[1] swap_in_task.start_time = swap_in_task.end_time - swap_in_task.time_cost swap_scheduler[swap_in_task.tensor.job_id].append(swap_in_task) succeed = True break if not succeed: return False else: return True def can_next_input_access_swap_in(i, all_access_of_tensor, swap_out_task, swap_scheduler): # 至少将第一个访问swap in才算成功,后续的能换入的话,则把前一个的release_flag设为True access = all_access_of_tensor[i] swap_in_task = SwapTask(access.tensor, access.time, access.tensor.swap_time, TaskType.swap_in, front_boundary=swap_out_task.end_time if swap_out_task.end_time > all_access_of_tensor[i - 1].end_time else all_access_of_tensor[i - 1].end_time, back_boundary=access.time) return try_swap_in(swap_in_task, swap_scheduler, tensor_access_by_tensor[swap_in_task.tensor.job_id][swap_in_task.tensor]) def get_framework_info(info, logged_time, job_id): global global_tensors tensors = {} tensor_access_list = [] global_time = 0 parameter = [] # tensor_id: execution time of operator which generate the tensor operator_execution_time = [] # for output_tensor_id, input_tensor_id, output_tensor_size, operation_name, is_parameter, shape, inputs_of_model in info: for tensor_info, input_tensor_id, operation_name, operation_id, is_parameter, inputs_of_model, _ in info: # is_parameter: 生成的张量是否为参数 # 输入的为Byte # 转换为MB input_tensors = [] for tensor_id in input_tensor_id: input_tensor = tensors[tensor_id] input_tensors.append(input_tensor) time_cost = get_predicted_execution_time(operation_name, inputs_of_model, logged_time[operation_id]) for output_tensor_id, output_tensor_size, shape in tensor_info: output_tensor_size = output_tensor_size / 1000000 operator_execution_time.append(time_cost) if operation_name in optimizer_op: is_parameter = 1 output_tensor = Tensor(tensor_id=output_tensor_id, job_id=job_id, size=output_tensor_size, source_tensors=input_tensors, recomputation_time=time_cost, is_parameter=is_parameter, shape=shape) output_access = TensorAccess(tensor=output_tensor, time=global_time + time_cost, run_time=time_cost, access_type=AccessType.output, operation_id=operation_id, operation_name=operation_name) tensor_access_list.append(output_access) tensors[output_tensor.tensor_id] = output_tensor if is_parameter: parameter.append(output_tensor) for tensor_id in input_tensor_id: input_tensor = tensors[tensor_id] input_access = TensorAccess(tensor=input_tensor, time=global_time, run_time=time_cost, access_type=AccessType.input, operation_id=operation_id, operation_name=operation_name) tensor_access_list.append(input_access) global_time += time_cost tensors = list(tensors.values()) global_tensors[job_id] = tensors tensor_access_list = sorted(tensor_access_list, key=lambda x: x.time) dic = defaultdict(list) for access in tensor_access_list: dic[access.tensor].append(access) for k, v in dic.items(): dic[k] = sorted(v, key=lambda x: x.time) tensor_access_by_tensor[job_id] = dic swap_scheduler = [] # 对参数进行swap in调度 # earliest_swap = None # earliest_time = float('inf') # 从最早的参数开始安排 parameter = sorted(parameter, key=lambda x: dic[x][0].start_time) return tensor_access_list, swap_scheduler, parameter, operator_execution_time # 随机生成数据用的参数 times = 150 tensors = 50 time_scale = times ratio = 1 # 全局变量 job_num = 0 global_tensor_access = [[]] tensor_access_by_tensor = [] weight = 1 jobs_weights = [] # jobs_weight = [1, 1, 1, 1, 1] total_memory = 0 enable_recomputation = True global_graphs = [] global_tensors = {} swap_scheduler = [] parameters = [] models = {} global_memory_analyzer = [] # load_all_model() def init(logged_times: list, gpu: int): global job_num global global_tensor_access global tensor_access_by_tensor global total_memory global handle global jobs_weights global global_graphs global global_tensors global swap_scheduler global parameters global global_memory_analyzer global_tensor_access = [[]] tensor_access_by_tensor = [] global_tensors = {} swap_scheduler = [] parameters = [] global_memory_analyzer = [] graphs = global_graphs jobs_weights = [weight for _ in range(len(graphs))] tensor_access_by_tensor = [[] for _ in range(job_num)] # 获取当前剩余显存总量 if not debug_mod: nvmlInit() handle = nvmlDeviceGetHandleByIndex(gpu) total_memory = nvmlDeviceGetMemoryInfo(handle).free / 1000000 else: total_memory = 6000 job_num = len(graphs) tmp = [get_framework_info(graphs[i], logged_times[i], i) for i in range(job_num)] global_tensor_access = [tmp[i][0] for i in range(job_num)] swap_scheduler = [tmp[i][1] for i in range(job_num)] parameters = [tmp[i][2] for i in range(job_num)] for i in range(job_num): global_memory_analyzer.append(MemoryAnalyzer(global_tensor_access[i], global_tensors[i])) def add_job(graph, job_id, gpu: int): global global_graphs assert job_id == len(global_graphs) or global_graphs[job_id] is None if job_id == len(global_graphs): global_graphs.append(graph) else: global_graphs[job_id] = graph init([[] for _ in range(job_num)], gpu) def remove_job(job_id, gpu: int): global global_graphs global_graphs[job_id] = None init([], gpu) def generate_scheduling_plan(logged_times, gpu: int): # 如果是此时logged_times已经清空,则 # logged_times: [[(operation_id, [time, time, time])]],外层索引为job_id global total_memory global global_tensors init(logged_times, gpu) # 指数加权平均更新估计时间 tensor_nums = list(map(lambda x: len(x), tensor_access_by_tensor)) swap_out_number_limits = [int(weight * tensor_num) for weight, tensor_num in zip(jobs_weights, tensor_nums)] swap_out_number = [0 for _ in tensor_nums] swapped_out_tensor = set() swapped_in_source_tensor = set() swap_out_dict = {} swapped_in_access = set() recomputations = [] recomputation_tensor = set() # key:tensor,value:[所有释放这个张量的重计算对应的在recomputations中的index] # 上一轮没有成功的swap_out时为False swapped_flag = True recomputation_flag = True iter = 0 original_memory_used = 0 last_memory_used = 0 job_id_ordered_by_weights = list(map(lambda x: x[0], sorted([(job_id, weights) for job_id, weights in enumerate(jobs_weights)], key=lambda x: x[1], reverse=True))) max_memory_footprint = [] # draw_all_task(tensor_access_by_tensor, swap_scheduler, job_num) while swapped_flag or (recomputation_flag and enable_recomputation): # MB if not debug_mod: total_memory = nvmlDeviceGetMemoryInfo(handle).free / 1000000 else: total_memory = 6000 max_memory, max_tensors, last_input_accesses, max_time, time_axis = run_global_memory_analysis(swap_scheduler, swapped_out_tensor) max_memory_footprint.append(max_memory) # 最后三次迭代的峰值,做一阶差分,结果的最大值大于上一次峰值的0.05%以上或迭代次数小于100轮才继续~` if len(max_memory_footprint) > 3 and max([max_memory_footprint[i] - max_memory_footprint[i + 1] for i in range(len(max_memory_footprint) - 3, len(max_memory_footprint) - 1)]) < max_memory_footprint[ -1] * 0.0005 and iter > 100: break if iter == 0: original_memory_used = max_memory liveness_analysis(global_tensor_access) else: last_memory_used = max_memory # print(f'iter:{iter}, max_memory:{max_memory}') max_tensors = sorted(max_tensors, key=lambda x: x.size, reverse=True) if swapped_flag: swapped_flag = False for tensor in max_tensors: # 对该张量进行swap_out计划的安排 is_new_parameter = tensor.is_parameter and tensor_access_by_tensor[tensor.job_id][tensor][0].operation_name in optimizer_op and len(tensor_access_by_tensor[tensor.job_id][tensor]) == 1 if not is_new_parameter: if swap_out_number[tensor.job_id] <= swap_out_number_limits[tensor.job_id] and len(tensor_access_by_tensor[tensor.job_id][tensor]) > 1: # swapped_out表示所有可能的swap_in已经调度过了 if tensor not in swapped_out_tensor: all_access_of_tensor = tensor_access_by_tensor[tensor.job_id][tensor][1:] # 首先确定swap_out的时间范围,最迟不能超过此时此刻,最早不能超过第一次访问结束时刻 output_access = tensor_access_by_tensor[tensor.job_id][tensor][0] assert output_access.access_type == AccessType.output if last_input_accesses[tensor.job_id] is not None: # 此时此刻 back_boundary = last_input_accesses[tensor.job_id].time else: last_time_access = tensor_access_by_tensor[tensor.job_id][tensor][-1] back_boundary = last_time_access.time + tensor.swap_time succeed = False front_boundary = output_access.time # failed_input_access = [] swap_out_succeed = True have_next_ITA = True # 如果是因为swap out放不下,则不用继续更新可行区间了,直接break while not succeed and front_boundary < back_boundary and swap_out_succeed and have_next_ITA: swap_out_task = SwapTask(tensor, output_access.time, tensor.swap_time, TaskType.swap_out, front_boundary=front_boundary, back_boundary=back_boundary) free_intervals = get_free_intervals(swap_out_task, swap_scheduler[swap_out_task.tensor.job_id], tensor_access_by_tensor[tensor.job_id][tensor]) selected_first_access_index = None # 选出能容纳该任务的剩余空间 swap_out_succeed = False have_next_ITA = False for interval in free_intervals: if interval[1] - interval[0] >= swap_out_task.time_cost: swap_out_succeed = True swap_out_task.start_time = interval[0] swap_out_task.end_time = swap_out_task.start_time + swap_out_task.time_cost swap_scheduler[swap_out_task.tensor.job_id].append(swap_out_task) # 看一下后面第一个swap_in能否放下 for i, access in enumerate(all_access_of_tensor): # 找到后面第一个访问 if access.start_time >= swap_out_task.end_time: have_next_ITA = True if can_next_input_access_swap_in(i, all_access_of_tensor, swap_out_task, swap_scheduler): swapped_out_tensor.add(tensor) swap_out_dict[tensor] = swap_out_task swapped_in_access.add(access) swap_out_number[tensor.job_id] += 1 selected_first_access_index = i succeed = True swapped_flag = True else: # failed_input_access.append(access) swap_scheduler[swap_out_task.tensor.job_id].remove(swap_out_task) # 修正swap_out_task前向限制为这个失败的input_access的结束时间 front_boundary = access.end_time assert tensor not in swapped_out_tensor # swapped_out_tensor.remove(tensor) break if not succeed: if swap_out_task in swap_scheduler[swap_out_task.tensor.job_id]: swap_scheduler[swap_out_task.tensor.job_id].remove(swap_out_task) # 如果不是因为swap out没安排下则重新生成区间 break else: break # 安排失败 if not succeed: continue if not is_new_parameter: # 后续的能换入的话,则把前一个的release_flag设为True for i in range(selected_first_access_index + 1, len(all_access_of_tensor)): access = all_access_of_tensor[i] if i == 0 or access in swapped_in_access: continue else: if can_next_input_access_swap_in(i, all_access_of_tensor, swap_out_task, swap_scheduler): # print(f'成功{access}') swapped_in_access.add(access) if all_access_of_tensor[i - 1].start_time > swap_out_task.end_time: all_access_of_tensor[i - 1].release_flag = True if swapped_flag: break # 如果是新参数,则尝试对新参数进行swap out,对对应的旧参数进行swap in else: if tensor not in swapped_out_tensor: output_access = tensor_access_by_tensor[tensor.job_id][tensor][0] assert output_access.access_type == AccessType.output swap_out_task = SwapTask(tensor, time=output_access.time, time_cost=tensor.swap_time, task_type=TaskType.swap_out, front_boundary=output_access.end_time, back_boundary=float('inf')) free_intervals = get_free_intervals(swap_out_task, swap_scheduler[swap_out_task.tensor.job_id], tensor_access_by_tensor[tensor.job_id][tensor]) for interval in free_intervals: if interval[1] - interval[0] >= swap_out_task.time_cost: swap_out_task.start_time = interval[0] swap_out_task.end_time = swap_out_task.start_time + swap_out_task.time_cost swap_scheduler[swap_out_task.tensor.job_id].append(swap_out_task) # 找到对应的旧参数张量 # 由于二者可行域无关,所以直接查看对应的swap in 能否调度 for t in tensor.source_tensors: if t.is_parameter and t not in swapped_in_source_tensor: # 试图swap in # 找到第一次input访问(feed_dict不实际使用) first_access = tensor_access_by_tensor[t.job_id][t][1] assert first_access.access_type == AccessType.input swap_in_task = SwapTask(t, first_access.time, first_access.tensor.swap_time, TaskType.swap_in, front_boundary=0, back_boundary=first_access.start_time) res = try_swap_in(swap_in_task, swap_scheduler, tensor_access_by_tensor[t.job_id][t]) # assert not res, f'swap in parameter:{t} failed' if res: swapped_in_source_tensor.add(t) swapped_out_tensor.add(tensor) swap_out_dict[tensor] = swap_out_task swapped_in_access.add(first_access) swap_out_number[tensor.job_id] += 1 swapped_flag = True else: swap_scheduler[swap_out_task.tensor.job_id].remove(swap_out_task) assert tensor not in swapped_out_tensor break break elif enable_recomputation: recomputation_flag = False # 需要重计算 if max_memory >= total_memory: for job_id in job_id_ordered_by_weights: max_tensors_filtered = [] for tensor in max_tensors: # 张量不是参数,没被逐出过,且他的所有源张量从未被swap或recomputation if not tensor.is_parameter and tensor not in swapped_out_tensor and tensor.source_tensors is not None and len(tensor.source_tensors) > 0 and \ False not in [t not in swapped_out_tensor for t in tensor.source_tensors] and False not in [t not in recomputations for t in tensor.source_tensors]: max_tensors_filtered.append(tensor) if len(max_tensors_filtered) == 0: continue max_tensors_by_metric = sorted(max_tensors_filtered, key=lambda x: x.recomputation_metric, reverse=True) # 选取metric最大的张量 tensor = max_tensors_by_metric[0] # 找到此刻对应的下一个访问 now_time = max_time[job_id] all_access_of_tensor = tensor_access_by_tensor[tensor.job_id][tensor] for i, access in enumerate(all_access_of_tensor): if access.access_type == AccessType.input and access not in recomputations: if access.start_time >= now_time: for source_tensor in access.tensor.source_tensors: accesses = tensor_access_by_tensor[source_tensor.job_id][source_tensor] for temp_acc in accesses: #  确保source被release过的不进行重计算 if temp_acc.release_flag and temp_acc.end_time <= access.start_time: break else: recomputations.append(access) all_access_of_tensor[i - 1].release_flag = True recomputation_flag = True recomputation_tensor.add(access.tensor) break break iter += 1 # fig = go.Figure(data=[go.Scatter(x=list(original_memory_footprint[0].keys()), y=list(original_memory_footprint[0].values())), go.Scatter(x=list(foot_prints[0].keys()), y=list(foot_prints[0].values()))]) # plotly.offline.plot(fig, filename='../../pic/footprint.html') # if not debug_mod: # total_memory = nvmlDeviceGetMemoryInfo(handle).free / 1000000 # else: # total_memory = 6000 # stats = 'succeed' if max_memory < total_memory else ' failure' # print(f'scheduling {stats}') # draw_all_task(tensor_access_by_tensor, swap_scheduler, job_num) memory_saved_ratio = format((1 - last_memory_used / original_memory_used) * 100, '.2f') print(f'memory_saved_ratio:{memory_saved_ratio}%') print(f'swap ratio:{len(swap_scheduler[0]) / len(global_tensors)}') # print(f'recomputations:{recomputations}') return generate_swap_recomputation_release_order(tensor_access_by_tensor, swap_scheduler, recomputations, job_num) def multiprocess_init(global_message_queue: multiprocessing.Queue, global_control_queue: multiprocessing.Queue, total_job_number): # swap_order = [(20, 0, 20, 0)] # control_messages = [] # control_message = [swap_order, [], []] # control_messages.append(control_message) # global_control_queue.put(control_messages) logged_times = [] log_repeat = 0 alpha = 0.9 second_schedule_finished = False # todo 设置从executor到algorithm的job_id的映射 map_out_to_in = {} map_in_to_out = {} global job_num job_num = 0 while True: if not global_message_queue.empty(): global_message = global_message_queue.get() job_id = global_message[0] message_type = global_message[1][0] message_graph = global_message[1][1] if message_type == 0: # print("job_id =", job_id) job_num += 1 map_out_to_in[job_id] = job_num - 1 map_in_to_out[job_num - 1] = job_id job_id_in = job_num - 1 logged_times.append([]) global_graphs.append(message_graph) tensor_num = len(message_graph) # with open("../../global_graphs", "wb") as f1: # pickle.dump(global_graphs, f1) for i in range(tensor_num): # print(message_graph[i][6]) logged_times[job_id_in].append([message_graph[i][6]]) s = time.time() if job_num == total_job_number: release_order, swap_order, recomputation_order = generate_scheduling_plan(logged_times, 0) print(f'time:{time.time() - s}') control_messages = {} for i in range(job_num): # print(swap_order) control_message = [swap_order[i], release_order[i], recomputation_order[i]] control_messages[map_in_to_out[i]] = control_message global_control_queue.put(control_messages) else: job_id_in = map_out_to_in[job_id] total_time_old = 0 for run_time in logged_times[job_id_in]: total_time_old += run_time[0] total_time_new = 0 for run_time in message_graph: total_time_new += run_time[1] change_rate = abs(total_time_new - total_time_old) / total_time_old print("change rate is ", change_rate) # print("total time new is", total_time_new) # print("total time old is", total_time_old) if change_rate > 0.3: is_replan = True else: is_replan = False # with open("./log/total_time.txt", "a") as f1: # print(total_time_new, file=f1) # todo 此处控制了在一定轮数之后才进行决策 log_repeat += 1 if log_repeat > 0 and (is_replan or (not second_schedule_finished)): second_schedule_finished = True # with open("../../logged_times", "wb") as f1: # pickle.dump(logged_times, f1) for node_message in message_graph: time_new = node_message[1] * alpha + logged_times[job_id_in][node_message[0]][0] * (1 - alpha) logged_times[job_id_in][node_message[0]] = [time_new] release_order, swap_order, recomputation_order = generate_scheduling_plan(logged_times, 0) print(logged_times) control_messages = {} for i in range(job_num): print(swap_order) control_message = [swap_order[i], release_order[i], recomputation_order[i]] control_messages[map_in_to_out[i]] = control_message global_control_queue.put(control_messages) # print(logged_times[0]) if debug_mod and __name__ == '__main__': import pickle with open('../../global_graphs', 'rb') as f: g = pickle.load(f) global_graphs = g with open('../../logged_times', 'rb') as f: logged_times = pickle.load(f) job_num = 1 # profiler = LineProfiler() # profiler.add_function(get_free_intervals) # # profiler.add_function(get_occupied_intervals) # # profiler.add_function(MemoryAnalyzer.get_max_memory_used) # # profiler.add_function(run_global_memory_analysis) # profiler_wrapper = profiler(generate_scheduling_plan) # res = profiler_wrapper(logged_times, 0) # profiler.print_stats() release_order, swap_order, recomputation_order = generate_scheduling_plan(logged_times, 0)
[]
[]
[ "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_VISIBLE_DEVICES"]
python
1
0
disentanglement_lib/data/ground_truth/norb.py
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """SmallNORB dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from disentanglement_lib.data.ground_truth import ground_truth_data from disentanglement_lib.data.ground_truth import util import numpy as np import PIL from six.moves import range from six.moves import zip import tensorflow.compat.v1 as tf SMALLNORB_TEMPLATE = os.path.join( os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "small_norb", "smallnorb-{}-{}.mat") SMALLNORB_CHUNKS = [ "5x46789x9x18x6x2x96x96-training", "5x01235x9x18x6x2x96x96-testing", ] class SmallNORB(ground_truth_data.GroundTruthData): """SmallNORB dataset. The data set can be downloaded from https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/. Images are resized to 64x64. The ground-truth factors of variation are: 0 - category (5 different values) 1 - elevation (9 different values) 2 - azimuth (18 different values) 3 - lighting condition (6 different values) The instance in each category is randomly sampled when generating the images. """ def __init__(self): self.images, features = _load_small_norb_chunks(SMALLNORB_TEMPLATE, SMALLNORB_CHUNKS) self.factor_sizes = [5, 10, 9, 18, 6] # Instances are not part of the latent space. self.latent_factor_indices = [0, 2, 3, 4] self.num_total_factors = features.shape[1] self.index = util.StateSpaceAtomIndex(self.factor_sizes, features) self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes, self.latent_factor_indices) @property def num_factors(self): return self.state_space.num_latent_factors @property def factors_num_values(self): return [self.factor_sizes[i] for i in self.latent_factor_indices] @property def observation_shape(self): return [64, 64, 1] def sample_factors(self, num, random_state): """Sample a batch of factors Y.""" return self.state_space.sample_latent_factors(num, random_state) def sample_observations_from_factors(self, factors, random_state): all_factors = self.state_space.sample_all_factors(factors, random_state) indices = self.index.features_to_index(all_factors) return np.expand_dims(self.images[indices].astype(np.float32), axis=3) def _load_small_norb_chunks(path_template, chunk_names): """Loads several chunks of the small norb data set for final use.""" list_of_images, list_of_features = _load_chunks(path_template, chunk_names) features = np.concatenate(list_of_features, axis=0) features[:, 3] = features[:, 3] / 2 # azimuth values are 0, 2, 4, ..., 24 return np.concatenate(list_of_images, axis=0), features def _load_chunks(path_template, chunk_names): """Loads several chunks of the small norb data set into lists.""" list_of_images = [] list_of_features = [] for chunk_name in chunk_names: norb = _read_binary_matrix(path_template.format(chunk_name, "dat")) list_of_images.append(_resize_images(norb[:, 0])) norb_class = _read_binary_matrix(path_template.format(chunk_name, "cat")) norb_info = _read_binary_matrix(path_template.format(chunk_name, "info")) list_of_features.append(np.column_stack((norb_class, norb_info))) return list_of_images, list_of_features def _read_binary_matrix(filename): """Reads and returns binary formatted matrix stored in filename.""" with tf.gfile.GFile(filename, "rb") as f: s = f.read() magic = int(np.frombuffer(s, "int32", 1)) ndim = int(np.frombuffer(s, "int32", 1, 4)) eff_dim = max(3, ndim) raw_dims = np.frombuffer(s, "int32", eff_dim, 8) dims = [] for i in range(0, ndim): dims.append(raw_dims[i]) dtype_map = { 507333717: "int8", 507333716: "int32", 507333713: "float", 507333715: "double" } data = np.frombuffer(s, dtype_map[magic], offset=8 + eff_dim * 4) data = data.reshape(tuple(dims)) return data def _resize_images(integer_images): resized_images = np.zeros((integer_images.shape[0], 64, 64)) for i in range(integer_images.shape[0]): image = PIL.Image.fromarray(integer_images[i, :, :]) image = image.resize((64, 64), PIL.Image.ANTIALIAS) resized_images[i, :, :] = image return resized_images / 255.
[]
[]
[ "DISENTANGLEMENT_LIB_DATA" ]
[]
["DISENTANGLEMENT_LIB_DATA"]
python
1
0
ais/target.go
// Package ais provides core functionality for the AIStore object storage. /* * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. */ package ais import ( "context" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time" "github.com/NVIDIA/aistore/3rdparty/atomic" "github.com/NVIDIA/aistore/3rdparty/glog" "github.com/NVIDIA/aistore/ais/backend" "github.com/NVIDIA/aistore/cluster" "github.com/NVIDIA/aistore/cmn" "github.com/NVIDIA/aistore/cmn/cos" "github.com/NVIDIA/aistore/cmn/debug" "github.com/NVIDIA/aistore/cmn/mono" "github.com/NVIDIA/aistore/dbdriver" "github.com/NVIDIA/aistore/dsort" "github.com/NVIDIA/aistore/ec" "github.com/NVIDIA/aistore/etl" "github.com/NVIDIA/aistore/fs" "github.com/NVIDIA/aistore/health" "github.com/NVIDIA/aistore/memsys" "github.com/NVIDIA/aistore/mirror" "github.com/NVIDIA/aistore/nl" "github.com/NVIDIA/aistore/reb" "github.com/NVIDIA/aistore/res" "github.com/NVIDIA/aistore/stats" "github.com/NVIDIA/aistore/transport" "github.com/NVIDIA/aistore/volume" "github.com/NVIDIA/aistore/xaction" "github.com/NVIDIA/aistore/xreg" ) const dbName = "ais.db" const clusterClockDrift = 5 * time.Millisecond // is expected to be bounded by type ( regstate struct { sync.Mutex disabled atomic.Bool // target was unregistered by internal event (e.g, all mountpaths are down) } backends map[string]cluster.BackendProvider // main targetrunner struct { httprunner backend backends fshc *health.FSHC fsprg fsprungroup reb *reb.Reb res *res.Res db dbdriver.Driver transactions transactions regstate regstate // the state of being registered with the primary, can be (en/dis)abled via API } ) // interface guard var _ cos.Runner = (*targetrunner)(nil) ////////////// // backends // ////////////// func (b backends) init(t *targetrunner, starting bool) { backend.Init() ais := backend.NewAIS(t) b[cmn.ProviderAIS] = ais // ais cloud is always present config := cmn.GCO.Get() if aisConf, ok := config.Backend.ProviderConf(cmn.ProviderAIS); ok { if err := ais.Apply(aisConf, "init"); err != nil { glog.Errorf("%s: %v - proceeding to start anyway...", t.si, err) } } b[cmn.ProviderHTTP], _ = backend.NewHTTP(t, config) if err := b.initExt(t, starting); err != nil { cos.ExitLogf("%v", err) } } // 3rd part cloud: empty stubs unless populated via build tags // NOTE: write access to backends - other than target startup is also invoked // via primary startup (see earlystart for "choosing remote backends") func (b backends) initExt(t *targetrunner, starting bool) (err error) { config := cmn.GCO.Get() for provider := range b { if provider == cmn.ProviderHTTP || provider == cmn.ProviderAIS { // always present continue } if _, ok := config.Backend.Providers[provider]; !ok { if !starting { glog.Errorf("Warning: %s: delete %q backend", t.si, provider) } delete(b, provider) } } for provider := range config.Backend.Providers { var add string switch provider { case cmn.ProviderAmazon: if _, ok := b[provider]; !ok { b[provider], err = backend.NewAWS(t) add = provider } case cmn.ProviderAzure: if _, ok := b[provider]; !ok { b[provider], err = backend.NewAzure(t) add = provider } case cmn.ProviderGoogle: if _, ok := b[provider]; !ok { b[provider], err = backend.NewGCP(t) add = provider } case cmn.ProviderHDFS: if _, ok := b[provider]; !ok { b[provider], err = backend.NewHDFS(t) add = provider } default: err = fmt.Errorf(cmn.FmtErrUnknown, t.si, "backend provider", provider) } if err != nil { err = _overback(err) } if err != nil { return } if add != "" && !starting { glog.Errorf("Warning: %s: add %q backend", t.si, add) } } return } func _overback(err error) error { if _, ok := err.(*cmn.ErrInitBackend); !ok { return err } if !daemon.cli.overrideBackends { return fmt.Errorf("%v - consider using '-override_backends' command-line", err) } glog.Warningf("%v - overriding, proceeding anyway", err) return nil } /////////////////// // target runner // /////////////////// func (t *targetrunner) init(config *cmn.Config) { t.initNetworks() tid, generated := initTID(config) if generated && len(config.FSP.Paths) > 0 { // in an unlikely case of losing all mountpath-stored IDs but still having a volume tid = volume.RecoverTID(tid, config.FSP.Paths) } t.si.Init(tid, cmn.Target) cos.InitShortID(t.si.Digest()) memsys.Init(t.si.ID(), t.si.ID()) newVol := volume.Init(t, config, daemon.cli.target.allowSharedDisksAndNoDisks, daemon.cli.target.startWithLostMountpath) t.initHostIP() daemon.rg.add(t) ts := &stats.Trunner{T: t} // iostat below startedUp := ts.Init(t) daemon.rg.add(ts) t.statsT = ts // stats tracker k := newTargetKeepalive(t, ts, startedUp) daemon.rg.add(k) t.keepalive = k t.fsprg.init(t, newVol) // subgroup of the daemon.rg rungroup // Stream Collector - a singleton object with responsibilities that include: sc := transport.Init(ts) daemon.rg.add(sc) fshc := health.NewFSHC(t) daemon.rg.add(fshc) t.fshc = fshc if err := ts.InitCapacity(); err != nil { // goes after fs.New cos.ExitLogf("%s", err) } } func (t *targetrunner) initHostIP() { var hostIP string if hostIP = os.Getenv("AIS_HOST_IP"); hostIP == "" { return } var ( config = cmn.GCO.Get() port = config.HostNet.Port extAddr = net.ParseIP(hostIP) extPort = port ) if portStr := os.Getenv("AIS_HOST_PORT"); portStr != "" { portNum, err := cmn.ParsePort(portStr) cos.AssertNoErr(err) extPort = portNum } t.si.PublicNet.NodeHostname = extAddr.String() t.si.PublicNet.DaemonPort = strconv.Itoa(extPort) t.si.PublicNet.DirectURL = fmt.Sprintf("%s://%s:%d", config.Net.HTTP.Proto, extAddr.String(), extPort) glog.Infof("AIS_HOST_IP=%s; PubNetwork=%s", hostIP, t.si.URL(cmn.NetworkPublic)) // applies to intra-cluster networks unless separately defined if !config.HostNet.UseIntraControl { t.si.IntraControlNet = t.si.PublicNet } if !config.HostNet.UseIntraData { t.si.IntraDataNet = t.si.PublicNet } } func initTID(config *cmn.Config) (tid string, generated bool) { if tid = envDaemonID(cmn.Target); tid != "" { if err := cos.ValidateDaemonID(tid); err != nil { glog.Errorf("Warning: %v", err) } return } var err error if tid, err = fs.LoadNodeID(config.FSP.Paths); err != nil { cos.ExitLogf("%v", err) } if tid != "" { return } tid = genDaemonID(cmn.Target, config) err = cos.ValidateDaemonID(tid) debug.AssertNoErr(err) glog.Infof("t[%s] ID randomly generated", tid) generated = true return } func regDiskMetrics(tstats *stats.Trunner, mpi fs.MPI) { for _, mi := range mpi { for _, disk := range mi.Disks { tstats.RegDiskMetrics(disk) } } } func (t *targetrunner) Run() error { if err := t.si.Validate(); err != nil { cos.ExitLogf("%v", err) } config := cmn.GCO.Get() t.httprunner.init(config) cluster.Init(t) cluster.RegLomCacheWithHK(t) // metrics, disks first tstats := t.statsT.(*stats.Trunner) availablePaths, disabledPaths := fs.Get() if len(availablePaths) == 0 { cos.ExitLogf("%v", cmn.ErrNoMountpaths) } regDiskMetrics(tstats, availablePaths) regDiskMetrics(tstats, disabledPaths) t.statsT.RegMetrics(t.si) // + Prometheus, if configured fatalErr, writeErr := t.checkRestarted() if fatalErr != nil { cos.ExitLogf("%v", fatalErr) } if writeErr != nil { glog.Errorln("") glog.Error(writeErr) glog.Errorln("") } // register object type and workfile type if err := fs.CSM.Reg(fs.ObjectType, &fs.ObjectContentResolver{}); err != nil { cos.ExitLogf("%v", err) } if err := fs.CSM.Reg(fs.WorkfileType, &fs.WorkfileContentResolver{}); err != nil { cos.ExitLogf("%v", err) } // Init meta-owners and load local instances t.owner.bmd.init() t.owner.etl.init() smap, reliable := t.tryLoadSmap() if !reliable { smap = newSmap() } // Add self to the cluster map smap.Tmap[t.si.ID()] = t.si t.owner.smap.put(smap) if daemon.cli.target.standby { tstats.Standby(true) t.regstate.disabled.Store(true) glog.Warningf("%s not joining - standing by...", t.si) go func() { for !t.ClusterStarted() { time.Sleep(2 * config.Periodic.StatsTime.D()) glog.Flush() } }() // see endStartupStandby() } else { // discover primary and join cluster (compare with manual `cmn.AdminJoin`) if status, err := t.joinCluster(cmn.ActSelfJoinTarget); err != nil { glog.Errorf("%s failed to join cluster (status: %d, err: %v)", t.si, status, err) glog.Errorf("%s is terminating", t.si) return err } t.markNodeStarted() go func() { smap := t.owner.smap.get() cii := t.pollClusterStarted(config, smap.Primary) if daemon.stopping.Load() { return } if cii != nil { if status, err := t.joinCluster(cmn.ActSelfJoinTarget, cii.Smap.Primary.CtrlURL, cii.Smap.Primary.PubURL); err != nil { glog.Errorf("%s failed to re-join cluster (status: %d, err: %v)", t.si, status, err) return } } t.markClusterStarted() if t.fsprg.newVol && !config.TestingEnv() { config := cmn.GCO.BeginUpdate() fspathsSave(config) } }() } t.backend.init(t, true /*starting*/) db, err := dbdriver.NewBuntDB(filepath.Join(config.ConfigDir, dbName)) if err != nil { glog.Errorf("Failed to initialize DB: %v", err) return err } t.db = db defer cos.Close(db) // transactions t.transactions.init(t) t.reb = reb.New(t, config) t.res = res.New(t) // register storage target's handler(s) and start listening t.initRecvHandlers() ec.Init(t) mirror.Init() xreg.RegWithHK() marked := xreg.GetResilverMarked() if marked.Interrupted || daemon.resilver.required { go func() { if marked.Interrupted { glog.Info("Resuming resilver...") } else if daemon.resilver.required { glog.Infof("Starting resilver, reason: %q", daemon.resilver.reason) } t.runResilver(res.Args{}, nil /*wg*/) }() } dsort.InitManagers(db) dsort.RegisterNode(t.owner.smap, t.owner.bmd, t.si, t, t.statsT) defer etl.StopAll(t) // Always try to stop running ETLs. err = t.httprunner.run() // do it after the `run()` to retain `restarted` marker on panic fs.RemoveMarker(cmn.NodeRestartedMarker) return err } func (t *targetrunner) endStartupStandby() (err error) { smap := t.owner.smap.get() if err = smap.validate(); err != nil { return } daemon.cli.target.standby = false t.markNodeStarted() t.markClusterStarted() t.regstate.disabled.Store(false) tstats := t.statsT.(*stats.Trunner) tstats.Standby(false) glog.Infof("%s enabled and joined (%s)", t.si, smap.StringEx()) config := cmn.GCO.Get() if t.fsprg.newVol && !config.TestingEnv() { config = cmn.GCO.BeginUpdate() fspathsSave(config) } return } func (t *targetrunner) initRecvHandlers() { networkHandlers := []networkHandler{ {r: cmn.Buckets, h: t.bucketHandler, net: accessNetAll}, {r: cmn.Objects, h: t.objectHandler, net: accessNetAll}, {r: cmn.Daemon, h: t.daemonHandler, net: accessNetPublicControl}, {r: cmn.Metasync, h: t.metasyncHandler, net: accessNetIntraControl}, {r: cmn.Health, h: t.healthHandler, net: accessNetPublicControl}, {r: cmn.Xactions, h: t.xactHandler, net: accessNetIntraControl}, {r: cmn.EC, h: t.ecHandler, net: accessNetIntraData}, {r: cmn.Vote, h: t.voteHandler, net: accessNetIntraControl}, {r: cmn.Txn, h: t.txnHandler, net: accessNetIntraControl}, {r: cmn.ObjStream, h: transport.RxAnyStream, net: accessControlData}, {r: cmn.Download, h: t.downloadHandler, net: accessNetIntraControl}, {r: cmn.Sort, h: dsort.SortHandler, net: accessControlData}, {r: cmn.ETL, h: t.etlHandler, net: accessNetAll}, {r: cmn.Query, h: t.queryHandler, net: accessNetPublicControl}, {r: "/" + cmn.S3, h: t.s3Handler, net: accessNetPublicData}, {r: "/", h: t.writeErrURL, net: accessNetAll}, } t.registerNetworkHandlers(networkHandlers) } // stop gracefully func (t *targetrunner) Stop(err error) { // NOTE: vs metasync t.regstate.Lock() daemon.stopping.Store(true) t.regstate.Unlock() f := glog.Infof if err != nil { f = glog.Warningf } f("Stopping %s, err: %v", t.si, err) xreg.AbortAll() t.httprunner.stop(t.netServ.pub.s != nil && !isErrNoUnregister(err) /*rm from Smap*/) } func (t *targetrunner) checkRestarted() (fatalErr, writeErr error) { if fs.MarkerExists(cmn.NodeRestartedMarker) { t.statsT.Add(stats.RestartCount, 1) } else { fatalErr, writeErr = fs.PersistMarker(cmn.NodeRestartedMarker) } return } // // http handlers // // verb /v1/buckets func (t *targetrunner) bucketHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: t.httpbckget(w, r) case http.MethodDelete: t.httpbckdelete(w, r) case http.MethodPost: t.httpbckpost(w, r) case http.MethodHead: t.httpbckhead(w, r) default: cmn.WriteErr405(w, r, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodPost) } } // verb /v1/objects func (t *targetrunner) objectHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: t.httpobjget(w, r) case http.MethodHead: t.httpobjhead(w, r) case http.MethodPut: t.httpobjput(w, r) case http.MethodDelete: t.httpobjdelete(w, r) case http.MethodPost: t.httpobjpost(w, r) case http.MethodPatch: t.httpobjpatch(w, r) default: cmn.WriteErr405(w, r, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut) } } // verb /v1/slices // Non-public inerface func (t *targetrunner) ecHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: t.httpecget(w, r) default: cmn.WriteErr405(w, r, http.MethodGet) } } /////////////////////// // httpbck* handlers // /////////////////////// // GET /v1/buckets[/bucket-name] func (t *targetrunner) httpbckget(w http.ResponseWriter, r *http.Request) { var ( bckName string queryBcks cmn.QueryBcks ) apiItems, err := t.checkRESTItems(w, r, 0, true, cmn.URLPathBuckets.L) if err != nil { return } msg := &aisMsg{} if err := cmn.ReadJSON(w, r, &msg); err != nil { return } if len(apiItems) > 0 { bckName = apiItems[0] } if queryBcks, err = newQueryBcksFromQuery(bckName, r.URL.Query()); err != nil { t.writeErr(w, r, err) return } t.ensureLatestBMD(msg, r) switch msg.Action { case cmn.ActList: if queryBcks.Name == "" { t.listBuckets(w, r, queryBcks) return } t.handleListObjects(w, r, queryBcks, msg) case cmn.ActSummary: t.handleSummary(w, r, queryBcks, msg) default: t.writeErrAct(w, r, msg.Action) } } func (t *targetrunner) handleListObjects(w http.ResponseWriter, r *http.Request, queryBcks cmn.QueryBcks, msg *aisMsg) { bck := cluster.NewBckEmbed(cmn.Bck(queryBcks)) if err := bck.Init(t.owner.bmd); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = bck.Init(t.owner.bmd) } if err != nil { t.writeErr(w, r, err) return } } begin := mono.NanoTime() if ok := t.listObjects(w, r, bck, msg); !ok { return } delta := mono.SinceNano(begin) t.statsT.AddMany( cos.NamedVal64{Name: stats.ListCount, Value: 1}, cos.NamedVal64{Name: stats.ListLatency, Value: delta}, ) } func (t *targetrunner) handleSummary(w http.ResponseWriter, r *http.Request, queryBcks cmn.QueryBcks, msg *aisMsg) { bck := cluster.NewBckEmbed(cmn.Bck(queryBcks)) if bck.Name != "" { // Ensure that the bucket exists. if err := bck.Init(t.owner.bmd); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = bck.Init(t.owner.bmd) } if err != nil { t.writeErr(w, r, err) return } } } t.bucketSummary(w, r, bck, msg) } // DELETE { action } /v1/buckets/bucket-name // (evict | delete) (list | range) func (t *targetrunner) httpbckdelete(w http.ResponseWriter, r *http.Request) { msg := aisMsg{} if err := cmn.ReadJSON(w, r, &msg, true); err != nil { return } request := &apiRequest{after: 1, prefix: cmn.URLPathBuckets.L} if err := t.parseReq(w, r, request); err != nil { return } if err := request.bck.Init(t.owner.bmd); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = request.bck.Init(t.owner.bmd) } if err != nil { t.writeErr(w, r, err) return } } switch msg.Action { case cmn.ActEvictRemoteBck: keepMD := cos.IsParseBool(request.query.Get(cmn.URLParamKeepBckMD)) // HDFS buckets will always keep metadata so they can re-register later if request.bck.IsHDFS() || keepMD { nlp := request.bck.GetNameLockPair() nlp.Lock() defer nlp.Unlock() err := fs.DestroyBucket(msg.Action, request.bck.Bck, request.bck.Props.BID) if err != nil { t.writeErr(w, r, err) return } // Recreate bucket directories (now empty), since bck is still in BMD errs := fs.CreateBucket(msg.Action, request.bck.Bck, false /*nilbmd*/) if len(errs) > 0 { debug.AssertNoErr(errs[0]) t.writeErr(w, r, errs[0]) // only 1 err is possible for 1 bck } } case cmn.ActDeleteObjects, cmn.ActEvictObjects: lrMsg := &cmn.ListRangeMsg{} if err := cos.MorphMarshal(msg.Value, lrMsg); err != nil { t.writeErrf(w, r, cmn.FmtErrMorphUnmarshal, t.si, msg.Action, msg.Value, err) return } rns := xreg.RenewEvictDelete(msg.UUID, t, msg.Action /*xaction kind*/, request.bck, lrMsg) if rns.Err != nil { t.writeErr(w, r, rns.Err) return } xact := rns.Entry.Get() xact.AddNotif(&xaction.NotifXact{ NotifBase: nl.NotifBase{ When: cluster.UponTerm, Dsts: []string{equalIC}, F: t.callerNotifyFin, }, Xact: xact, }) go xact.Run(nil) default: t.writeErrAct(w, r, msg.Action) } } // POST /v1/buckets/bucket-name func (t *targetrunner) httpbckpost(w http.ResponseWriter, r *http.Request) { msg := &aisMsg{} if err := cmn.ReadJSON(w, r, msg); err != nil { return } request := &apiRequest{prefix: cmn.URLPathBuckets.L, after: 1} if err := t.parseReq(w, r, request); err != nil { return } t.ensureLatestBMD(msg, r) if err := request.bck.Init(t.owner.bmd); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = request.bck.Init(t.owner.bmd) } if err != nil { t.writeErr(w, r, err) return } } switch msg.Action { case cmn.ActPrefetchObjects: var ( err error lrMsg = &cmn.ListRangeMsg{} ) if !request.bck.IsRemote() { t.writeErrf(w, r, "%s: expecting remote bucket, got %s, action=%s", t.si, request.bck, msg.Action) return } if err = cos.MorphMarshal(msg.Value, lrMsg); err != nil { t.writeErrf(w, r, cmn.FmtErrMorphUnmarshal, t.si, msg.Action, msg.Value, err) return } rns := xreg.RenewPrefetch(msg.UUID, t, request.bck, lrMsg) xact := rns.Entry.Get() go xact.Run(nil) default: t.writeErrAct(w, r, msg.Action) } } // HEAD /v1/buckets/bucket-name func (t *targetrunner) httpbckhead(w http.ResponseWriter, r *http.Request) { var ( bucketProps cos.SimpleKVs err error code int ctx = context.Background() hdr = w.Header() request = &apiRequest{after: 1, prefix: cmn.URLPathBuckets.L} ) if err = t.parseReq(w, r, request); err != nil { return } inBMD := true if err = request.bck.Init(t.owner.bmd); err != nil { if !cmn.IsErrRemoteBckNotFound(err) { // is ais t.writeErr(w, r, err) return } inBMD = false } if glog.FastV(4, glog.SmoduleAIS) { pid := request.query.Get(cmn.URLParamProxyID) glog.Infof("%s %s <= %s", r.Method, request.bck, pid) } debug.Assert(!request.bck.IsAIS()) if request.bck.IsHTTP() { originalURL := request.query.Get(cmn.URLParamOrigURL) ctx = context.WithValue(ctx, cos.CtxOriginalURL, originalURL) if !inBMD && originalURL == "" { err = cmn.NewErrRemoteBckNotFound(request.bck.Bck) t.writeErrSilent(w, r, err, http.StatusNotFound) return } } // + cloud bucketProps, code, err = t.Backend(request.bck).HeadBucket(ctx, request.bck) if err != nil { if !inBMD { if code == http.StatusNotFound { err = cmn.NewErrRemoteBckNotFound(request.bck.Bck) t.writeErrSilent(w, r, err, code) } else { err = fmt.Errorf("failed to locate bucket %q, err: %v", request.bck, err) t.writeErr(w, r, err, code) } return } glog.Warningf("%s: bucket %s, err: %v(%d)", t.si, request.bck, err, code) bucketProps = make(cos.SimpleKVs) bucketProps[cmn.HdrBackendProvider] = request.bck.Provider bucketProps[cmn.HdrRemoteOffline] = strconv.FormatBool(request.bck.IsRemote()) } for k, v := range bucketProps { if k == cmn.HdrBucketVerEnabled && request.bck.Props != nil { if curr := strconv.FormatBool(request.bck.VersionConf().Enabled); curr != v { // e.g., change via vendor-provided CLI and similar glog.Errorf("%s: %s versioning got out of sync: %s != %s", t.si, request.bck, v, curr) } } hdr.Set(k, v) } } /////////////////////// // httpobj* handlers // /////////////////////// // GET /v1/objects/<bucket-name>/<object-name> // // Initially validates if the request is internal request (either from proxy // or target) and calls getObject. // // Checks if the object exists locally (if not, downloads it) and sends it back // If the bucket is in the Cloud one and ValidateWarmGet is enabled there is an extra // check whether the object exists locally. Version is checked as well if configured. func (t *targetrunner) httpobjget(w http.ResponseWriter, r *http.Request) { var ( features = cmn.GCO.Get().Client.Features request = &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} ) if err := t.parseReq(w, r, request); err != nil { return } ptime := isRedirect(request.query) if !t.isIntraCall(r.Header) && ptime == "" && !features.IsSet(cmn.FeatureDirectAccess) { t.writeErrf(w, r, "%s: %s(obj) is expected to be redirected (remaddr=%s)", t.si, r.Method, r.RemoteAddr) return } lom := cluster.AllocLOM(request.items[1]) t.getObject(w, r, request.query, request.bck, lom) cluster.FreeLOM(lom) } // getObject is main function to get the object. It doesn't check request origin, // so it must be done by the caller (if necessary). func (t *targetrunner) getObject(w http.ResponseWriter, r *http.Request, query url.Values, bck *cluster.Bck, lom *cluster.LOM) { var ( ptime = isRedirect(query) config = cmn.GCO.Get() started = time.Now() nanotim = mono.NanoTime() ) if nanotim&0x5 == 5 { if redelta := ptLatency(time.Now(), ptime); redelta != 0 { t.statsT.Add(stats.GetRedirLatency, redelta) } } if err := lom.Init(bck.Bck); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = lom.Init(bck.Bck) } if err != nil { t.writeErr(w, r, err) return } } if isETLRequest(query) { t.doETL(w, r, query.Get(cmn.URLParamUUID), bck, lom.ObjName) return } filename := query.Get(cmn.URLParamArchpath) if strings.HasPrefix(filename, lom.ObjName) { if rel, err := filepath.Rel(lom.ObjName, filename); err == nil { filename = rel } } goi := allocGetObjInfo() { goi.started = started goi.nanotim = nanotim goi.t = t goi.lom = lom goi.w = w goi.ctx = context.Background() goi.ranges = rangesQuery{Range: r.Header.Get(cmn.HdrRange), Size: 0} goi.archive = archiveQuery{ filename: filename, mime: query.Get(cmn.URLParamArchmime), } goi.isGFN = cos.IsParseBool(query.Get(cmn.URLParamIsGFNRequest)) goi.chunked = config.Net.HTTP.Chunked } if bck.IsHTTP() { originalURL := query.Get(cmn.URLParamOrigURL) goi.ctx = context.WithValue(goi.ctx, cos.CtxOriginalURL, originalURL) } if errCode, err := goi.getObject(); err != nil && err != errSendingResp { t.writeErr(w, r, err, errCode) } freeGetObjInfo(goi) } // PUT /v1/objects/bucket-name/object-name func (t *targetrunner) httpobjput(w http.ResponseWriter, r *http.Request) { request := &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} if err := t.parseReq(w, r, request); err != nil { return } ptime := isRedirect(request.query) if ptime == "" && !isIntraPut(r.Header) { t.writeErrf(w, r, "%s: %s(obj) is expected to be redirected or replicated", t.si, r.Method) return } objName := request.items[1] started := time.Now() if ptime != "" { if redelta := ptLatency(started, ptime); redelta != 0 { t.statsT.Add(stats.PutRedirLatency, redelta) } } if cs := fs.GetCapStatus(); cs.Err != nil || cs.PctMax > cmn.StoreCleanupWM { cs = t.OOS(nil) if cs.OOS { // fail this write t.writeErr(w, r, cs.Err, http.StatusInsufficientStorage) return } } lom := cluster.AllocLOM(objName) defer cluster.FreeLOM(lom) if err := lom.Init(request.bck.Bck); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = lom.Init(request.bck.Bck) } if err != nil { t.writeErr(w, r, err) return } } var ( handle string err, errdb error errCode int skipVC = cos.IsParseBool(request.query.Get(cmn.URLParamSkipVC)) archPathProvided = request.query.Has(cmn.URLParamArchpath) appendTyProvided = request.query.Has(cmn.URLParamAppendType) ) if skipVC { errdb = lom.AllowDisconnectedBackend(false) } else if lom.Load(true, false) == nil { errdb = lom.AllowDisconnectedBackend(true) } if errdb != nil { t.writeErr(w, r, errdb) return } if archPathProvided { errCode, err = t.doAppendArch(r, lom, started, request.query) } else if appendTyProvided { handle, errCode, err = t.doAppend(r, lom, started, request.query) if err == nil { w.Header().Set(cmn.HdrAppendHandle, handle) return } } else { errCode, err = t.doPut(r, lom, started, request.query, skipVC) } if err != nil { t.fsErr(err, lom.FQN) t.writeErr(w, r, err, errCode) } } // DELETE [ { action } ] /v1/objects/bucket-name/object-name func (t *targetrunner) httpobjdelete(w http.ResponseWriter, r *http.Request) { var ( msg aisMsg request = &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} ) if err := cmn.ReadJSON(w, r, &msg, true); err != nil { return } if err := t.parseReq(w, r, request); err != nil { return } if isRedirect(request.query) == "" { t.writeErrf(w, r, "%s: %s(obj) is expected to be redirected", t.si, r.Method) return } evict := msg.Action == cmn.ActEvictObjects lom := cluster.AllocLOM(request.items[1]) defer cluster.FreeLOM(lom) if err := lom.Init(request.bck.Bck); err != nil { t.writeErr(w, r, err) return } errCode, err := t.DeleteObject(lom, evict) if err != nil { if errCode == http.StatusNotFound { t.writeErrSilentf(w, r, http.StatusNotFound, "object %s/%s doesn't exist", lom.Bucket(), lom.ObjName) } else { t.writeErr(w, r, err, errCode) } return } // EC cleanup if EC is enabled ec.ECM.CleanupObject(lom) } // POST /v1/objects/bucket-name/object-name func (t *targetrunner) httpobjpost(w http.ResponseWriter, r *http.Request) { var ( msg cmn.ActionMsg query = r.URL.Query() ) if cmn.ReadJSON(w, r, &msg) != nil { return } switch msg.Action { case cmn.ActRenameObject: if isRedirect(query) == "" { t.writeErrf(w, r, "%s: %s-%s(obj) is expected to be redirected", t.si, r.Method, msg.Action) return } t.objMv(w, r, &msg) case cmn.ActPromote: if isRedirect(query) == "" && !t.isIntraCall(r.Header) { t.writeErrf(w, r, "%s: %s-%s(obj) is expected to be redirected or intra-called", t.si, r.Method, msg.Action) return } t.promoteFQN(w, r, &msg) default: t.writeErrAct(w, r, msg.Action) } } // HEAD /v1/objects/<bucket-name>/<object-name> // // Initially validates if the request is internal request (either from proxy // or target) and calls headObject. func (t *targetrunner) httpobjhead(w http.ResponseWriter, r *http.Request) { var ( features = cmn.GCO.Get().Client.Features request = &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} ) if err := t.parseReq(w, r, request); err != nil { return } if isRedirect(request.query) == "" && !t.isIntraCall(r.Header) && !features.IsSet(cmn.FeatureDirectAccess) { t.writeErrf(w, r, "%s: %s(obj) is expected to be redirected (remaddr=%s)", t.si, r.Method, r.RemoteAddr) return } lom := cluster.AllocLOM(request.items[1] /*objName*/) t.headObject(w, r, request.query, request.bck, lom) cluster.FreeLOM(lom) } // headObject is main function to head the object. It doesn't check request origin, // so it must be done by the caller (if necessary). func (t *targetrunner) headObject(w http.ResponseWriter, r *http.Request, query url.Values, bck *cluster.Bck, lom *cluster.LOM) { var ( invalidHandler = t.writeErr hdr = w.Header() checkExists = cos.IsParseBool(query.Get(cmn.URLParamCheckExists)) checkExistsAny = cos.IsParseBool(query.Get(cmn.URLParamCheckExistsAny)) silent = cos.IsParseBool(query.Get(cmn.URLParamSilent)) exists = true addedEC bool ) if silent { invalidHandler = t.writeErrSilent } if err := lom.Init(bck.Bck); err != nil { invalidHandler(w, r, err) return } if err := lom.Load(true /*cache it*/, false /*locked*/); err != nil { if !cmn.IsObjNotExist(err) { invalidHandler(w, r, err) return } exists = false } if glog.FastV(4, glog.SmoduleAIS) { pid := query.Get(cmn.URLParamProxyID) glog.Infof("%s %s(exists=%t) <= %s", r.Method, lom, exists, pid) } // * `checkExists` and `checkExistsAny` can be used to: // a) establish local object's presence on any of the local mountpaths, and // b) if located, restore the object to its default location. // * `checkExistsAny` tries to perform the b) even if the object does not have copies. // * see also: GFN if !exists { // lookup and restore the object to its proper location if (checkExists && lom.HasCopies()) || checkExistsAny { exists = lom.RestoreToLocation() } } if checkExists || checkExistsAny { if !exists { err := cmn.NewErrNotFound("%s: object %s", t.si, lom.FullName()) invalidHandler(w, r, err, http.StatusNotFound) } return } // NOTE: compare with `api.HeadObject()` // fill-in op := cmn.ObjectProps{Name: lom.ObjName, Bck: lom.Bucket(), Present: exists} if lom.Bck().IsAIS() { if !exists { err := cmn.NewErrNotFound("%s: object %s", t.si, lom.FullName()) invalidHandler(w, r, err, http.StatusNotFound) return } op.ObjAttrs = *lom.ObjAttrs() } else if exists { op.ObjAttrs = *lom.ObjAttrs() } else { // cold HEAD objAttrs, errCode, err := t.Backend(lom.Bck()).HeadObj(context.Background(), lom) if err != nil { err = fmt.Errorf(cmn.FmtErrFailed, t.si, "HEAD", lom, err) invalidHandler(w, r, err, errCode) return } op.ObjAttrs = *objAttrs } if exists { op.NumCopies = lom.NumCopies() if lom.Bck().Props.EC.Enabled { if md, err := ec.ObjectMetadata(lom.Bck(), lom.ObjName); err == nil { addedEC = true op.EC.DataSlices = md.Data op.EC.ParitySlices = md.Parity op.EC.IsECCopy = md.IsCopy op.EC.Generation = md.Generation } } } // to header op.ObjAttrs.ToHeader(hdr) err := cmn.IterFields(op, func(tag string, field cmn.IterField) (err error, b bool) { if !addedEC && strings.HasPrefix(tag, "ec-") { return nil, false } v := field.String() if v == "" { return nil, false } headerName := cmn.PropToHeader(tag) hdr.Set(headerName, v) return nil, false }) debug.AssertNoErr(err) } // PATCH /v1/objects/<bucket-name>/<object-name> // By default, adds or updates existing custom keys. Will remove all existing keys and // replace them with the specified ones _iff_ `cmn.URLParamNewCustom` is set. func (t *targetrunner) httpobjpatch(w http.ResponseWriter, r *http.Request) { var ( msg cmn.ActionMsg features = cmn.GCO.Get().Client.Features request = &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} ) if err := t.parseReq(w, r, request); err != nil { return } if isRedirect(request.query) == "" && !t.isIntraCall(r.Header) && !features.IsSet(cmn.FeatureDirectAccess) { t.writeErrf(w, r, "%s: %s(obj) is expected to be redirected (remaddr=%s)", t.si, r.Method, r.RemoteAddr) return } if cmn.ReadJSON(w, r, &msg) != nil { return } custom := cos.SimpleKVs{} if err := cos.MorphMarshal(msg.Value, &custom); err != nil { t.writeErrf(w, r, cmn.FmtErrMorphUnmarshal, t.si, "set-custom", msg.Value, err) return } lom := cluster.AllocLOM(request.items[1] /*objName*/) defer cluster.FreeLOM(lom) if err := lom.Init(request.bck.Bck); err != nil { t.writeErr(w, r, err) return } if err := lom.Load(true /*cache it*/, false /*locked*/); err != nil { if cmn.IsObjNotExist(err) { t.writeErr(w, r, err, http.StatusNotFound) } else { t.writeErr(w, r, err) } return } delOldSetNew := cos.IsParseBool(request.query.Get(cmn.URLParamNewCustom)) if glog.FastV(4, glog.SmoduleAIS) { glog.Infof("%s: %s, custom=%+v, del-old-set-new=%t", t.si, lom, msg.Value, delOldSetNew) } if delOldSetNew { lom.SetCustomMD(custom) } else { for key, val := range custom { lom.SetCustomKey(key, val) } } lom.Persist() } ////////////////////// // httpec* handlers // ////////////////////// // Returns a slice. Does not use GFN. func (t *targetrunner) httpecget(w http.ResponseWriter, r *http.Request) { request := &apiRequest{after: 3, prefix: cmn.URLPathEC.L, bckIdx: 1} if err := t.parseReq(w, r, request); err != nil { return } switch request.items[0] { case ec.URLMeta: t.sendECMetafile(w, r, request.bck, request.items[2]) case ec.URLCT: t.sendECCT(w, r, request.bck, request.items[2]) default: t.writeErrURL(w, r) } } // Returns a CT's metadata. func (t *targetrunner) sendECMetafile(w http.ResponseWriter, r *http.Request, bck *cluster.Bck, objName string) { if err := bck.Init(t.owner.bmd); err != nil { if !cmn.IsErrRemoteBckNotFound(err) { // is ais t.writeErrSilent(w, r, err) return } } md, err := ec.ObjectMetadata(bck, objName) if err != nil { if os.IsNotExist(err) { t.writeErrSilent(w, r, err, http.StatusNotFound) } else { t.writeErrSilent(w, r, err, http.StatusInternalServerError) } return } w.Write(md.NewPack()) } func (t *targetrunner) sendECCT(w http.ResponseWriter, r *http.Request, bck *cluster.Bck, objName string) { lom := cluster.AllocLOM(objName) defer cluster.FreeLOM(lom) if err := lom.Init(bck.Bck); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = lom.Init(bck.Bck) } if err != nil { t.writeErr(w, r, err) return } } sliceFQN := lom.MpathInfo().MakePathFQN(bck.Bck, fs.ECSliceType, objName) finfo, err := os.Stat(sliceFQN) if err != nil { t.writeErrSilent(w, r, err, http.StatusNotFound) return } file, err := os.Open(sliceFQN) if err != nil { t.fsErr(err, sliceFQN) t.writeErr(w, r, err, http.StatusInternalServerError) return } w.Header().Set(cmn.HdrContentLength, strconv.FormatInt(finfo.Size(), 10)) _, err = io.Copy(w, file) // No need for `io.CopyBuffer` as `sendfile` syscall will be used. cos.Close(file) if err != nil { glog.Errorf("Failed to send slice %s/%s: %v", bck, objName, err) } } // // supporting methods // // CheckRemoteVersion sets `vchanged` to true if object versions differ between // remote object and local cache. // NOTE: Should be called only if the local copy exists. func (t *targetrunner) CompareObjects(ctx context.Context, lom *cluster.LOM) (equal bool, errCode int, err error) { var objAttrs *cmn.ObjAttrs objAttrs, errCode, err = t.Backend(lom.Bck()).HeadObj(ctx, lom) if err != nil { err = fmt.Errorf(cmn.FmtErrFailed, t.si, "head metadata of", lom, err) return } if lom.Bck().IsHDFS() { equal = true // no versioning in HDFS return } equal = lom.Equal(objAttrs) return } func (t *targetrunner) listBuckets(w http.ResponseWriter, r *http.Request, query cmn.QueryBcks) { const fmterr = "failed to list %q buckets: [%v]" var ( bcks cmn.Bcks code int err error config = cmn.GCO.Get() ) if query.Provider != "" { bcks, code, err = t._listBcks(query, config) if err != nil { t.writeErrStatusf(w, r, code, fmterr, query, err) return } } else /* all providers */ { for provider := range cmn.Providers { var buckets cmn.Bcks query.Provider = provider buckets, code, err = t._listBcks(query, config) if err != nil { if provider == cmn.ProviderAIS { t.writeErrStatusf(w, r, code, fmterr, query, err) return } if glog.FastV(4, glog.SmoduleAIS) { glog.Warningf(fmterr, query, err) } } bcks = append(bcks, buckets...) } } sort.Sort(bcks) t.writeJSON(w, r, bcks, listBuckets) } func (t *targetrunner) _listBcks(query cmn.QueryBcks, cfg *cmn.Config) (names cmn.Bcks, errCode int, err error) { _, ok := cfg.Backend.Providers[query.Provider] // HDFS doesn't support listing remote buckets (there are no remote buckets). if (!ok && !query.IsRemoteAIS()) || query.IsHDFS() { names = selectBMDBuckets(t.owner.bmd.get(), query) } else { bck := cluster.NewBck("", query.Provider, query.Ns) names, errCode, err = t.Backend(bck).ListBuckets(query) sort.Sort(names) } return } func (t *targetrunner) doAppend(r *http.Request, lom *cluster.LOM, started time.Time, query url.Values) (newHandle string, errCode int, err error) { var ( cksumValue = r.Header.Get(cmn.HdrObjCksumVal) cksumType = r.Header.Get(cmn.HdrObjCksumType) contentLength = r.Header.Get(cmn.HdrContentLength) handle = query.Get(cmn.URLParamAppendHandle) ) hi, err := parseAppendHandle(handle) if err != nil { return "", http.StatusBadRequest, err } aoi := &appendObjInfo{ started: started, t: t, lom: lom, r: r.Body, op: query.Get(cmn.URLParamAppendType), hi: hi, } if contentLength != "" { if size, ers := strconv.ParseInt(contentLength, 10, 64); ers == nil { aoi.size = size } } if cksumValue != "" { aoi.cksum = cos.NewCksum(cksumType, cksumValue) } return aoi.appendObject() } // PUT new version and update object metadata // ais bucket: // - if ais bucket versioning is enabled, the version is auto-incremented // Cloud bucket: // - returned version ID is the version // In both cases, new checksum is also generated and stored along with the new version. func (t *targetrunner) doPut(r *http.Request, lom *cluster.LOM, started time.Time, query url.Values, skipVC bool) (errCode int, err error) { var ( header = r.Header owt = query.Get(cmn.URLParamOWT) ) // TODO: oa.Size vs "Content-Length" vs actual, similar to checksum cksumToUse := lom.ObjAttrs().FromHeader(header) poi := allocPutObjInfo() { poi.atime = started poi.t = t poi.lom = lom poi.r = r.Body poi.workFQN = fs.CSM.Gen(lom, fs.WorkfileType, fs.WorkfilePut) poi.cksumToUse = cksumToUse poi.owt = cmn.OwtPut poi.skipVC = skipVC } if owt != "" { n, err := strconv.Atoi(owt) debug.AssertNoErr(err) poi.owt = cmn.OWT(n) } if sizeStr := header.Get(cmn.HdrContentLength); sizeStr != "" { if size, ers := strconv.ParseInt(sizeStr, 10, 64); ers == nil { poi.size = size } } errCode, err = poi.putObject() freePutObjInfo(poi) return } func (t *targetrunner) doAppendArch(r *http.Request, lom *cluster.LOM, started time.Time, query url.Values) (errCode int, err error) { var ( sizeStr = r.Header.Get(cmn.HdrContentLength) mime = query.Get(cmn.URLParamArchmime) filename = query.Get(cmn.URLParamArchpath) ) if strings.HasPrefix(filename, lom.ObjName) { if rel, err := filepath.Rel(lom.ObjName, filename); err == nil { filename = rel } } lom.Lock(true) defer lom.Unlock(true) if err := lom.Load(false /*cache it*/, true /*locked*/); err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusInternalServerError, err } aaoi := &appendArchObjInfo{ started: started, t: t, lom: lom, r: r.Body, filename: filename, mime: mime, } if sizeStr != "" { if size, ers := strconv.ParseInt(sizeStr, 10, 64); ers == nil { aaoi.size = size } } if aaoi.size == 0 { return http.StatusBadRequest, errors.New("size is not defined") } return aaoi.appendObject() } func (t *targetrunner) putMirror(lom *cluster.LOM) { mconfig := lom.MirrorConf() if !mconfig.Enabled { return } if mpathCnt := fs.NumAvail(); mpathCnt < int(mconfig.Copies) { t.statsT.Add(stats.ErrPutCount, 1) // TODO: differentiate put err metrics nanotim := mono.NanoTime() if nanotim&0x7 == 7 { if mpathCnt == 0 { glog.Errorf("%s: %v", t.si, cmn.ErrNoMountpaths) } else { glog.Errorf(fmtErrInsuffMpaths2, t.si, mpathCnt, lom, mconfig.Copies) } } return } rns := xreg.RenewPutMirror(t, lom) xact := rns.Entry.Get() xputlrep := xact.(*mirror.XactPut) xputlrep.Repl(lom) } func (t *targetrunner) DeleteObject(lom *cluster.LOM, evict bool) (int, error) { var ( aisErr, backendErr error aisErrCode, backendErrCode int delFromAIS, delFromBackend bool ) lom.Lock(true) defer lom.Unlock(true) delFromBackend = lom.Bck().IsRemote() && !evict if err := lom.Load(false /*cache it*/, true /*locked*/); err == nil { delFromAIS = true } else if !cmn.IsObjNotExist(err) { return 0, err } else { aisErrCode = http.StatusNotFound if !delFromBackend { return http.StatusNotFound, err } } if delFromBackend { backendErrCode, backendErr = t.Backend(lom.Bck()).DeleteObj(lom) if backendErr == nil { t.statsT.Add(stats.DeleteCount, 1) } } if delFromAIS { size := lom.SizeBytes() aisErr = lom.Remove() if aisErr != nil { if !os.IsNotExist(aisErr) { if backendErr != nil { glog.Errorf("failed to delete %s from %s: %v", lom, lom.Bck(), backendErr) } return 0, aisErr } } else if evict { cos.Assert(lom.Bck().IsRemote()) t.statsT.AddMany( cos.NamedVal64{Name: stats.LruEvictCount, Value: 1}, cos.NamedVal64{Name: stats.LruEvictSize, Value: size}, ) } } if backendErr != nil { return backendErrCode, backendErr } return aisErrCode, aisErr } /////////////////// // RENAME OBJECT // /////////////////// // TODO: unify with PromoteFile (refactor) func (t *targetrunner) objMv(w http.ResponseWriter, r *http.Request, msg *cmn.ActionMsg) { request := &apiRequest{after: 2, prefix: cmn.URLPathObjects.L} if err := t.parseReq(w, r, request); err != nil { return } lom := cluster.AllocLOM(request.items[1]) defer cluster.FreeLOM(lom) if err := lom.Init(request.bck.Bck); err != nil { t.writeErr(w, r, err) return } if lom.Bck().IsRemote() { t.writeErrf(w, r, "%s: cannot rename object %s from a remote bucket", t.si, lom) return } if lom.Bck().Props.EC.Enabled { t.writeErrf(w, r, "%s: cannot rename erasure-coded object %s", t.si, lom) return } if msg.Name == lom.ObjName { t.writeErrf(w, r, "%s: cannot rename/move object %s onto itself", t.si, lom) return } buf, slab := t.gmm.Alloc() coi := allocCopyObjInfo() { coi.CopyObjectParams = cluster.CopyObjectParams{BckTo: lom.Bck(), Buf: buf} coi.t = t coi.localOnly = false coi.finalize = true } _, err := coi.copyObject(lom, msg.Name /* new object name */) slab.Free(buf) freeCopyObjInfo(coi) if err != nil { t.writeErr(w, r, err) return } // TODO: combine copy+delete under a single write lock lom.Lock(true) if err = lom.Remove(); err != nil { glog.Warningf("%s: failed to delete renamed object %s (new name %s): %v", t.si, lom, msg.Name, err) } lom.Unlock(true) } /////////////////////////////////////// // PROMOTE local file(s) => objects // /////////////////////////////////////// func (t *targetrunner) promoteFQN(w http.ResponseWriter, r *http.Request, msg *cmn.ActionMsg) { const fmtErr = "%s: %s failed: " request := &apiRequest{after: 1, prefix: cmn.URLPathObjects.L} if err := t.parseReq(w, r, request); err != nil { return } promoteArgs := cmn.ActValPromote{} if err := cos.MorphMarshal(msg.Value, &promoteArgs); err != nil { t.writeErrf(w, r, cmn.FmtErrMorphUnmarshal, t.si, msg.Action, msg.Value, err) return } if promoteArgs.Target != "" && promoteArgs.Target != t.si.ID() { glog.Errorf("%s: unexpected target ID %s mismatch", t.si, promoteArgs.Target) } // 2. init & validate srcFQN := msg.Name if srcFQN == "" { t.writeErrf(w, r, fmtErr+"missing source filename", t.si, msg.Action) return } finfo, err := os.Stat(srcFQN) if err != nil { if os.IsNotExist(err) { err := cmn.NewErrNotFound("%s: file %q", t.si, srcFQN) t.writeErr(w, r, err, http.StatusNotFound) return } t.writeErr(w, r, err) return } if err = request.bck.Init(t.owner.bmd); err != nil { if cmn.IsErrRemoteBckNotFound(err) { t.BMDVersionFixup(r) err = request.bck.Init(t.owner.bmd) } if err != nil { t.writeErr(w, r, err) return } } // 3a. promote dir if finfo.IsDir() { if glog.FastV(4, glog.SmoduleAIS) { glog.Infof("%s: promote %+v", t.si, promoteArgs) } rns := xreg.RenewDirPromote(t, request.bck, srcFQN, &promoteArgs) if rns.Err != nil { t.writeErr(w, r, rns.Err) return } xact := rns.Entry.Get() go xact.Run(nil) return } // 3b. promote file objName := promoteArgs.ObjName if objName == "" || objName[len(objName)-1] == os.PathSeparator { objName += filepath.Base(srcFQN) } params := cluster.PromoteFileParams{ SrcFQN: srcFQN, Bck: request.bck, ObjName: objName, Overwrite: promoteArgs.Overwrite, KeepOrig: promoteArgs.KeepOrig, } if _, err = t.PromoteFile(params); err != nil { t.writeErrf(w, r, fmtErr+" %v", t.si, msg.Action, err) } // TODO: inc stats } func (t *targetrunner) fsErr(err error, filepath string) { if !cmn.GCO.Get().FSHC.Enabled || !cos.IsIOError(err) { return } mpathInfo, _ := fs.Path2Mpath(filepath) if mpathInfo == nil { return } if cos.IsErrOOS(err) { cs := t.OOS(nil) glog.Errorf("%s: %s", t.si, cs) return } glog.Errorf("%s: waking up FSHC to check %q for err %v", t.si, filepath, err) keyName := mpathInfo.Path // keyName is the mountpath is the fspath - counting IO errors on a per basis.. t.statsT.AddMany(cos.NamedVal64{Name: stats.ErrIOCount, NameSuffix: keyName, Value: 1}) t.fshc.OnErr(filepath) } func (t *targetrunner) runResilver(args res.Args, wg *sync.WaitGroup) { // with no cluster-wide UUID it's a local run if args.UUID == "" { args.UUID = cos.GenUUID() regMsg := xactRegMsg{UUID: args.UUID, Kind: cmn.ActResilver, Srcs: []string{t.si.ID()}} msg := t.newAmsgActVal(cmn.ActRegGlobalXaction, regMsg) t.bcastAsyncIC(msg) } if wg != nil { wg.Done() // compare w/ xaction.GoRunW(() } t.res.RunResilver(args) }
[ "\"AIS_HOST_IP\"", "\"AIS_HOST_PORT\"" ]
[]
[ "AIS_HOST_IP", "AIS_HOST_PORT" ]
[]
["AIS_HOST_IP", "AIS_HOST_PORT"]
go
2
0
perf_dashboard/regression_alerts/views.py
# Copyright Istio Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.shortcuts import render from helpers import download import pandas as pd import os cwd = os.getcwd() perf_data_path = cwd + "/perf_data/" current_release = [os.getenv('CUR_RELEASE')] # Create your views here. def cur_alert(request): cur_release_names, cur_release_dates, master_release_names, master_release_dates = download.download_benchmark_csv(40) cur_pattern_mixer_base_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_base', 'p90') cur_pattern_mixer_serveronly_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_serveronly', 'p90') cur_pattern_mixer_both_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_both', 'p90') cur_pattern_none_serveronly_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_none_serveronly', 'p90') cur_pattern_none_both_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_none_both', 'p90') cur_pattern_v2_serveronly_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, 'nullvm_serveronly', 'p90') cur_pattern_v2_both_p90 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, 'nullvm_both', 'p90') cur_pattern_mixer_base_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_base', 'p99') cur_pattern_mixer_serveronly_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_serveronly', 'p99') cur_pattern_mixer_both_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_mixer_both', 'p99') cur_pattern_none_serveronly_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_none_serveronly', 'p99') cur_pattern_none_both_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, '_none_both', 'p99') cur_pattern_v2_serveronly_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, 'nullvm_serveronly', 'p99') cur_pattern_v2_both_p99 = get_mixer_mode_y_series(cur_release_names, cur_release_dates, 'nullvm_both', 'p99') context = {'current_release': current_release, 'cur_pattern_mixer_base_p90': cur_pattern_mixer_base_p90, 'cur_pattern_mixer_serveronly_p90': cur_pattern_mixer_serveronly_p90, 'cur_pattern_mixer_both_p90': cur_pattern_mixer_both_p90, 'cur_pattern_none_serveronly_p90': cur_pattern_none_serveronly_p90, 'cur_pattern_none_both_p90': cur_pattern_none_both_p90, 'cur_pattern_v2_serveronly_p90': cur_pattern_v2_serveronly_p90, 'cur_pattern_v2_both_p90': cur_pattern_v2_both_p90, 'cur_pattern_mixer_base_p99': cur_pattern_mixer_base_p99, 'cur_pattern_mixer_serveronly_p99': cur_pattern_mixer_serveronly_p99, 'cur_pattern_mixer_both_p99': cur_pattern_mixer_both_p99, 'cur_pattern_none_serveronly_p99': cur_pattern_none_serveronly_p99, 'cur_pattern_none_both_p99': cur_pattern_none_both_p99, 'cur_pattern_v2_serveronly_p99': cur_pattern_v2_serveronly_p99, 'cur_pattern_v2_both_p99': cur_pattern_v2_both_p99 } return render(request, "cur_alert.html", context=context) # Create your views here. def master_alert(request): cur_release_names, cur_release_dates, master_release_names, master_release_dates = download.download_benchmark_csv(40) master_pattern_mixer_base_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_base', 'p90') master_pattern_mixer_serveronly_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_serveronly', 'p90') master_pattern_mixer_both_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_both', 'p90') master_pattern_none_serveronly_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_none_serveronly', 'p90') master_pattern_none_both_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_none_both', 'p90') master_pattern_v2_serveronly_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, 'nullvm_serveronly', 'p90') master_pattern_v2_both_p90 = get_mixer_mode_y_series(master_release_names, master_release_dates, 'nullvm_both', 'p90') master_pattern_mixer_base_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_base', 'p99') master_pattern_mixer_serveronly_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_serveronly', 'p99') master_pattern_mixer_both_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_mixer_both', 'p99') master_pattern_none_serveronly_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_none_serveronly', 'p99') master_pattern_none_both_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, '_none_both', 'p99') master_pattern_v2_serveronly_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, 'nullvm_serveronly', 'p99') master_pattern_v2_both_p99 = get_mixer_mode_y_series(master_release_names, master_release_dates, 'nullvm_both', 'p99') context = {'current_release': current_release, 'master_pattern_mixer_base_p90': master_pattern_mixer_base_p90, 'master_pattern_mixer_serveronly_p90': master_pattern_mixer_serveronly_p90, 'master_pattern_mixer_both_p90': master_pattern_mixer_both_p90, 'master_pattern_none_serveronly_p90': master_pattern_none_serveronly_p90, 'master_pattern_none_both_p90': master_pattern_none_both_p90, 'master_pattern_v2_serveronly_p90': master_pattern_v2_serveronly_p90, 'master_pattern_v2_both_p90': master_pattern_v2_both_p90, 'master_pattern_mixer_base_p99': master_pattern_mixer_base_p99, 'master_pattern_mixer_serveronly_p99': master_pattern_mixer_serveronly_p99, 'master_pattern_mixer_both_p99': master_pattern_mixer_both_p99, 'master_pattern_none_serveronly_p99': master_pattern_none_serveronly_p99, 'master_pattern_none_both_p99': master_pattern_none_both_p99, 'master_pattern_v2_serveronly_p99': master_pattern_v2_serveronly_p99, 'master_pattern_v2_both_p99': master_pattern_v2_both_p99 } return render(request, "master_alert.html", context=context) # Helpers def get_latency_y_data_point(df, mixer_mode, quantiles): y_series_data = [] data = df.query('ActualQPS == 1000 and NumThreads == 16 and Labels.str.endswith(@mixer_mode)') if not data[quantiles].head().empty: y_series_data.append(data[quantiles].head(1).values[0]/1000) else: y_series_data.append('null') return y_series_data def get_mixer_mode_y_series(release_names, release_dates, mixer_mode, quantiles): pattern_data = [[]] * len(release_names) for i in range(len(release_names)): try: df = pd.read_csv(perf_data_path + release_names[i] + ".csv") except Exception as e: print(e) pattern_data[i] = release_dates[i] + ["null"] else: pattern_data[i] = release_dates[i] + get_latency_y_data_point(df, mixer_mode, quantiles) return pattern_data
[]
[]
[ "CUR_RELEASE" ]
[]
["CUR_RELEASE"]
python
1
0
platform/util/src/com/intellij/util/EnvironmentUtil.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util; import com.intellij.execution.CommandLineUtil; import com.intellij.execution.process.UnixProcessManager; import com.intellij.execution.process.WinProcessManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.AtomicNotNullLazyValue; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.FixedFuture; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.BaseOutputReader; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; import gnu.trove.THashMap; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.io.InputStream; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import static java.util.Collections.unmodifiableMap; public class EnvironmentUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.util.EnvironmentUtil"); private static final int SHELL_ENV_READING_TIMEOUT = 20000; private static final String LANG = "LANG"; private static final String LC_ALL = "LC_ALL"; private static final String LC_CTYPE = "LC_CTYPE"; private static final Future<Map<String, String>> ourEnvGetter; static { if (SystemInfo.isMac && "unlocked".equals(System.getProperty("__idea.mac.env.lock")) && SystemProperties.getBooleanProperty("idea.fix.mac.env", true)) { ourEnvGetter = AppExecutorUtil.getAppExecutorService().submit(new Callable<Map<String, String>>() { @Override public Map<String, String> call() throws Exception { return unmodifiableMap(setCharsetVar(getShellEnv())); } }); } else { ourEnvGetter = new FixedFuture<Map<String, String>>(getSystemEnv()); } } private static final NotNullLazyValue<Map<String, String>> ourEnvironment = new AtomicNotNullLazyValue<Map<String, String>>() { @NotNull @Override protected Map<String, String> compute() { try { return ourEnvGetter.get(); } catch (Throwable t) { LOG.warn("can't get shell environment", t); return getSystemEnv(); } } }; private static Map<String, String> getSystemEnv() { if (SystemInfo.isWindows) { return unmodifiableMap(new THashMap<String, String>(System.getenv(), CaseInsensitiveStringHashingStrategy.INSTANCE)); } else { return System.getenv(); } } private EnvironmentUtil() { } public static boolean isEnvironmentReady() { return ourEnvGetter.isDone(); } /** * A wrapper layer around {@link System#getenv()}. * <p> * On Windows, the returned map is case-insensitive (i.e. {@code map.get("Path") == map.get("PATH")} holds). * <p> * On Mac OS X things are complicated.<br/> * An app launched by a GUI launcher (Finder, Dock, Spotlight etc.) receives a pretty empty and useless environment, * since standard Unix ways of setting variables via e.g. ~/.profile do not work. What's more important, there are no * sane alternatives. This causes a lot of user complaints about tools working in a terminal not working when launched * from the IDE. To ease their pain, the IDE loads a shell environment (see {@link #getShellEnv()} for gory details) * and returns it as the result.<br/> * And one more thing (c): locale variables on OS X are usually set by a terminal app - meaning they are missing * even from a shell environment above. This again causes user complaints about tools being unable to output anything * outside ASCII range when launched from the IDE. Resolved by adding LC_CTYPE variable to the map if it doesn't contain * explicitly set locale variables (LANG/LC_ALL/LC_CTYPE). See {@link #setCharsetVar(Map)} for details. * * @return unmodifiable map of the process environment. */ @NotNull public static Map<String, String> getEnvironmentMap() { return ourEnvironment.getValue(); } /** * Same as {@code getEnvironmentMap().get(name)}. * Returns value for the passed environment variable name, or null if no such variable found. * * @see #getEnvironmentMap() */ @Nullable public static String getValue(@NotNull String name) { return getEnvironmentMap().get(name); } /** * Same as {@code flattenEnvironment(getEnvironmentMap())}. * Returns an environment as an array of "NAME=VALUE" strings. * * @see #getEnvironmentMap() */ public static String[] getEnvironment() { return flattenEnvironment(getEnvironmentMap()); } public static String[] flattenEnvironment(@NotNull Map<String, String> environment) { String[] array = new String[environment.size()]; int i = 0; for (Map.Entry<String, String> entry : environment.entrySet()) { array[i++] = entry.getKey() + "=" + entry.getValue(); } return array; } /** * Validates environment variable name in accordance to * {@code ProcessEnvironment#validateVariable} ({@code ProcessEnvironment#validateName} on Windows). * * @see #isValidValue(String) * @see <a href="http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html">Environment Variables in Unix</a> * @see <a href="https://docs.microsoft.com/en-us/windows/desktop/ProcThread/environment-variables">Environment Variables in Windows</a> */ @Contract(value = "null -> false", pure = true) public static boolean isValidName(@Nullable String name) { return name != null && !name.isEmpty() && name.indexOf('\0') == -1 && name.indexOf('=', SystemInfo.isWindows ? 1 : 0) == -1; } /** * Validates environment variable value in accordance to {@code ProcessEnvironment#validateValue}. * * @see #isValidName(String) */ @Contract(value = "null -> false", pure = true) public static boolean isValidValue(@Nullable String value) { return value != null && value.indexOf('\0') == -1; } private static final String DISABLE_OMZ_AUTO_UPDATE = "DISABLE_AUTO_UPDATE"; private static final String INTELLIJ_ENVIRONMENT_READER = "INTELLIJ_ENVIRONMENT_READER"; private static Map<String, String> getShellEnv() throws Exception { return new ShellEnvReader().readShellEnv(); } public static class ShellEnvReader { public Map<String, String> readShellEnv() throws Exception { return readShellEnv(null); } protected Map<String, String> readShellEnv(@Nullable Map<String, String> additionalEnvironment) throws Exception { File reader = PathManager.findBinFileWithException("printenv.py"); File envFile = FileUtil.createTempFile("intellij-shell-env.", ".tmp", false); try { List<String> command = getShellProcessCommand(); int idx = command.indexOf("-c"); if (idx>=0) { // if there is already a command append command to the end command.set(idx + 1, command.get(idx+1) + ";" + "'" + reader.getAbsolutePath() + "' '" + envFile.getAbsolutePath() + "'"); } else { command.add("-c"); command.add("'" + reader.getAbsolutePath() + "' '" + envFile.getAbsolutePath() + "'"); } LOG.info("loading shell env: " + StringUtil.join(command, " ")); return runProcessAndReadOutputAndEnvs(command, null, additionalEnvironment, envFile).second; } finally { FileUtil.delete(envFile); } } @NotNull public Map<String, String> readBatEnv(@NotNull File batchFile, List<String> args) throws Exception { return readBatOutputAndEnv(batchFile, args).second; } @NotNull protected Pair<String, Map<String, String>> readBatOutputAndEnv(@NotNull File batchFile, List<String> args) throws Exception { File envFile = FileUtil.createTempFile("intellij-cmd-env.", ".tmp", false); try { List<String> cl = new ArrayList<String>(); cl.add(CommandLineUtil.getWinShellName()); cl.add("/c"); cl.add("call"); cl.add(batchFile.getPath()); cl.addAll(args); cl.add("&&"); cl.addAll(getReadEnvCommand()); cl.add(envFile.getPath()); cl.addAll(Arrays.asList("||", "exit", "/B", "%ERRORLEVEL%")); return runProcessAndReadOutputAndEnvs(cl, batchFile.getParentFile(), null, envFile); } finally { FileUtil.delete(envFile); } } @NotNull private static List<String> getReadEnvCommand() { return Arrays.asList(FileUtil.toSystemDependentName(System.getProperty("java.home") + "/bin/java"), "-cp", PathManager.getJarPathForClass(ReadEnv.class), ReadEnv.class.getCanonicalName()); } @NotNull protected static Pair<String, Map<String, String>> runProcessAndReadOutputAndEnvs(@NotNull List<String> command, @Nullable File workingDir, @Nullable Map<String, String> scriptEnvironment, @NotNull File envFile) throws Exception { ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); if (scriptEnvironment != null) { // we might need default environment for the process to launch correctly builder.environment().putAll(scriptEnvironment); } if (workingDir != null) builder.directory(workingDir); builder.environment().put(DISABLE_OMZ_AUTO_UPDATE, "true"); builder.environment().put(INTELLIJ_ENVIRONMENT_READER, "true"); Process process = builder.start(); StreamGobbler gobbler = new StreamGobbler(process.getInputStream()); int rv = waitAndTerminateAfter(process, SHELL_ENV_READING_TIMEOUT); gobbler.stop(); String lines = FileUtil.loadFile(envFile); if (rv != 0 || lines.isEmpty()) { throw new Exception("rv:" + rv + " text:" + lines.length() + " out:" + StringUtil.trimEnd(gobbler.getText(), '\n')); } return Pair.create(gobbler.getText(), parseEnv(lines)); } @NotNull protected List<String> getShellProcessCommand() throws Exception { String shell = getShell(); if (shell == null || !new File(shell).canExecute()) { throw new Exception("shell:" + shell); } List<String> commands = ContainerUtil.newArrayList(shell); if (!shell.endsWith("/tcsh") && !shell.endsWith("/csh")) { // Act as a login shell // tsch does allow to use -l with any other options commands.add("-l"); } commands.add("-i"); // enable interactive shell return commands; } @Nullable protected String getShell() { return System.getenv("SHELL"); } } @NotNull public static Map<String, String> parseEnv(String... lines) throws Exception { Set<String> toIgnore = new HashSet<String>(Arrays.asList("_", "PWD", "SHLVL", DISABLE_OMZ_AUTO_UPDATE, INTELLIJ_ENVIRONMENT_READER)); Map<String, String> env = System.getenv(); Map<String, String> newEnv = new HashMap<String, String>(); for (String line : lines) { int pos = line.indexOf('='); if (pos <= 0) { throw new Exception("malformed:" + line); } String name = line.substring(0, pos); if (!toIgnore.contains(name)) { newEnv.put(name, line.substring(pos + 1)); } else if (env.containsKey(name)) { newEnv.put(name, env.get(name)); } } LOG.info("shell environment loaded (" + newEnv.size() + " vars)"); return newEnv; } @NotNull private static Map<String, String> parseEnv(String text) throws Exception { String[] lines = text.split("\0"); return parseEnv(lines); } private static int waitAndTerminateAfter(@NotNull Process process, int timeoutMillis) { Integer exitCode = waitFor(process, timeoutMillis); if (exitCode != null) { return exitCode; } LOG.warn("shell env loader is timed out"); // First, try to interrupt 'softly' (we know how to do it only on *nix) if (!SystemInfo.isWindows) { UnixProcessManager.sendSigIntToProcessTree(process); exitCode = waitFor(process, 1000); if (exitCode != null) { return exitCode; } LOG.warn("failed to terminate shell env loader process gracefully, terminating forcibly"); } if (SystemInfo.isWindows) { WinProcessManager.kill(process, true); } else { UnixProcessManager.sendSigKillToProcessTree(process); } exitCode = waitFor(process, 1000); if (exitCode != null) { return exitCode; } LOG.warn("failed to kill shell env loader"); return -1; } @Nullable private static Integer waitFor(@NotNull Process process, int timeoutMillis) { long stop = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() < stop) { TimeoutUtil.sleep(100); try { return process.exitValue(); } catch (IllegalThreadStateException ignore) { } } return null; } private static Map<String, String> setCharsetVar(@NotNull Map<String, String> env) { if (!isCharsetVarDefined(env)) { String value = setLocaleEnv(env, CharsetToolkit.getDefaultSystemCharset()); LOG.info("LC_CTYPE=" + value); } return env; } private static boolean checkIfLocaleAvailable(String candidateLanguageTerritory) { Locale[] available = Locale.getAvailableLocales(); for (Locale l : available) { if (StringUtil.equals(l.toString(), candidateLanguageTerritory)) { return true; } } return false; } @NotNull public static String setLocaleEnv(@NotNull Map<String, String> env, @NotNull Charset charset) { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); String languageTerritory = "en_US"; if (!language.isEmpty() && !country.isEmpty()) { String languageTerritoryFromLocale = language + '_' + country; if (checkIfLocaleAvailable(languageTerritoryFromLocale)) { languageTerritory = languageTerritoryFromLocale ; } } String result = languageTerritory + '.' + charset.name(); env.put(LC_CTYPE, result); return result; } private static boolean isCharsetVarDefined(@NotNull Map<String, String> env) { return !env.isEmpty() && (env.containsKey(LANG) || env.containsKey(LC_ALL) || env.containsKey(LC_CTYPE)); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs) { inlineParentOccurrences(envs, getEnvironmentMap()); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs, @NotNull Map<String, String> parentEnv) { for (Map.Entry<String, String> entry : envs.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value != null) { String parentVal = parentEnv.get(key); if (parentVal != null && containsEnvKeySubstitution(key, value)) { envs.put(key, value.replace("$" + key + "$", parentVal)); } } } } private static boolean containsEnvKeySubstitution(final String envKey, final String val) { return ArrayUtil.find(val.split(File.pathSeparator), "$" + envKey + "$") != -1; } @TestOnly static Map<String, String> testLoader() { try { return getShellEnv(); } catch (Exception e) { throw new RuntimeException(e); } } @TestOnly static Map<String, String> testParser(@NotNull String lines) { try { return parseEnv(lines); } catch (Exception e) { throw new RuntimeException(e); } } private static class StreamGobbler extends BaseOutputReader { private static final Options OPTIONS = new Options() { @Override public SleepingPolicy policy() { return SleepingPolicy.BLOCKING; } @Override public boolean splitToLines() { return false; } }; private final StringBuffer myBuffer; StreamGobbler(@NotNull InputStream stream) { super(stream, CharsetToolkit.getDefaultSystemCharset(), OPTIONS); myBuffer = new StringBuffer(); start("stdout/stderr streams of shell env loading process"); } @NotNull @Override protected Future<?> executeOnPooledThread(@NotNull Runnable runnable) { return AppExecutorUtil.getAppExecutorService().submit(runnable); } @Override protected void onTextAvailable(@NotNull String text) { myBuffer.append(text); } @NotNull public String getText() { return myBuffer.toString(); } } }
[ "\"SHELL\"" ]
[]
[ "SHELL" ]
[]
["SHELL"]
java
1
0
analyzer/tests/functional/analyze_and_parse/test_analyze_and_parse.py
# ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ------------------------------------------------------------------------- """This module tests the CodeChecker 'analyze' and 'parse' feature.""" import glob import json import os import re import shlex import shutil import subprocess import unittest from subprocess import CalledProcessError from libtest import env from libtest import project from libtest.codechecker import call_command class AnalyzeParseTestCaseMeta(type): def __new__(mcs, name, bases, test_dict): def gen_test(path, mode): """ The returned test function will run the actual tests which compare the output of the command with the stored expected output. """ def test(self): self.check_one_file(path, mode) return test test_dir = os.path.join( os.path.dirname(__file__), 'test_files') # Iterate over the test directory and generate the test cases # for each of the output files. for ofile in glob.glob(os.path.join(test_dir, '*.output')): test_name = 'test_' + os.path.basename(ofile) test_dict[test_name + '_normal'] = gen_test(ofile, 'NORMAL') test_dict[test_name + '_check'] = gen_test(ofile, 'CHECK') return type.__new__(mcs, name, bases, test_dict) class AnalyzeParseTestCase( unittest.TestCase, metaclass=AnalyzeParseTestCaseMeta): """This class tests the CodeChecker 'analyze' and 'parse' feature.""" @classmethod def setup_class(cls): """Setup the class.""" # TEST_WORKSPACE is automatically set by test package __init__.py test_workspace = os.environ['TEST_WORKSPACE'] cls.test_workspaces = {'NORMAL': os.path.join(test_workspace, 'NORMAL'), 'CHECK': os.path.join(test_workspace, 'CHECK')} # Get an environment with CodeChecker command in it. cls.env = env.codechecker_env() cls.test_dir = os.path.join( os.path.dirname(__file__), 'test_files') # Copy test projects and replace file path in plist files. test_projects = ['notes', 'macros'] for test_project in test_projects: test_project_path = os.path.join(cls.test_workspaces['NORMAL'], "test_files", test_project) shutil.copytree(project.path(test_project), test_project_path) for test_file in os.listdir(test_project_path): if test_file.endswith(".plist"): test_file_path = os.path.join(test_project_path, test_file) with open(test_file_path, 'r+', encoding="utf-8", errors="ignore") as plist_file: content = plist_file.read() new_content = content.replace("$FILE_PATH$", test_project_path) plist_file.seek(0) plist_file.truncate() plist_file.write(new_content) # Change working dir to testfile dir so CodeChecker can be run easily. cls.__old_pwd = os.getcwd() os.chdir(cls.test_dir) @classmethod def teardown_class(cls): """Restore environment after tests have ran.""" os.chdir(cls.__old_pwd) def check_one_file(self, path, mode): """ Test 'analyze' and 'parse' output on a ".output" file. The '.output' file is formatted as follows: * >= 1 lines of CodeChecker commands to execute, prefixed by a 'mode' usually containing commands to build, log, analyze and parse the corresponding test file. * A single line containing some - (dashes) * The lines of the output which is expected to be produced by the commands in the lines above the -------------. mode specifies which command prefixes to execute. """ with open(path, 'r', encoding="utf-8", errors="ignore") as ofile: lines = ofile.readlines() only_dash = re.compile(r'^[-]+$') dash_index = 0 for idx, line in enumerate(lines): if re.match(only_dash, line): # The current line is the first line only containing dashes, # thus mark it as separator. dash_index = idx break commands = [line.strip() for line in lines[:dash_index]] current_commands = [c for c in commands if c.split('#')[0] == mode] if not current_commands: return correct_output = ''.join(lines[dash_index + 1:]) run_name = os.path.basename(path).replace(".output", "") workspace = self.test_workspaces[mode] os.makedirs(os.path.join(workspace, run_name, "reports")) output = [] for command in current_commands: split = command.split('#') command = ''.join(split[1:]) command = command.replace("$LOGFILE$", os.path.join(workspace, run_name, "build.json")) command = command.replace("$OUTPUT$", os.path.join(workspace, run_name, "reports")) command = command.replace("$WORKSPACE$", workspace) try: result = subprocess.check_output( shlex.split(command), env=self.env, cwd=self.test_dir, encoding="utf-8", errors="ignore") output += result.splitlines(True) except CalledProcessError as cerr: print("Failed to run: " + ' '.join(cerr.cmd)) print(cerr.output) post_processed_output = [] skip_prefixes = ["[] - Analysis length:", "[] - Previous analysis results", "[] - Skipping input file", # Enabled checkers are listed in the beginning of # analysis. "[] - Enabled checkers:", "clang-tidy:", "clangsa:"] for line in output: # replace timestamps line = re.sub(r'\[\w+ \d{4}-\d{2}-\d{2} \d{2}:\d{2}\]', '[]', line) # Replace full path only to file name on the following # formatted lines: # [severity] /a/b/x.cpp:line:col: message [checker] # The replacement on this line will be the following: # [severity] x.cpp:line:col: message [checker] sep = re.escape(os.sep) line = re.sub(r'^(\[\w+\]\s)(?P<path>.+{0})' r'(.+\:\d+\:\d+\:\s.*\s\[.*\])$'.format(sep), r'\1\3', line) if not any([line.startswith(prefix) for prefix in skip_prefixes]): post_processed_output.append(line) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Actual output below:") print(''.join(post_processed_output)) print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Expected output below:") print(correct_output) print("Test output file: " + path) self.assertEqual(''.join(post_processed_output), correct_output) def test_json_output_for_macros(self): """ Test parse json output for macros. """ test_project_macros = os.path.join(self.test_workspaces['NORMAL'], "test_files", "macros") extract_cmd = ['CodeChecker', 'parse', "-e", "json", test_project_macros] out, _ = call_command(extract_cmd, cwd=self.test_dir, env=self.env) res = json.loads(out) self.assertEqual(len(res), 1) res = res[0] self.assertIn('check_name', res) self.assertIn('issue_hash_content_of_line_in_context', res) self.assertIn('files', res) self.assertEqual(len(res['files']), 1) self.assertIn('path', res) self.assertTrue(res['path']) self.assertIn('macro_expansions', res) self.assertTrue(res['macro_expansions']) def test_json_output_for_notes(self): """ Test parse json output for notes. """ test_project_notes = os.path.join(self.test_workspaces['NORMAL'], "test_files", "notes") extract_cmd = ['CodeChecker', 'parse', "-e", "json", test_project_notes] out, _ = call_command(extract_cmd, cwd=self.test_dir, env=self.env) res = json.loads(out) self.assertEqual(len(res), 1) res = res[0] self.assertIn('check_name', res) self.assertIn('issue_hash_content_of_line_in_context', res) self.assertIn('files', res) self.assertEqual(len(res['files']), 1) self.assertIn('path', res) self.assertTrue(res['path']) self.assertIn('notes', res) self.assertTrue(res['notes']) def test_codeclimate_output(self): """ Test parse codeclimate output. """ test_project_notes = os.path.join(self.test_workspaces['NORMAL'], "test_files", "notes") extract_cmd = ['CodeChecker', 'parse', "-e", "codeclimate", test_project_notes, '--trim-path-prefix', test_project_notes] out, _ = call_command(extract_cmd, cwd=self.test_dir, env=self.env) res = json.loads(out) self.assertEqual(res, [{ 'type': 'issue', 'check_name': 'alpha.clone.CloneChecker', 'description': 'Duplicate code detected', 'categories': ['Bug Risk'], 'fingerprint': '3d15184f38c5fa57e479b744fe3f5035', 'location': { 'path': 'notes.cpp', 'lines': { 'begin': 3 } } }]) def test_invalid_plist_file(self): """ Test parsing invalid plist file. """ invalid_plist_file = os.path.join(self.test_workspaces['NORMAL'], "test_files", "invalid.plist") with open(invalid_plist_file, "w+", encoding="utf-8", errors="ignore") as invalid_plist_f: invalid_plist_f.write("Invalid plist file.") extract_cmd = ['CodeChecker', 'parse', invalid_plist_file] out, _ = call_command(extract_cmd, cwd=self.test_dir, env=self.env) self.assertTrue("Invalid plist file" in out)
[]
[]
[ "TEST_WORKSPACE" ]
[]
["TEST_WORKSPACE"]
python
1
0
examples/multi_app_transfer/main.go
package main import ( "fmt" "os" "github.com/hashgraph/hedera-sdk-go/v2" ) func main() { // Our hypothetical primary service only knows the operator/sender's account ID and the recipient's accountID operatorAccountID, err := hedera.AccountIDFromString(os.Getenv("OPERATOR_ID")) if err != nil { println(err.Error(), ": error converting string to AccountID") return } operatorPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("OPERATOR_KEY")) if err != nil { println(err.Error(), ": error converting string to PrivateKey") return } recipientAccountID := hedera.AccountID{Account: 3} // We create a client without a set operator client := hedera.ClientForTestnet().SetOperator(operatorAccountID, operatorPrivateKey) // We must manually construct a TransactionID with the accountID of the operator/sender // This is the account that will be charged the transaction fee txID := hedera.TransactionIDGenerate(operatorAccountID) // The following steps are required for manually signing transaction, err := hedera.NewTransferTransaction(). // 1. Manually set the transaction ID SetTransactionID(txID). // 2. Add your sender and amount to be send AddHbarTransfer(operatorAccountID, hedera.NewHbar(-1)). // 3. add the recipient(s) and amount to be received AddHbarTransfer(recipientAccountID, hedera.NewHbar(1)). SetTransactionMemo("go sdk example multi_app_transfer/main.go"). // 4. build the transaction using the client that does not have a set operator FreezeWith(client) if err != nil { println(err.Error(), ": error freezing Transfer Transaction") return } // marshal your transaction to bytes txBytes, err := transaction.ToBytes() if err != nil { println(err.Error(), ": error converting transfer transaction to bytes") return } fmt.Printf("Marshalled the unsigned transaction to bytes \n%v\n", txBytes) // // Send the bytes to the application or service that acts as a signer for your transactions // signedTxBytes, err := signingService(txBytes) if err != nil { println(err.Error(), ": error signing transfer transaction") return } fmt.Printf("Received bytes for signed transaction: \n%v\n", signedTxBytes) // unmarshal your bytes into the signed transaction var signedTx hedera.TransferTransaction tx, err := hedera.TransactionFromBytes(signedTxBytes) if err != nil { println(err.Error(), ": error converting bytes to transfer transaction") return } switch t := tx.(type) { case hedera.TransferTransaction: signedTx = t default: panic("Did not receive `TransferTransaction` back from signed bytes") } // execute the transaction response, err := signedTx.Execute(client) if err != nil { println(err.Error(), ": error executing the transfer transaction") return } // get the receipt of the transaction to check the status receipt, err := response.GetReceipt(client) if err != nil { println(err.Error(), ": error retrieving transfer transaction receipt") return } // if Status Success is returned then everything is good fmt.Printf("Crypto transfer status: %v\n", receipt.Status) } // signingService represents an offline service which knows the private keys needed for signing // a transaction and returns the byte representation of the transaction func signingService(txBytes []byte) ([]byte, error) { fmt.Println("\nSigning service has received the transaction") // Your signing service is aware of the operator's private key operatorPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("OPERATOR_KEY")) if err != nil { return txBytes, err } // unmarshal the unsigned transaction's bytes var unsignedTx hedera.TransferTransaction tx, err := hedera.TransactionFromBytes(txBytes) if err != nil { return txBytes, err } switch t := tx.(type) { case hedera.TransferTransaction: unsignedTx = t default: panic("Did not receive `TransferTransaction` back from signed bytes") } fmt.Printf("The Signing service is signing the transaction with key: %v\n", operatorPrivateKey) // sign your unsigned transaction and marshal back to bytes return unsignedTx. Sign(operatorPrivateKey). ToBytes() }
[ "\"OPERATOR_ID\"", "\"OPERATOR_KEY\"", "\"OPERATOR_KEY\"" ]
[]
[ "OPERATOR_ID", "OPERATOR_KEY" ]
[]
["OPERATOR_ID", "OPERATOR_KEY"]
go
2
0
cmd/contour/serve.go
// Copyright Project Contour Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "context" "errors" "fmt" "net" "net/http" "os" "os/signal" "strconv" "syscall" "time" "github.com/projectcontour/contour/internal/controller" envoy_server_v3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" contour_api_v1alpha1 "github.com/projectcontour/contour/apis/projectcontour/v1alpha1" "github.com/projectcontour/contour/internal/annotation" "github.com/projectcontour/contour/internal/contour" "github.com/projectcontour/contour/internal/dag" "github.com/projectcontour/contour/internal/debug" "github.com/projectcontour/contour/internal/health" "github.com/projectcontour/contour/internal/httpsvc" "github.com/projectcontour/contour/internal/k8s" "github.com/projectcontour/contour/internal/metrics" "github.com/projectcontour/contour/internal/timeout" "github.com/projectcontour/contour/internal/workgroup" "github.com/projectcontour/contour/internal/xds" contour_xds_v3 "github.com/projectcontour/contour/internal/xds/v3" "github.com/projectcontour/contour/internal/xdscache" xdscache_v3 "github.com/projectcontour/contour/internal/xdscache/v3" "github.com/projectcontour/contour/pkg/config" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/sirupsen/logrus" "gopkg.in/alecthomas/kingpin.v2" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/cache" ctrl_cache "sigs.k8s.io/controller-runtime/pkg/cache" controller_config "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/manager/signals" ) // Add RBAC policy to support leader election. // +kubebuilder:rbac:groups="",resources=configmaps,verbs=create;get;update // registerServe registers the serve subcommand and flags // with the Application provided. func registerServe(app *kingpin.Application) (*kingpin.CmdClause, *serveContext) { serve := app.Command("serve", "Serve xDS API traffic.") // The precedence of configuration for contour serve is as follows: // If ContourConfiguration resource is specified, it takes precedence, // otherwise config file, overridden by env vars, overridden by cli flags. // however, as -c is a cli flag, we don't know its value til cli flags // have been parsed. To correct this ordering we assign a post parse // action to -c, then parse cli flags twice (see main.main). On the second // parse our action will return early, resulting in the precedence order // we want. var ( configFile string parsed bool ) ctx := newServeContext() parseConfig := func(_ *kingpin.ParseContext) error { if ctx.contourConfigurationName != "" && configFile != "" { return fmt.Errorf("cannot specify both %s and %s", "--contour-config", "-c/--config-path") } if parsed || configFile == "" { // if there is no config file supplied, or we've // already parsed it, return immediately. return nil } f, err := os.Open(configFile) if err != nil { return err } defer f.Close() params, err := config.Parse(f) if err != nil { return err } if err := params.Validate(); err != nil { return fmt.Errorf("invalid Contour configuration: %w", err) } parsed = true ctx.Config = *params return nil } serve.Flag("config-path", "Path to base configuration.").Short('c').PlaceHolder("/path/to/file").Action(parseConfig).ExistingFileVar(&configFile) serve.Flag("contour-config-name", "Name of ContourConfiguration CRD.").PlaceHolder("contour").Action(parseConfig).StringVar(&ctx.contourConfigurationName) serve.Flag("incluster", "Use in cluster configuration.").BoolVar(&ctx.Config.InCluster) serve.Flag("kubeconfig", "Path to kubeconfig (if not in running inside a cluster).").PlaceHolder("/path/to/file").StringVar(&ctx.Config.Kubeconfig) serve.Flag("xds-address", "xDS gRPC API address.").PlaceHolder("<ipaddr>").StringVar(&ctx.xdsAddr) serve.Flag("xds-port", "xDS gRPC API port.").PlaceHolder("<port>").IntVar(&ctx.xdsPort) serve.Flag("stats-address", "Envoy /stats interface address.").PlaceHolder("<ipaddr>").StringVar(&ctx.statsAddr) serve.Flag("stats-port", "Envoy /stats interface port.").PlaceHolder("<port>").IntVar(&ctx.statsPort) serve.Flag("debug-http-address", "Address the debug http endpoint will bind to.").PlaceHolder("<ipaddr>").StringVar(&ctx.debugAddr) serve.Flag("debug-http-port", "Port the debug http endpoint will bind to.").PlaceHolder("<port>").IntVar(&ctx.debugPort) serve.Flag("http-address", "Address the metrics HTTP endpoint will bind to.").PlaceHolder("<ipaddr>").StringVar(&ctx.metricsAddr) serve.Flag("http-port", "Port the metrics HTTP endpoint will bind to.").PlaceHolder("<port>").IntVar(&ctx.metricsPort) serve.Flag("health-address", "Address the health HTTP endpoint will bind to.").PlaceHolder("<ipaddr>").StringVar(&ctx.healthAddr) serve.Flag("health-port", "Port the health HTTP endpoint will bind to.").PlaceHolder("<port>").IntVar(&ctx.healthPort) serve.Flag("contour-cafile", "CA bundle file name for serving gRPC with TLS.").Envar("CONTOUR_CAFILE").StringVar(&ctx.caFile) serve.Flag("contour-cert-file", "Contour certificate file name for serving gRPC over TLS.").PlaceHolder("/path/to/file").Envar("CONTOUR_CERT_FILE").StringVar(&ctx.contourCert) serve.Flag("contour-key-file", "Contour key file name for serving gRPC over TLS.").PlaceHolder("/path/to/file").Envar("CONTOUR_KEY_FILE").StringVar(&ctx.contourKey) serve.Flag("insecure", "Allow serving without TLS secured gRPC.").BoolVar(&ctx.PermitInsecureGRPC) serve.Flag("root-namespaces", "Restrict contour to searching these namespaces for root ingress routes.").PlaceHolder("<ns,ns>").StringVar(&ctx.rootNamespaces) serve.Flag("ingress-class-name", "Contour IngressClass name.").PlaceHolder("<name>").StringVar(&ctx.ingressClassName) serve.Flag("ingress-status-address", "Address to set in Ingress object status.").PlaceHolder("<address>").StringVar(&ctx.Config.IngressStatusAddress) serve.Flag("envoy-http-access-log", "Envoy HTTP access log.").PlaceHolder("/path/to/file").StringVar(&ctx.httpAccessLog) serve.Flag("envoy-https-access-log", "Envoy HTTPS access log.").PlaceHolder("/path/to/file").StringVar(&ctx.httpsAccessLog) serve.Flag("envoy-service-http-address", "Kubernetes Service address for HTTP requests.").PlaceHolder("<ipaddr>").StringVar(&ctx.httpAddr) serve.Flag("envoy-service-https-address", "Kubernetes Service address for HTTPS requests.").PlaceHolder("<ipaddr>").StringVar(&ctx.httpsAddr) serve.Flag("envoy-service-http-port", "Kubernetes Service port for HTTP requests.").PlaceHolder("<port>").IntVar(&ctx.httpPort) serve.Flag("envoy-service-https-port", "Kubernetes Service port for HTTPS requests.").PlaceHolder("<port>").IntVar(&ctx.httpsPort) serve.Flag("envoy-service-name", "Name of the Envoy service to inspect for Ingress status details.").PlaceHolder("<name>").StringVar(&ctx.Config.EnvoyServiceName) serve.Flag("envoy-service-namespace", "Envoy Service Namespace.").PlaceHolder("<namespace>").StringVar(&ctx.Config.EnvoyServiceNamespace) serve.Flag("use-proxy-protocol", "Use PROXY protocol for all listeners.").BoolVar(&ctx.useProxyProto) serve.Flag("accesslog-format", "Format for Envoy access logs.").PlaceHolder("<envoy|json>").StringVar((*string)(&ctx.Config.AccessLogFormat)) serve.Flag("disable-leader-election", "Disable leader election mechanism.").BoolVar(&ctx.DisableLeaderElection) serve.Flag("debug", "Enable debug logging.").Short('d').BoolVar(&ctx.Config.Debug) serve.Flag("kubernetes-debug", "Enable Kubernetes client debug logging with log level.").PlaceHolder("<log level>").UintVar(&ctx.KubernetesDebug) return serve, ctx } // doServe runs the contour serve subcommand. func doServe(log logrus.FieldLogger, ctx *serveContext) error { // Establish k8s core & dynamic client connections. clients, err := k8s.NewClients(ctx.Config.Kubeconfig, ctx.Config.InCluster) if err != nil { return fmt.Errorf("failed to create Kubernetes clients: %w", err) } // Set up workgroup runner. var g workgroup.Group scheme, err := k8s.NewContourScheme() if err != nil { log.WithError(err).Fatal("unable to create scheme") } // Get the ContourConfiguration CRD if specified if len(ctx.contourConfigurationName) > 0 { // Determine the name/namespace of the configuration resource utilizing the environment // variable "CONTOUR_NAMESPACE" which should exist on the Contour deployment. // // If the env variable is not present, it will return "" and still fail the lookup // of the ContourConfiguration in the cluster. namespacedName := types.NamespacedName{Name: ctx.contourConfigurationName, Namespace: os.Getenv("CONTOUR_NAMESPACE")} client := clients.DynamicClient().Resource(contour_api_v1alpha1.ContourConfigurationGVR).Namespace(namespacedName.Namespace) // ensure the specified ContourConfiguration exists res, err := client.Get(context.Background(), namespacedName.Name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("error getting contour configuration %s: %v", namespacedName, err) } var contourConfiguration contour_api_v1alpha1.ContourConfiguration if err := runtime.DefaultUnstructuredConverter.FromUnstructured(res.Object, &contourConfiguration); err != nil { return fmt.Errorf("error converting contour configuration %s: %v", namespacedName, err) } } // Instantiate a controller-runtime manager. We need this regardless of whether // we're running the Gateway API controllers or not, because we use its cache // everywhere. mgr, err := manager.New(controller_config.GetConfigOrDie(), manager.Options{ Scheme: scheme, }) if err != nil { log.WithError(err).Fatal("unable to set up controller manager") } // Register the manager with the workgroup. g.AddContext(func(taskCtx context.Context) error { return mgr.Start(signals.SetupSignalHandler()) }) // informerNamespaces is a list of namespaces that we should start informers for. var informerNamespaces []string fallbackCert := namespacedNameOf(ctx.Config.TLS.FallbackCertificate) clientCert := namespacedNameOf(ctx.Config.TLS.ClientCertificate) if rootNamespaces := ctx.proxyRootNamespaces(); len(rootNamespaces) > 0 { informerNamespaces = append(informerNamespaces, rootNamespaces...) // Add the FallbackCertificateNamespace to informerNamespaces if it isn't present. if !contains(informerNamespaces, ctx.Config.TLS.FallbackCertificate.Namespace) && fallbackCert != nil { informerNamespaces = append(informerNamespaces, ctx.Config.TLS.FallbackCertificate.Namespace) log.WithField("context", "fallback-certificate"). Infof("fallback certificate namespace %q not defined in 'root-namespaces', adding namespace to watch", ctx.Config.TLS.FallbackCertificate.Namespace) } // Add the client certificate namespace to informerNamespaces if it isn't present. if !contains(informerNamespaces, ctx.Config.TLS.ClientCertificate.Namespace) && clientCert != nil { informerNamespaces = append(informerNamespaces, ctx.Config.TLS.ClientCertificate.Namespace) log.WithField("context", "envoy-client-certificate"). Infof("client certificate namespace %q not defined in 'root-namespaces', adding namespace to watch", ctx.Config.TLS.ClientCertificate.Namespace) } } // Set up Prometheus registry and register base metrics. registry := prometheus.NewRegistry() registry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) registry.MustRegister(collectors.NewGoCollector()) // Before we can build the event handler, we need to initialize the converter we'll // use to convert from Unstructured. converter, err := k8s.NewUnstructuredConverter() if err != nil { return err } // XXX(jpeach) we know the config file validated, so all // the timeouts will parse. Shall we add a `timeout.MustParse()` // and use it here? connectionIdleTimeout, err := timeout.Parse(ctx.Config.Timeouts.ConnectionIdleTimeout) if err != nil { return fmt.Errorf("error parsing connection idle timeout: %w", err) } streamIdleTimeout, err := timeout.Parse(ctx.Config.Timeouts.StreamIdleTimeout) if err != nil { return fmt.Errorf("error parsing stream idle timeout: %w", err) } delayedCloseTimeout, err := timeout.Parse(ctx.Config.Timeouts.DelayedCloseTimeout) if err != nil { return fmt.Errorf("error parsing delayed close timeout: %w", err) } maxConnectionDuration, err := timeout.Parse(ctx.Config.Timeouts.MaxConnectionDuration) if err != nil { return fmt.Errorf("error parsing max connection duration: %w", err) } connectionShutdownGracePeriod, err := timeout.Parse(ctx.Config.Timeouts.ConnectionShutdownGracePeriod) if err != nil { return fmt.Errorf("error parsing connection shutdown grace period: %w", err) } requestTimeout, err := timeout.Parse(ctx.Config.Timeouts.RequestTimeout) if err != nil { return fmt.Errorf("error parsing request timeout: %w", err) } // connection balancer if ok := ctx.Config.Listener.ConnectionBalancer == "exact" || ctx.Config.Listener.ConnectionBalancer == ""; !ok { log.Warnf("Invalid listener connection balancer value %q. Only 'exact' connection balancing is supported for now.", ctx.Config.Listener.ConnectionBalancer) ctx.Config.Listener.ConnectionBalancer = "" } listenerConfig := xdscache_v3.ListenerConfig{ UseProxyProto: ctx.useProxyProto, HTTPListeners: map[string]xdscache_v3.Listener{ "ingress_http": { Name: "ingress_http", Address: ctx.httpAddr, Port: ctx.httpPort, }, }, HTTPSListeners: map[string]xdscache_v3.Listener{ "ingress_https": { Name: "ingress_https", Address: ctx.httpsAddr, Port: ctx.httpsPort, }, }, HTTPAccessLog: ctx.httpAccessLog, HTTPSAccessLog: ctx.httpsAccessLog, AccessLogType: ctx.Config.AccessLogFormat, AccessLogFields: ctx.Config.AccessLogFields, AccessLogFormatString: ctx.Config.AccessLogFormatString, AccessLogFormatterExtensions: ctx.Config.AccessLogFormatterExtensions(), MinimumTLSVersion: annotation.MinTLSVersion(ctx.Config.TLS.MinimumProtocolVersion, "1.2"), CipherSuites: config.SanitizeCipherSuites(ctx.Config.TLS.CipherSuites), RequestTimeout: requestTimeout, ConnectionIdleTimeout: connectionIdleTimeout, StreamIdleTimeout: streamIdleTimeout, DelayedCloseTimeout: delayedCloseTimeout, MaxConnectionDuration: maxConnectionDuration, ConnectionShutdownGracePeriod: connectionShutdownGracePeriod, DefaultHTTPVersions: parseDefaultHTTPVersions(ctx.Config.DefaultHTTPVersions), AllowChunkedLength: !ctx.Config.DisableAllowChunkedLength, XffNumTrustedHops: ctx.Config.Network.XffNumTrustedHops, ConnectionBalancer: ctx.Config.Listener.ConnectionBalancer, } if ctx.Config.RateLimitService.ExtensionService != "" { namespacedName := k8s.NamespacedNameFrom(ctx.Config.RateLimitService.ExtensionService) client := clients.DynamicClient().Resource(contour_api_v1alpha1.ExtensionServiceGVR).Namespace(namespacedName.Namespace) // ensure the specified ExtensionService exists res, err := client.Get(context.Background(), namespacedName.Name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("error getting rate limit extension service %s: %v", namespacedName, err) } var extensionSvc contour_api_v1alpha1.ExtensionService if err := runtime.DefaultUnstructuredConverter.FromUnstructured(res.Object, &extensionSvc); err != nil { return fmt.Errorf("error converting rate limit extension service %s: %v", namespacedName, err) } // get the response timeout from the ExtensionService var responseTimeout timeout.Setting if tp := extensionSvc.Spec.TimeoutPolicy; tp != nil { responseTimeout, err = timeout.Parse(tp.Response) if err != nil { return fmt.Errorf("error parsing rate limit extension service %s response timeout: %v", namespacedName, err) } } listenerConfig.RateLimitConfig = &xdscache_v3.RateLimitConfig{ ExtensionService: namespacedName, Domain: ctx.Config.RateLimitService.Domain, Timeout: responseTimeout, FailOpen: ctx.Config.RateLimitService.FailOpen, EnableXRateLimitHeaders: ctx.Config.RateLimitService.EnableXRateLimitHeaders, } } contourMetrics := metrics.NewMetrics(registry) // Endpoints updates are handled directly by the EndpointsTranslator // due to their high update rate and their orthogonal nature. endpointHandler := xdscache_v3.NewEndpointsTranslator(log.WithField("context", "endpointstranslator")) resources := []xdscache.ResourceCache{ xdscache_v3.NewListenerCache(listenerConfig, ctx.statsAddr, ctx.statsPort, ctx.Config.Network.EnvoyAdminPort), &xdscache_v3.SecretCache{}, &xdscache_v3.RouteCache{}, &xdscache_v3.ClusterCache{}, endpointHandler, } // snapshotHandler is used to produce new snapshots when the internal state changes for any xDS resource. snapshotHandler := xdscache.NewSnapshotHandler(resources, log.WithField("context", "snapshotHandler")) // register observer for endpoints updates. endpointHandler.Observer = contour.ComposeObservers(snapshotHandler) // Log that we're using the fallback certificate if configured. if fallbackCert != nil { log.WithField("context", "fallback-certificate").Infof("enabled fallback certificate with secret: %q", fallbackCert) } if clientCert != nil { log.WithField("context", "envoy-client-certificate").Infof("enabled client certificate with secret: %q", clientCert) } // Build the core Kubernetes event handler. contourHandler := &contour.EventHandler{ HoldoffDelay: 100 * time.Millisecond, HoldoffMaxDelay: 500 * time.Millisecond, Observer: dag.ComposeObservers(append(xdscache.ObserversOf(resources), snapshotHandler)...), Builder: getDAGBuilder(ctx, clients, clientCert, fallbackCert, log), FieldLogger: log.WithField("context", "contourEventHandler"), } // Wrap contourHandler in an EventRecorder which tracks API server events. eventHandler := &contour.EventRecorder{ Next: contourHandler, Counter: contourMetrics.EventHandlerOperations, } // Register leadership election. if ctx.DisableLeaderElection { contourHandler.IsLeader = disableLeaderElection(log) } else { contourHandler.IsLeader = setupLeadershipElection(&g, log, &ctx.Config.LeaderElection, clients, contourHandler.UpdateNow) } // Start setting up StatusUpdateHandler since we need it in // the Gateway API controllers. Will finish setting it up and // start it later. sh := k8s.StatusUpdateHandler{ Log: log.WithField("context", "StatusUpdateHandler"), Clients: clients, Cache: mgr.GetCache(), Converter: converter, } // Inform on DefaultResources. for _, r := range k8s.DefaultResources() { if err := informOnResource(clients, r, eventHandler, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", r).Fatal("failed to create informer") } } for _, r := range k8s.IngressV1Resources() { if err := informOnResource(clients, r, eventHandler, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", r).Fatal("failed to create informer") } } // Only inform on Gateway API resources if Gateway API is found. if ctx.Config.GatewayConfig != nil { if clients.ResourcesExist(k8s.GatewayAPIResources()...) { // Create and register the gatewayclass controller with the manager. gatewayClassControllerName := ctx.Config.GatewayConfig.ControllerName if _, err := controller.NewGatewayClassController( mgr, eventHandler, sh.Writer(), log.WithField("context", "gatewayclass-controller"), gatewayClassControllerName, contourHandler.IsLeader, ); err != nil { log.WithError(err).Fatal("failed to create gatewayclass-controller") } // Create and register the NewGatewayController controller with the manager. if _, err := controller.NewGatewayController( mgr, eventHandler, sh.Writer(), log.WithField("context", "gateway-controller"), gatewayClassControllerName, contourHandler.IsLeader, ); err != nil { log.WithError(err).Fatal("failed to create gateway-controller") } // Create and register the NewHTTPRouteController controller with the manager. if _, err := controller.NewHTTPRouteController(mgr, eventHandler, log.WithField("context", "httproute-controller")); err != nil { log.WithError(err).Fatal("failed to create httproute-controller") } // Create and register the NewTLSRouteController controller with the manager. if _, err := controller.NewTLSRouteController(mgr, eventHandler, log.WithField("context", "tlsroute-controller")); err != nil { log.WithError(err).Fatal("failed to create tlsroute-controller") } // Inform on Namespaces. if err := informOnResource(clients, k8s.NamespacesResource(), eventHandler, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", k8s.NamespacesResource()).Fatal("failed to create informer") } } else { log.Fatalf("Gateway API Gateway configured but APIs not installed in cluster.") } } // Inform on secrets, filtering by root namespaces. for _, r := range k8s.SecretsResources() { var handler cache.ResourceEventHandler = eventHandler // If root namespaces are defined, filter for secrets in only those namespaces. if len(informerNamespaces) > 0 { handler = k8s.NewNamespaceFilter(informerNamespaces, eventHandler) } if err := informOnResource(clients, r, handler, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", r).Fatal("failed to create informer") } } // Inform on endpoints. for _, r := range k8s.EndpointsResources() { if err := informOnResource(clients, r, &contour.EventRecorder{ Next: endpointHandler, Counter: contourMetrics.EventHandlerOperations, }, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", r).Fatal("failed to create informer") } } // Register our event handler with the workgroup. g.Add(contourHandler.Start()) // Create metrics service and register with workgroup. metricsvc := httpsvc.Service{ Addr: ctx.metricsAddr, Port: ctx.metricsPort, FieldLogger: log.WithField("context", "metricsvc"), ServeMux: http.ServeMux{}, } metricsvc.ServeMux.Handle("/metrics", metrics.Handler(registry)) if ctx.healthAddr == ctx.metricsAddr && ctx.healthPort == ctx.metricsPort { h := health.Handler(clients.ClientSet()) metricsvc.ServeMux.Handle("/health", h) metricsvc.ServeMux.Handle("/healthz", h) } g.Add(metricsvc.Start) // Create a separate health service if required. if ctx.healthAddr != ctx.metricsAddr || ctx.healthPort != ctx.metricsPort { healthsvc := httpsvc.Service{ Addr: ctx.healthAddr, Port: ctx.healthPort, FieldLogger: log.WithField("context", "healthsvc"), } h := health.Handler(clients.ClientSet()) healthsvc.ServeMux.Handle("/health", h) healthsvc.ServeMux.Handle("/healthz", h) g.Add(healthsvc.Start) } // Create debug service and register with workgroup. debugsvc := debug.Service{ Service: httpsvc.Service{ Addr: ctx.debugAddr, Port: ctx.debugPort, FieldLogger: log.WithField("context", "debugsvc"), }, Builder: &contourHandler.Builder, } g.Add(debugsvc.Start) // Once we have the leadership detection channel, we can // push DAG rebuild metrics onto the observer stack. contourHandler.Observer = &contour.RebuildMetricsObserver{ Metrics: contourMetrics, IsLeader: contourHandler.IsLeader, NextObserver: contourHandler.Observer, } // Finish setting up the StatusUpdateHandler and // add it to the work group. sh.LeaderElected = contourHandler.IsLeader g.Add(sh.Start) // Now we have the statusUpdateHandler, we can create the event handler's StatusUpdater, which will take the // status updates from the DAG, and send them to the status update handler. contourHandler.StatusUpdater = sh.Writer() // Set up ingress load balancer status writer. lbsw := loadBalancerStatusWriter{ log: log.WithField("context", "loadBalancerStatusWriter"), cache: mgr.GetCache(), isLeader: contourHandler.IsLeader, lbStatus: make(chan corev1.LoadBalancerStatus, 1), ingressClassName: ctx.ingressClassName, statusUpdater: sh.Writer(), Converter: converter, } g.Add(lbsw.Start) // Register an informer to watch envoy's service if we haven't been given static details. if lbAddr := ctx.Config.IngressStatusAddress; lbAddr != "" { log.WithField("loadbalancer-address", lbAddr).Info("Using supplied information for Ingress status") lbsw.lbStatus <- parseStatusFlag(lbAddr) } else { serviceHandler := &k8s.ServiceStatusLoadBalancerWatcher{ ServiceName: ctx.Config.EnvoyServiceName, LBStatus: lbsw.lbStatus, Log: log.WithField("context", "serviceStatusLoadBalancerWatcher"), } for _, r := range k8s.ServicesResources() { var handler cache.ResourceEventHandler = serviceHandler if ctx.Config.EnvoyServiceNamespace != "" { handler = k8s.NewNamespaceFilter([]string{ctx.Config.EnvoyServiceNamespace}, handler) } if err := informOnResource(clients, r, handler, mgr.GetCache()); err != nil { log.WithError(err).WithField("resource", r).Fatal("failed to create informer") } } log.WithField("envoy-service-name", ctx.Config.EnvoyServiceName). WithField("envoy-service-namespace", ctx.Config.EnvoyServiceNamespace). Info("Watching Service for Ingress status") } g.AddContext(func(taskCtx context.Context) error { log := log.WithField("context", "xds") log.Printf("waiting for informer caches to sync") if !mgr.GetCache().WaitForCacheSync(taskCtx) { return errors.New("informer cache failed to sync") } log.Printf("informer caches synced") grpcServer := xds.NewServer(registry, ctx.grpcOptions(log)...) switch ctx.Config.Server.XDSServerType { case config.EnvoyServerType: v3cache := contour_xds_v3.NewSnapshotCache(false, log) snapshotHandler.AddSnapshotter(v3cache) contour_xds_v3.RegisterServer(envoy_server_v3.NewServer(taskCtx, v3cache, contour_xds_v3.NewRequestLoggingCallbacks(log)), grpcServer) case config.ContourServerType: contour_xds_v3.RegisterServer(contour_xds_v3.NewContourServer(log, xdscache.ResourcesOf(resources)...), grpcServer) default: // This can't happen due to config validation. log.Fatalf("invalid xDS server type %q", ctx.Config.Server.XDSServerType) } addr := net.JoinHostPort(ctx.xdsAddr, strconv.Itoa(ctx.xdsPort)) l, err := net.Listen("tcp", addr) if err != nil { return err } log = log.WithField("address", addr) if ctx.PermitInsecureGRPC { log = log.WithField("insecure", true) } log.Infof("started xDS server type: %q", ctx.Config.Server.XDSServerType) defer log.Info("stopped xDS server") go func() { <-taskCtx.Done() // We don't use GracefulStop here because envoy // has long-lived hanging xDS requests. There's no // mechanism to make those pending requests fail, // so we forcibly terminate the TCP sessions. grpcServer.Stop() }() return grpcServer.Serve(l) }) // Set up SIGTERM handler for graceful shutdown. g.Add(func(stop <-chan struct{}) error { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGTERM, syscall.SIGINT) select { case sig := <-c: log.WithField("context", "sigterm-handler").WithField("signal", sig).Info("shutting down") case <-stop: // Do nothing. The group is shutting down. } return nil }) // GO! return g.Run(context.Background()) } func getDAGBuilder(ctx *serveContext, clients *k8s.Clients, clientCert, fallbackCert *types.NamespacedName, log logrus.FieldLogger) dag.Builder { var requestHeadersPolicy dag.HeadersPolicy if ctx.Config.Policy.RequestHeadersPolicy.Set != nil { requestHeadersPolicy.Set = make(map[string]string) for k, v := range ctx.Config.Policy.RequestHeadersPolicy.Set { requestHeadersPolicy.Set[k] = v } } if ctx.Config.Policy.RequestHeadersPolicy.Remove != nil { requestHeadersPolicy.Remove = make([]string, 0, len(ctx.Config.Policy.RequestHeadersPolicy.Remove)) requestHeadersPolicy.Remove = append(requestHeadersPolicy.Remove, ctx.Config.Policy.RequestHeadersPolicy.Remove...) } var responseHeadersPolicy dag.HeadersPolicy if ctx.Config.Policy.ResponseHeadersPolicy.Set != nil { responseHeadersPolicy.Set = make(map[string]string) for k, v := range ctx.Config.Policy.ResponseHeadersPolicy.Set { responseHeadersPolicy.Set[k] = v } } if ctx.Config.Policy.ResponseHeadersPolicy.Remove != nil { responseHeadersPolicy.Remove = make([]string, 0, len(ctx.Config.Policy.ResponseHeadersPolicy.Remove)) responseHeadersPolicy.Remove = append(responseHeadersPolicy.Remove, ctx.Config.Policy.ResponseHeadersPolicy.Remove...) } var requestHeadersPolicyIngress dag.HeadersPolicy var responseHeadersPolicyIngress dag.HeadersPolicy if ctx.Config.Policy.ApplyToIngress { requestHeadersPolicyIngress = requestHeadersPolicy responseHeadersPolicyIngress = responseHeadersPolicy } log.Debugf("EnableExternalNameService is set to %t", ctx.Config.EnableExternalNameService) // Get the appropriate DAG processors. dagProcessors := []dag.Processor{ &dag.IngressProcessor{ EnableExternalNameService: ctx.Config.EnableExternalNameService, FieldLogger: log.WithField("context", "IngressProcessor"), ClientCertificate: clientCert, RequestHeadersPolicy: &requestHeadersPolicyIngress, ResponseHeadersPolicy: &responseHeadersPolicyIngress, }, &dag.ExtensionServiceProcessor{ // Note that ExtensionService does not support ExternalName, if it does get added, // need to bring EnableExternalNameService in here too. FieldLogger: log.WithField("context", "ExtensionServiceProcessor"), ClientCertificate: clientCert, }, &dag.HTTPProxyProcessor{ EnableExternalNameService: ctx.Config.EnableExternalNameService, DisablePermitInsecure: ctx.Config.DisablePermitInsecure, FallbackCertificate: fallbackCert, DNSLookupFamily: ctx.Config.Cluster.DNSLookupFamily, ClientCertificate: clientCert, RequestHeadersPolicy: &requestHeadersPolicy, ResponseHeadersPolicy: &responseHeadersPolicy, }, } if ctx.Config.GatewayConfig != nil && clients.ResourcesExist(k8s.GatewayAPIResources()...) { dagProcessors = append(dagProcessors, &dag.GatewayAPIProcessor{ EnableExternalNameService: ctx.Config.EnableExternalNameService, FieldLogger: log.WithField("context", "GatewayAPIProcessor"), }) } // The listener processor has to go last since it looks at // the output of the other processors. dagProcessors = append(dagProcessors, &dag.ListenerProcessor{}) var configuredSecretRefs []*types.NamespacedName if fallbackCert != nil { configuredSecretRefs = append(configuredSecretRefs, fallbackCert) } if clientCert != nil { configuredSecretRefs = append(configuredSecretRefs, clientCert) } builder := dag.Builder{ Source: dag.KubernetesCache{ RootNamespaces: ctx.proxyRootNamespaces(), IngressClassName: ctx.ingressClassName, ConfiguredSecretRefs: configuredSecretRefs, FieldLogger: log.WithField("context", "KubernetesCache"), }, Processors: dagProcessors, } // govet complains about copying the sync.Once that's in the dag.KubernetesCache // but it's safe to ignore since this function is only called once. // nolint:govet return builder } func contains(namespaces []string, ns string) bool { for _, namespace := range namespaces { if ns == namespace { return true } } return false } func informOnResource(clients *k8s.Clients, gvr schema.GroupVersionResource, handler cache.ResourceEventHandler, cache ctrl_cache.Cache) error { gvk, err := clients.KindFor(gvr) if err != nil { return err } inf, err := cache.GetInformerForKind(context.Background(), gvk) if err != nil { return err } inf.AddEventHandler(handler) return nil }
[ "\"CONTOUR_NAMESPACE\"" ]
[]
[ "CONTOUR_NAMESPACE" ]
[]
["CONTOUR_NAMESPACE"]
go
1
0
internal/buf/bufcheck/buflint/internal/util.go
package internal import ( "strconv" "strings" "github.com/bufbuild/buf/internal/buf/bufcheck/internal" "github.com/bufbuild/buf/internal/pkg/analysis" "github.com/bufbuild/buf/internal/pkg/protodesc" "github.com/bufbuild/buf/internal/pkg/stringutil" ) // addFunc adds an annotation. // // Both the Descriptor and Location can be nil. type addFunc func(protodesc.Descriptor, protodesc.Location, string, ...interface{}) func fieldToLowerSnakeCase(s string) string { // Try running this on googleapis and watch // We allow both effectively by not passing the option //return stringutil.ToLowerSnakeCase(s, stringutil.SnakeCaseWithNewWordOnDigits()) return stringutil.ToLowerSnakeCase(s) } func fieldToUpperSnakeCase(s string) string { // Try running this on googleapis and watch // We allow both effectively by not passing the option //return stringutil.ToUpperSnakeCase(s, stringutil.SnakeCaseWithNewWordOnDigits()) return stringutil.ToUpperSnakeCase(s) } // https://cloud.google.com/apis/design/versioning // // All Proto Package values pass. // // v1test can be v1test.* // v1p1alpha1 is also valid in addition to v1p1beta1 func packageHasVersionSuffix(pkg string) bool { if pkg == "" { return false } parts := strings.Split(pkg, ".") if len(parts) < 2 { return false } lastPart := parts[len(parts)-1] if len(lastPart) < 2 { return false } if lastPart[0] != 'v' { return false } version := lastPart[1:] if strings.Contains(version, "test") { split := strings.SplitN(version, "test", 2) if len(split) != 2 { return false } return stringIsPositiveNumber(split[0]) } if strings.Contains(version, "alpha") { return packageVersionIsValidAlphaOrBeta(version, "alpha") } if strings.Contains(version, "beta") { return packageVersionIsValidAlphaOrBeta(version, "beta") } return stringIsPositiveNumber(version) } func packageVersionIsValidAlphaOrBeta(version string, name string) bool { split := strings.SplitN(version, name, 2) if len(split) != 2 { return false } if strings.Contains(split[0], "p") { patchSplit := strings.SplitN(split[0], "p", 2) if len(patchSplit) != 2 { return false } if !stringIsPositiveNumber(patchSplit[0]) || !stringIsPositiveNumber(patchSplit[1]) { return false } } else { if !stringIsPositiveNumber(split[0]) { return false } } return stringIsPositiveNumber(split[1]) } func stringIsPositiveNumber(s string) bool { if s == "" { return false } value, err := strconv.ParseUint(s, 10, 64) if err != nil { return false } return value > 0 } func newFilesCheckFunc( f func(addFunc, []protodesc.File) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return func(id string, files []protodesc.File) ([]*analysis.Annotation, error) { helper := internal.NewHelper(id) if err := f(helper.AddAnnotationf, files); err != nil { return nil, err } return helper.Annotations(), nil } } func newPackageToFilesCheckFunc( f func(add addFunc, pkg string, files []protodesc.File) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFilesCheckFunc( func(add addFunc, files []protodesc.File) error { packageToFiles, err := protodesc.PackageToFiles(files...) if err != nil { return err } for pkg, files := range packageToFiles { if err := f(add, pkg, files); err != nil { return err } } return nil }, ) } func newDirToFilesCheckFunc( f func(add addFunc, dirPath string, files []protodesc.File) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFilesCheckFunc( func(add addFunc, files []protodesc.File) error { dirPathToFiles, err := protodesc.DirPathToFiles(files...) if err != nil { return err } for dirPath, files := range dirPathToFiles { if err := f(add, dirPath, files); err != nil { return err } } return nil }, ) } func newFileCheckFunc( f func(addFunc, protodesc.File) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFilesCheckFunc( func(add addFunc, files []protodesc.File) error { for _, file := range files { if err := f(add, file); err != nil { return err } } return nil }, ) } func newFileImportCheckFunc( f func(addFunc, protodesc.FileImport) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFileCheckFunc( func(add addFunc, file protodesc.File) error { for _, fileImport := range file.FileImports() { if err := f(add, fileImport); err != nil { return err } } return nil }, ) } func newEnumCheckFunc( f func(addFunc, protodesc.Enum) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFileCheckFunc( func(add addFunc, file protodesc.File) error { return protodesc.ForEachEnum( func(enum protodesc.Enum) error { return f(add, enum) }, file, ) }, ) } func newEnumValueCheckFunc( f func(addFunc, protodesc.EnumValue) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newEnumCheckFunc( func(add addFunc, enum protodesc.Enum) error { for _, enumValue := range enum.Values() { if err := f(add, enumValue); err != nil { return err } } return nil }, ) } func newMessageCheckFunc( f func(addFunc, protodesc.Message) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFileCheckFunc( func(add addFunc, file protodesc.File) error { return protodesc.ForEachMessage( func(message protodesc.Message) error { return f(add, message) }, file, ) }, ) } func newFieldCheckFunc( f func(addFunc, protodesc.Field) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newMessageCheckFunc( func(add addFunc, message protodesc.Message) error { for _, field := range message.Fields() { if err := f(add, field); err != nil { return err } } // TODO: is this right? for _, field := range message.Extensions() { if err := f(add, field); err != nil { return err } } return nil }, ) } func newOneofCheckFunc( f func(addFunc, protodesc.Oneof) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newMessageCheckFunc( func(add addFunc, message protodesc.Message) error { for _, oneof := range message.Oneofs() { if err := f(add, oneof); err != nil { return err } } return nil }, ) } func newServiceCheckFunc( f func(addFunc, protodesc.Service) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newFileCheckFunc( func(add addFunc, file protodesc.File) error { for _, service := range file.Services() { if err := f(add, service); err != nil { return err } } return nil }, ) } func newMethodCheckFunc( f func(addFunc, protodesc.Method) error, ) func(string, []protodesc.File) ([]*analysis.Annotation, error) { return newServiceCheckFunc( func(add addFunc, service protodesc.Service) error { for _, method := range service.Methods() { if err := f(add, method); err != nil { return err } } return nil }, ) }
[]
[]
[]
[]
[]
go
null
null
null
management-api-server/src/main/java/com/datastax/mgmtapi/Cli.java
/** * Copyright DataStax, Inc. * * Please see the included license file for details. */ package com.datastax.mgmtapi; import java.io.File; import java.io.IOException; import java.net.SocketAddress; import java.net.URI; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.net.ssl.SSLException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Uninterruptibles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.mgmtapi.util.ShellUtils; import com.github.rvesse.airline.HelpOption; import com.github.rvesse.airline.SingleCommand; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.github.rvesse.airline.annotations.help.Copyright; import com.github.rvesse.airline.annotations.help.License; import com.github.rvesse.airline.annotations.restrictions.Path; import com.github.rvesse.airline.annotations.restrictions.Required; import com.github.rvesse.airline.help.Help; import com.github.rvesse.airline.parser.ParseResult; import com.github.rvesse.airline.parser.errors.ParseException; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.kqueue.KQueue; import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.IdentityCipherSuiteFilter; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.util.AttributeKey; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.Slf4JLoggerFactory; import org.jboss.resteasy.core.ResteasyDeploymentImpl; import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer; import org.jboss.resteasy.plugins.server.netty.NettyUtil; import org.jboss.resteasy.spi.ResteasyDeployment; @Copyright(startYear = 2020, holder = "DataStax") @License(url = "https://www.apache.org/licenses/LICENSE-2.0") @Command(name = "cassandra-management-api", description = "REST service for managing an Apache Cassandra node") public class Cli implements Runnable { public static final String PROTOCOL_TLS_V1_2 = "TLSv1.2"; static { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); } private static final Logger logger = LoggerFactory.getLogger(Cli.class); private ScheduledExecutorService scheduledTasks = null; private ScheduledFuture keepAliveTask = null; @Inject HelpOption<Cli> help; @Path @Required @Option(name = {"-S", "--cassandra-socket"}, arity = 1, description = "Path to Cassandra unix socket file (required)") private String cassandra_unix_socket_file = "/var/run/cassandra.sock"; @Required @Option(name = {"-H", "--host"}, description = "Daemon socket(s) to listen on. (required)") private List<String> listen_address = new ArrayList<>(); @Path @Option(name = {"-p", "--pidfile"}, arity = 1, description = "Create a PID file at this file path.") private String pidfile = null; @Path(executable = true) @Option(name = {"-C", "--cassandra-home"}, arity = 1, description = "Path to the cassandra root directory, if missing will use $CASSANDRA_HOME") private String cassandra_home; @Option(name = {"-K", "--no-keep-alive"}, arity = 1, description = "Setting this flag will stop the management api from starting or keeping Cassandra up automatically") private boolean no_keep_alive = false; @Option(name = {"--explicit-start"}, arity = 1, description = "When using keep-alive, setting this flag will make the management api wait to start Cassandra until /start is called via REST") private boolean explicit_start = false; @Path(writable = false) @Option(name = {"--tlscacert"}, arity = 1, description = "Path to trust certs signed only by this CA") private String tls_ca_cert_file; @Path(writable = false) @Option(name = {"--tlscert"}, arity = 1, description = "Path to TLS certificate file") private String tls_cert_file; @Path(writable = false) @Option(name = {"--tlskey"}, arity = 1, description = "Path to TLS key file") private String tls_key_file; private boolean useTls = false; private File cassandraUnixSocketFile = null; private File cassandraHomeDir = null; private File cassandraExe = null; private Collection<String> cassandraExtraArgs = Collections.emptyList(); private ManagementApplication application = null; private final CountDownLatch shutdownLatch = new CountDownLatch(1); private List<NettyJaxrsServer> servers = new ArrayList<>(); public Cli() { } @VisibleForTesting public Cli(List<String> listenAddresses, String cassandraHomeDir, String cassandraUnixSocketFile, boolean keepAlive, Collection<String> cassandraExtraArgs) { this(listenAddresses, cassandraHomeDir, cassandraUnixSocketFile, keepAlive, cassandraExtraArgs, null, null, null); } @VisibleForTesting public Cli(List<String> listenAddresses, String cassandraHomeDir, String cassandraUnixSocketFile, boolean keepAlive, Collection<String> cassandraExtraArgs, String caCertFile, String certFile, String certKeyFile) { this.listen_address = listenAddresses; this.cassandra_home = cassandraHomeDir; this.cassandra_unix_socket_file = cassandraUnixSocketFile; this.no_keep_alive = !keepAlive; this.cassandraExtraArgs = cassandraExtraArgs; this.tls_ca_cert_file = caCertFile; this.tls_cert_file = certFile; this.tls_key_file = certKeyFile; } @Override public void run() { if (listen_address.isEmpty()) { System.err.println("Requires at least one host to start"); System.exit(1); } preflightChecks(); application = new ManagementApplication(cassandraHomeDir, cassandraExe, cassandraUnixSocketFile, new CqlService(), cassandraExtraArgs); try { for (String uriString : listen_address) { URI uri = URI.create(uriString); NettyJaxrsServer server = null; if ((uri.getScheme().equals("file") || uri.getScheme().equals("unix")) && !uri.getPath().isEmpty()) { server = startHTTPService(new File(uri.getPath())); } else if (uri.getScheme().equals("tcp") || uri.getScheme().equals("http") || uri.getScheme().equals("https")) { server = startHTTPService(uri.getHost(), uri.getPort()); } else { System.err.println("Unknown URI scheme: " + uriString); for (NettyJaxrsServer s : servers) s.stop(); System.exit(1); } try { server.start(); servers.add(server); System.out.println("Started service on " + uriString); } catch (Throwable t) { System.err.println("Error starting server on: " + uri.getPath()); t.printStackTrace(); for (NettyJaxrsServer s : servers) s.stop(); System.exit(2); } } if (!no_keep_alive) { if (explicit_start) { application.setRequestedState(ManagementApplication.STATE.STOPPED); } scheduledTasks = Executors.newSingleThreadScheduledExecutor(); keepAliveTask = scheduledTasks.scheduleAtFixedRate(() -> application.checkState(), 10, 30, TimeUnit.SECONDS); } Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); Uninterruptibles.awaitUninterruptibly(shutdownLatch); } catch (Throwable t) { // Errors should be being collected so if anything is thrown it is unexpected System.err.println(String.format("Unexpected error: %s", t.getMessage())); t.printStackTrace(System.err); } } public void stop() { if (shutdownLatch.getCount() > 0) { if (keepAliveTask != null) keepAliveTask.cancel(true); for (NettyJaxrsServer s : servers) s.stop(); shutdownLatch.countDown(); } } void checkNettyDeps() { if (PlatformDependent.isWindows()) { System.err.println("Management API is not supported under Windows"); System.exit(3); } if (PlatformDependent.isOsx()) { if (!KQueue.isAvailable()) { System.err.println("Missing KQueue netty libraries"); System.exit(3); } } else { if (!Epoll.isAvailable()) { System.err.println("Missing Epoll netty libraries"); System.exit(3); } } } private void checkCassandraCmd() { try { if (cassandra_home != null) { cassandraHomeDir = new File(cassandra_home); } else if (System.getenv("CASSANDRA_HOME") != null) { cassandraHomeDir = new File(System.getenv("CASSANDRA_HOME")); } Optional<File> exe = UnixCmds.which("cassandra"); exe.ifPresent(file -> cassandraExe = file); if (cassandraHomeDir != null && (!cassandraHomeDir.exists() || !cassandraHomeDir.isDirectory())) cassandraHomeDir = null; if (cassandraHomeDir != null) { File maybeCassandra = Paths.get(cassandraHomeDir.getAbsolutePath(), "bin", "cassandra").toFile(); if (maybeCassandra.exists() && maybeCassandra.canExecute()) cassandraExe = maybeCassandra; } if (cassandraExe == null) throw new IllegalArgumentException("Unable to locate cassandra executable, set $CASSANDRA_HOME or use -C"); //Verify Cassandra cmd works List<String> errorOutput = new ArrayList<>(); String version = ShellUtils.executeShellWithHandlers( cassandraExe.getAbsolutePath() + " -v", (input, err) -> input.readLine(), (exitCode, err) -> { String s; errorOutput.add("'" + cassandraExe.getAbsolutePath() + " -v' exit code: " + exitCode); while ((s = err.readLine()) != null) errorOutput.add(s); return null; }); if (version == null) throw new IllegalArgumentException("Version check failed. stderr: " + String.join("\n", errorOutput)); logger.info("Cassandra Version {}", version); } catch (IllegalArgumentException e) { logger.debug("Error encountered:", e); logger.error("Unable to start: unable to find or execute bin/cassandra " + (cassandra_home == null ? "use -C" : cassandra_home)); System.exit(3); } catch (IOException io) { logger.error("Unknown error", io); System.exit(4); } } void checkUnixSocket() { try { cassandraUnixSocketFile = Paths.get(cassandra_unix_socket_file).toFile(); } catch (InvalidPathException e) { logger.error("Unable to start: cassandra_unix_socket_file is not a valid file path: " + cassandra_unix_socket_file); System.exit(3); } } void checkTLSDeps() { boolean hasAny = false; // CA CERT File Checks if (tls_ca_cert_file != null) { hasAny = true; if (!Files.exists(Paths.get(tls_ca_cert_file))) { logger.error("Specified CA Cert file does not exist: {}", tls_ca_cert_file); System.exit(10); } } // CERT File Checks if (tls_cert_file == null && hasAny) { logger.error("TLS Cert file is required when CA Cert flag is used"); System.exit(11); } if (tls_cert_file != null && !hasAny) { logger.error("TLS CA Cert file is required when Cert flag is used"); System.exit(12); } if (tls_cert_file != null) { hasAny = true; if (!Files.exists(Paths.get(tls_cert_file))) { logger.error("Specified Cert file does not exist: {}", tls_cert_file); System.exit(13); } } // KEY File Checks if (tls_key_file == null && hasAny) { logger.error("TLS Key file is required when CA Cert flag is used"); System.exit(14); } if (tls_key_file != null && !hasAny) { logger.error("TLS CA Key file is required when Cert flag is used"); System.exit(15); } if (tls_key_file != null) { if (!Files.exists(Paths.get(tls_key_file))) { logger.error("Specified Key file does not exist: {}", tls_key_file); System.exit(16); } } useTls = hasAny; } void preflightChecks() { checkNettyDeps(); checkTLSDeps(); checkCassandraCmd(); checkUnixSocket(); } private NettyJaxrsServer startHTTPService(String hostname, int port) throws SSLException { NettyJaxrsServer server; if (useTls) { SslContext sslContext = SslContextBuilder .forServer(new File(tls_cert_file), new File(tls_key_file)) .trustManager(new File(tls_ca_cert_file)) .clientAuth(ClientAuth.REQUIRE) .protocols(PROTOCOL_TLS_V1_2) .ciphers(null, IdentityCipherSuiteFilter.INSTANCE) .build(); server = new NettyJaxrsTLSServer(sslContext); } else { server = new NettyJaxrsServer(); } ResteasyDeployment deployment = new ResteasyDeploymentImpl(); deployment.setApplication(application); server.setDeployment(deployment); server.setRootResourcePath(""); server.setIdleTimeout(60); server.setSecurityDomain(null); server.setChannelOptions(ImmutableMap.of(ChannelOption.SO_REUSEADDR, true)); server.setHostname(hostname); server.setPort(port); server.setHttpChannelHandlers(accessLogHandlers(useTls ? "https" : "http")); return server; } private NettyJaxrsServer startHTTPService(File socketFile) { EventLoopGroup loopGroup = PlatformDependent.isOsx() ? new KQueueEventLoopGroup(2) : new EpollEventLoopGroup(2); NettyJaxrsServer server = new NettyJaxrsIPCServer(loopGroup, socketFile); ResteasyDeployment deployment = new ResteasyDeploymentImpl(); deployment.setApplication(application); server.setDeployment(deployment); server.setRootResourcePath(""); server.setIdleTimeout(60); server.setSecurityDomain(null); server.setHttpChannelHandlers(accessLogHandlers("unix")); return server; } public static void main(String[] args) { SingleCommand<Cli> parser = SingleCommand.singleCommand(Cli.class); try { ParseResult<Cli> result = parser.parseWithResult(args); if (result.wasSuccessful()) { // Parsed successfully, so just run the command and exit result.getCommand().run(); } else { // Parsing failed // Display errors and then the help information System.err.println(String.format("%d errors encountered:", result.getErrors().size())); int i = 1; for (ParseException e : result.getErrors()) { System.err.println(String.format("Error %d: %s", i, e.getMessage())); i++; } System.err.println(); result.getCommand().help.showHelp(); } } catch (ParseException p) { //noinspection StatementWithEmptyBody if (args.length > 0 && (args[0].equals("-h") || args[0].equals("--help"))) { // don't tell the user it's a usage error // a bug in airline (https://github.com/airlift/airline/issues/44) prints a usage error even if // a user just uses -h/--help } else { System.err.println(String.format("Usage error: %s", p.getMessage())); System.err.println(); } try { Help.help(parser.getCommandMetadata(), System.err); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { // Errors should be being collected so if anything is thrown it is unexpected System.err.println(String.format("Unexpected error: %s", e.getMessage())); e.printStackTrace(System.err); } } List<ChannelHandler> accessLogHandlers(String protocol) { @ChannelHandler.Sharable class AccessLogInbound extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest r = (HttpRequest) msg; ctx.channel().attr(AttributeKey.valueOf("URIINFO")).set(NettyUtil.extractUriInfo(r, "", protocol).getPath()); } super.channelRead(ctx, msg); } } @ChannelHandler.Sharable class AccessLogOutbound extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse) { HttpResponse r = (HttpResponse) msg; SocketAddress addr = ctx.channel().remoteAddress(); logger.info("address={} url={} status={}", addr == null ? protocol : addr, ctx.channel().attr(AttributeKey.valueOf("URIINFO")).get(), r.getStatus()); } super.write(ctx, msg, promise); } } return ImmutableList.of(new AccessLogInbound(), new AccessLogOutbound()); } }
[ "\"CASSANDRA_HOME\"", "\"CASSANDRA_HOME\"" ]
[]
[ "CASSANDRA_HOME" ]
[]
["CASSANDRA_HOME"]
java
1
0
main.go
package main import ( "crypto/tls" "fmt" "log" "net/http" "os" "github.com/certifi/gocertifi" ) func main() { addr := ":" + os.Getenv("PORT") http.HandleFunc("/", handle) log.Fatal(http.ListenAndServe(addr, nil)) } func handle(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Error parsing form.", http.StatusBadRequest) return } host := r.Form.Get("text") + ":443" certPool, err := gocertifi.CACerts() tlsconfig := &tls.Config{ RootCAs: certPool, } conn, err := tls.Dial("tcp", host, tlsconfig) if err != nil { fmt.Println("err:", err) } defer conn.Close() for _, chain := range conn.ConnectionState().VerifiedChains { for i := len(chain) - 3; i >= 0; i-- { cert := chain[i] fmt.Fprintf(w, "certificate name: %s \ncertificate SANs: %s \n", cert.Subject.CommonName, cert.DNSNames) } } }
[ "\"PORT\"" ]
[]
[ "PORT" ]
[]
["PORT"]
go
1
0
iotservice/client_test.go
package iotservice import ( "context" "io" "net/http" "os" "strconv" "testing" "time" ) func TestSendWithNegativeFeedback(t *testing.T) { client := newClient(t) device := newDevice(t, client) mid := genID() ctx, cancel := context.WithCancel(context.Background()) defer cancel() errc := make(chan error, 1) go func() { errc <- client.SubscribeFeedback(ctx, func(f *Feedback) error { if f.OriginalMessageID == mid { cancel() } return nil }) }() // send a message to the previously created device that's not connected if err := client.SendEvent( ctx, device.DeviceID, nil, WithSendAck(AckNegative), WithSendMessageID(mid), WithSendExpiryTime(time.Now()), ); err != nil { t.Fatal(err) } select { case err := <-errc: if err != context.Canceled { t.Fatal(err) } case <-time.After(30 * time.Second): t.Fatal("timed out") } } func TestETags(t *testing.T) { client := newClient(t) device := newDevice(t, client) // invalid ETag etag := device.ETag device.ETag = "fake" if _, err := client.UpdateDevice(context.Background(), device); err == nil { t.Fatal("expected an error with an invalid etag") } // valid ETag device.ETag = etag if _, err := client.UpdateDevice(context.Background(), device); err != nil { t.Fatal(err) } // force update with If-Match = * device.ETag = "" if _, err := client.UpdateDevice(context.Background(), device); err != nil { t.Fatal(err) } } func TestBulkOperations(t *testing.T) { client := newClient(t) devices := []*Device{ {DeviceID: "test-bulk-0"}, {DeviceID: "test-bulk-1"}, } for _, dev := range devices { _ = client.DeleteDevice(context.Background(), dev) } res, err := client.CreateDevices(context.Background(), devices) if err != nil { t.Fatal(err) } if !res.IsSuccessful { t.Fatal("create is not successful") } res, err = client.UpdateDevices(context.Background(), devices, false) if err != nil { t.Fatal(err) } if !res.IsSuccessful { t.Fatal("update is not successful") } res, err = client.DeleteDevices(context.Background(), devices, false) if err != nil { t.Fatal(err) } if !res.IsSuccessful { t.Fatal("delete is not successful") } } func TestBulkErrors(t *testing.T) { client := newClient(t) devices := []*Device{ {DeviceID: "test-bulk-0"}, {DeviceID: "test-bulk-1"}, } for _, dev := range devices { _ = client.DeleteDevice(context.Background(), dev) } if _, err := client.CreateDevice(context.Background(), devices[0]); err != nil { t.Fatal(err) } res, err := client.CreateDevices(context.Background(), devices) if err != nil { t.Fatal(err) } if res.IsSuccessful { t.Errorf("IsSuccessful = true, want false") } if len(res.Errors) != 1 { t.Errorf("no errors returned") } } func TestRegistryError(t *testing.T) { client := newClient(t) _, err := client.CreateDevice(context.Background(), &Device{DeviceID: "!@#$%^&"}) re, ok := err.(*BadRequestError) if !ok { t.Fatalf("expected a registry error, got = %v", err) } if re.Message == "" || re.ExceptionMessage == "" { t.Fatal("message is empty") } } func TestListDevices(t *testing.T) { client := newClient(t) device := newDevice(t, client) devices, err := client.ListDevices(context.Background()) if err != nil { t.Fatal(err) } for _, dev := range devices { if dev.DeviceID == device.DeviceID { return } } t.Fatal("device not found", device) } func TestGetDevice(t *testing.T) { client := newClient(t) device := newDevice(t, client) if _, err := client.GetDevice(context.Background(), device.DeviceID); err != nil { t.Fatal(err) } } func TestUpdateDevice(t *testing.T) { client := newClient(t) device := newDevice(t, client) device.Status = Disabled dev, err := client.UpdateDevice(context.Background(), device) if err != nil { t.Fatal(err) } if dev.Status != device.Status { t.Fatal("device is not updated") } } func TestDeleteDevice(t *testing.T) { client := newClient(t) device := newDevice(t, client) if err := client.DeleteDevice(context.Background(), device); err != nil { t.Fatal(err) } if _, err := client.GetDevice(context.Background(), device.DeviceID); err == nil { t.Fatal("device found but should be removed") } } func TestDeviceConnectionString(t *testing.T) { client := newClient(t) device := newDevice(t, client) if _, err := client.DeviceConnectionString(device, false); err != nil { t.Fatal(err) } } func TestDeviceSAS(t *testing.T) { client := newClient(t) device := newDevice(t, client) sas, err := client.DeviceSAS(device, "", time.Hour, false) if err != nil { t.Fatal(err) } if sas == "" { t.Fatal("empty sas token") } } func TestGetDeviceTwin(t *testing.T) { client := newClient(t) device := newDevice(t, client) _, err := client.GetDeviceTwin(context.Background(), device.DeviceID) if err != nil { t.Fatal(err) } } func TestUpdateDeviceTwin(t *testing.T) { client := newClient(t) device := newDevice(t, client) twin, err := client.UpdateDeviceTwin(context.Background(), &Twin{ DeviceID: device.DeviceID, Properties: &Properties{ Desired: map[string]interface{}{ "hw": "1.11", }, }, }) if err != nil { t.Fatal(err) } if twin.Properties.Desired["hw"] != "1.11" { t.Fatal("twin not updated") } } func TestModuleConnectionString(t *testing.T) { client := newClient(t) _, module := newDeviceAndModule(t, client) if _, err := client.ModuleConnectionString(module, false); err != nil { t.Fatal(err) } } func TestListModules(t *testing.T) { client := newClient(t) device, module := newDeviceAndModule(t, client) modules, err := client.ListModules(context.Background(), device.DeviceID) if err != nil { t.Fatal(err) } for _, mod := range modules { if mod.DeviceID == device.DeviceID && mod.ModuleID == module.ModuleID { return } } t.Fatal("module not found", device) } func TestGetModule(t *testing.T) { client := newClient(t) device, module := newDeviceAndModule(t, client) if _, err := client.GetModule( context.Background(), device.DeviceID, module.ModuleID, ); err != nil { t.Fatal(err) } } func TestDeleteModule(t *testing.T) { client := newClient(t) device, module := newDeviceAndModule(t, client) if err := client.DeleteModule(context.Background(), module); err != nil { t.Fatal(err) } if _, err := client.GetModule( context.Background(), device.DeviceID, module.ModuleID, ); err == nil { t.Fatal("module is not deleted") } } func TestGetModuleTwin(t *testing.T) { client := newClient(t) device, module := newDeviceAndModule(t, client) if _, err := client.GetModuleTwin( context.Background(), device.DeviceID, module.ModuleID, ); err != nil { t.Fatal(err) } } func TestUpdateModuleTwin(t *testing.T) { client := newClient(t) device, module := newDeviceAndModule(t, client) twin, err := client.UpdateModuleTwin(context.Background(), &ModuleTwin{ DeviceID: device.DeviceID, ModuleID: module.ModuleID, Properties: &Properties{ Desired: map[string]interface{}{ "hw": "1.12", }, }, }) if err != nil { t.Fatal(err) } if twin.Properties.Desired["hw"] != "1.12" { t.Fatal("twin not updated") } } func TestListConfigurations(t *testing.T) { client := newClient(t) config := newConfiguration(t, client) configs, err := client.ListConfigurations(context.Background()) if err != nil { t.Fatal(err) } for _, cfg := range configs { if cfg.ID == config.ID { return } } t.Fatal("configuration not found in the list") } func TestGetConfiguration(t *testing.T) { client := newClient(t) config := newConfiguration(t, client) if _, err := client.GetConfiguration(context.Background(), config.ID); err != nil { t.Fatal(err) } } func TestUpdateConfiguration(t *testing.T) { client := newClient(t) config := newConfiguration(t, client) config.Labels = map[string]string{ "foo": "bar", } if _, err := client.UpdateConfiguration(context.Background(), config); err != nil { t.Fatal(err) } } func TestDeleteConfiguration(t *testing.T) { client := newClient(t) config := newConfiguration(t, client) if err := client.DeleteConfiguration(context.Background(), config); err != nil { t.Fatal(err) } if _, err := client.GetConfiguration(context.Background(), config.ID); err == nil { t.Fatal("configuration is not deleted") } } func TestStats(t *testing.T) { client := newClient(t) if _, err := client.Stats(context.Background()); err != nil { t.Fatal(err) } } func TestQueryDevices(t *testing.T) { client := newClient(t) device := newDevice(t, client) // some delay needed to wait until the device is available time.Sleep(500 * time.Millisecond) var found bool if err := client.QueryDevices( context.Background(), "select deviceId from devices", func(v map[string]interface{}) error { if v["deviceId"].(string) == device.DeviceID { found = true } return nil }, ); err != nil { t.Fatal(err) } if !found { t.Fatal("requested device not found") } } func TestScheduleMethodCall(t *testing.T) { client := newClient(t) job, err := client.CreateJobV2(context.Background(), &JobV2{ JobID: genID(), Type: JobTypeDeviceMethod, CloudToDeviceMethod: &DeviceMethodParams{ MethodName: "dist-upgrade", Payload: map[string]interface{}{"time": "now"}, TimeoutInSeconds: 0, }, QueryCondition: "deviceId='nonexisting'", StartTime: time.Now().Add(time.Minute), MaxExecutionTimeInSeconds: 5, }) if err != nil { t.Fatal(err) } // simply test that job can be found job, err = client.GetJobV2(context.Background(), job.JobID) if err != nil { t.Fatal(err) } // cancel job immediately because free-tier accounts support only one running job job, err = client.CancelJobV2(context.Background(), job.JobID) if err != nil { t.Fatal(err) } if job.Status != JobStatusCancelled { t.Errorf("job status = %q, want %q", job.Status, JobStatusCancelled) } // sometimes Azure is being slow time.Sleep(time.Second) // find just cancelled job var found bool if err = client.QueryJobsV2(context.Background(), &JobV2Query{ Type: JobTypeDeviceMethod, Status: JobStatusCancelled, PageSize: 10, }, func(j *JobV2) error { if j.JobID == job.JobID { found = true return io.EOF } return nil }); err != nil && err != io.EOF { t.Fatal(err) } if !found { t.Errorf("QueryJobsV2 hasn't found the job") } } func newClient(t *testing.T) *Client { t.Helper() cs := os.Getenv("TEST_IOTHUB_SERVICE_CONNECTION_STRING") if cs == "" { t.Fatal("$TEST_IOTHUB_SERVICE_CONNECTION_STRING is empty") } c, err := NewFromConnectionString(cs) if err != nil { t.Fatal(err) } return c } var testRunID = strconv.Itoa(int(time.Now().Unix())) func newDevice(t *testing.T, c *Client) *Device { t.Helper() device := &Device{ DeviceID: "test-device-" + testRunID, } device, err := c.CreateDevice(context.Background(), device) if err != nil { t.Fatal(err) } t.Cleanup(func() { device.ETag = "" if err := c.DeleteDevice(context.Background(), device); err != nil && !isNotFound(err) { t.Fatal(err) } }) return device } func newDeviceAndModule(t *testing.T, c *Client) (*Device, *Module) { t.Helper() device := newDevice(t, c) module := &Module{ DeviceID: device.DeviceID, ModuleID: "test-module-" + testRunID, ManagedBy: "admin", } module, err := c.CreateModule(context.Background(), module) if err != nil { t.Fatal(err) } t.Cleanup(func() { module.ETag = "" if err := c.DeleteModule(context.Background(), module); err != nil && !isNotFound(err) { t.Fatal(err) } }) return device, module } func isNotFound(err error) bool { e, ok := err.(*RequestError) return ok && e.Code == http.StatusNotFound } func newConfiguration(t *testing.T, c *Client) *Configuration { t.Helper() config := &Configuration{ ID: "test-configuration", Priority: 10, SchemaVersion: "1.0", TargetCondition: "deviceId='test-device'", Labels: map[string]string{ "test": "test", }, Content: &ConfigurationContent{ DeviceContent: map[string]interface{}{ "properties.desired.testconf": 1.12, }, }, Metrics: &ConfigurationMetrics{ Queries: map[string]string{ "Total": "select deviceId from devices", }, }, } config, err := c.CreateConfiguration(context.Background(), config) if err != nil { t.Fatal(err) } t.Cleanup(func() { config.ETag = "" if err := c.DeleteConfiguration(context.Background(), config); err != nil && !isNotFound(err) { t.Fatal(err) } }) return config }
[ "\"TEST_IOTHUB_SERVICE_CONNECTION_STRING\"" ]
[]
[ "TEST_IOTHUB_SERVICE_CONNECTION_STRING" ]
[]
["TEST_IOTHUB_SERVICE_CONNECTION_STRING"]
go
1
0
hooks/charmhelpers/fetch/giturl.py
# Copyright 2014-2015 Canonical Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from subprocess import check_call, CalledProcessError from charmhelpers.fetch import ( BaseFetchHandler, UnhandledSource, filter_installed_packages, apt_install, ) if filter_installed_packages(['git']) != []: apt_install(['git']) if filter_installed_packages(['git']) != []: raise NotImplementedError('Unable to install git') class GitUrlFetchHandler(BaseFetchHandler): """Handler for git branches via generic and github URLs""" def can_handle(self, source): url_parts = self.parse_url(source) # TODO (mattyw) no support for ssh git@ yet if url_parts.scheme not in ('http', 'https', 'git', ''): return False elif not url_parts.scheme: return os.path.exists(os.path.join(source, '.git')) else: return True def clone(self, source, dest, branch="master", depth=None): if not self.can_handle(source): raise UnhandledSource("Cannot handle {}".format(source)) if os.path.exists(dest): cmd = ['git', '-C', dest, 'pull', source, branch] else: cmd = ['git', 'clone', source, dest, '--branch', branch] if depth: cmd.extend(['--depth', depth]) check_call(cmd) def install(self, source, branch="master", dest=None, depth=None): url_parts = self.parse_url(source) branch_name = url_parts.path.strip("/").split("/")[-1] if dest: dest_dir = os.path.join(dest, branch_name) else: dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", branch_name) try: self.clone(source, dest_dir, branch, depth) except CalledProcessError as e: raise UnhandledSource(e) except OSError as e: raise UnhandledSource(e.strerror) return dest_dir
[]
[]
[ "CHARM_DIR" ]
[]
["CHARM_DIR"]
python
1
0
qa/pull-tester/rpc-tests.py
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Run Regression Test Suite This module calls down into individual test cases via subprocess. It will forward all unrecognized arguments onto the individual test scripts, other than: - `-h` or '--help': print help about all options - `-extended`: run the "extended" test suite in addition to the basic one. - `-extended-only`: run ONLY the "extended" test suite - `-list`: only list the test scripts, do not run. Works in combination with '-extended' and '-extended-only' too, to print subsets. - `-win`: signal that this is running in a Windows environment, and we should run the tests. - `--coverage`: this generates a basic coverage report for the RPC interface. For more detailed help on options, run with '--help'. For a description of arguments recognized by test scripts, see `qa/pull-tester/test_framework/test_framework.py:BitcoinTestFramework.main`. """ import pdb import os import time import shutil import signal import sys import subprocess import tempfile import re sys.path.append("qa/pull-tester/") from tests_config import * from test_classes import RpcTest, Disabled, Skip BOLD = ("","") if os.name == 'posix': # primitive formatting on supported # terminal via ANSI escape sequences: BOLD = ('\033[0m', '\033[1m') RPC_TESTS_DIR = SRCDIR + '/qa/rpc-tests/' #If imported values are not defined then set to zero (or disabled) if 'ENABLE_WALLET' not in vars(): ENABLE_WALLET=0 if 'ENABLE_BITCOIND' not in vars(): ENABLE_BITCOIND=0 if 'ENABLE_UTILS' not in vars(): ENABLE_UTILS=0 if 'ENABLE_ZMQ' not in vars(): ENABLE_ZMQ=0 ENABLE_COVERAGE=0 #Create a set to store arguments and create the passOn string opts = set() double_opts = set() # BU: added for checking validity of -- opts passOn = "" showHelp = False # if we need to print help p = re.compile("^--") p_parallel = re.compile('^-parallel=') run_parallel = 4 # some of the single-dash options applicable only to this runner script # are also allowed in double-dash format (but are not passed on to the # test scripts themselves) private_single_opts = ('-h', '-f', # equivalent to -force-enable '-help', '-list', '-extended', '-extended-only', '-only-extended', '-force-enable', '-win') private_double_opts = ('--list', '--extended', '--extended-only', '--only-extended', '--force-enable', '--win') framework_opts = ('--tracerpc', '--help', '--noshutdown', '--nocleanup', '--srcdir', '--tmpdir', '--coveragedir', '--randomseed', '--testbinary', '--refbinary') test_script_opts = ('--mineblock', '--extensive') def option_passed(option_without_dashes): """check if option was specified in single-dash or double-dash format""" return ('-' + option_without_dashes in opts or '--' + option_without_dashes in double_opts) bold = ("","") if (os.name == 'posix'): bold = ('\033[0m', '\033[1m') for arg in sys.argv[1:]: if arg == '--coverage': ENABLE_COVERAGE = 1 elif (p.match(arg) or arg in ('-h', '-help')): if arg not in private_double_opts: if arg == '--help' or arg == '-help' or arg == '-h': passOn = '--help' showHelp = True else: if passOn is not '--help': passOn += " " + arg # add it to double_opts only for validation double_opts.add(arg) elif p_parallel.match(arg): run_parallel = int(arg.split(sep='=', maxsplit=1)[1]) else: # this is for single-dash options only # they are interpreted only by this script opts.add(arg) # check for unrecognized options bad_opts_found = [] bad_opt_str="Unrecognized option: %s" for o in opts | double_opts: if o.startswith('--'): if o not in framework_opts + test_script_opts + private_double_opts: print(bad_opt_str % o) bad_opts_found.append(o) elif o.startswith('-'): if o not in private_single_opts: print(bad_opt_str % o) bad_opts_found.append(o) print("Run with -h to get help on usage.") sys.exit(1) #Set env vars if "BITCOIND" not in os.environ: os.environ["BITCOIND"] = BUILDDIR + '/src/bitcoind' + EXEEXT if "BITCOINCLI" not in os.environ: os.environ["BITCOINCLI"] = BUILDDIR + '/src/bitcoin-cli' + EXEEXT #Disable Windows tests by default if EXEEXT == ".exe" and not option_passed('win'): print("Win tests currently disabled. Use -win option to enable") sys.exit(0) if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1): print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled") sys.exit(0) # python3-zmq may not be installed. Handle this gracefully and with some helpful info if ENABLE_ZMQ: try: import zmq except ImportError as e: print("ERROR: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \ "to run zmq tests, see dependency info in /qa/README.md.") raise e #Tests testScripts = [ RpcTest(t) for t in [ 'bip68-112-113-p2p', 'validateblocktemplate', 'parallel', 'wallet', 'excessive', 'buip055', 'listtransactions', 'receivedby', 'mempool_resurrect_test', 'txn_doublespend --mineblock', 'txn_clone', 'getchaintips', 'rawtransactions', 'rest', 'mempool_spendcoinbase', 'mempool_reorg', Disabled('mempool_limit', "mempool priority changes causes create_lots_of_big_transactions to fail"), 'httpbasics', 'multi_rpc', 'zapwallettxes', 'proxy_test', 'merkle_blocks', 'fundrawtransaction', 'signrawtransactions', 'walletbackup', 'nodehandling', 'reindex', 'decodescript', Disabled('p2p-fullblocktest', "TODO"), 'blockchain', 'disablewallet', 'sendheaders', 'keypool', Disabled('prioritise_transaction', "TODO"), Disabled('invalidblockrequest', "TODO"), 'invalidtxrequest', 'abandonconflict', 'p2p-versionbits-warning', 'importprunedfunds', 'thinblocks' ] ] testScriptsExt = [ RpcTest(t) for t in [ 'txPerf', 'excessive --extensive', 'parallel --extensive', 'bip9-softforks', 'bip65-cltv', 'bip65-cltv-p2p', 'bip68-sequence', 'bipdersig-p2p', 'bipdersig', 'getblocktemplate_longpoll', 'getblocktemplate_proposals', 'txn_doublespend', 'txn_clone --mineblock', Disabled('pruning', "too much disk"), 'forknotify', 'invalidateblock', Disabled('rpcbind_test', "temporary, bug in libevent, see #6655"), 'smartfees', 'maxblocksinflight', 'p2p-acceptblock', 'mempool_packages', 'maxuploadtarget', Disabled('replace-by-fee', "disabled while Replace By Fee is disabled in code") ] ] #Enable ZMQ tests if ENABLE_ZMQ == 1: testScripts.append(RpcTest('zmq_test')) def show_wrapper_options(): """ print command line options specific to wrapper """ print("Wrapper options:") print() print(" -extended/--extended run the extended set of tests") print(" -only-extended / -extended-only\n" + \ " --only-extended / --extended-only\n" + \ " run ONLY the extended tests") print(" -list / --list only list test names") print(" -win / --win signal running on Windows and run those tests") print(" -f / -force-enable / --force-enable\n" + \ " attempt to run disabled/skipped tests") print(" -h / -help / --help print this help") def runtests(): global passOn coverage = None test_passed = [] disabled = [] skipped = [] tests_to_run = [] force_enable = option_passed('force-enable') or '-f' in opts run_only_extended = option_passed('only-extended') or option_passed('extended-only') if option_passed('list'): if run_only_extended: for t in testScriptsExt: print(t) else: for t in testScripts: print(t) if option_passed('extended'): for t in testScriptsExt: print(t) sys.exit(0) if ENABLE_COVERAGE: coverage = RPCCoverage() print("Initializing coverage directory at %s\n" % coverage.dir) if(ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1): rpcTestDir = RPC_TESTS_DIR buildDir = BUILDDIR run_extended = option_passed('extended') or run_only_extended cov_flag = coverage.flag if coverage else '' flags = " --srcdir %s/src %s %s" % (buildDir, cov_flag, passOn) # compile the list of tests to check # check for explicit tests if showHelp: tests_to_run = [ testScripts[0] ] else: for o in opts: if not o.startswith('-'): found = False for t in testScripts + testScriptsExt: t_rep = str(t).split(' ') if (t_rep[0] == o or t_rep[0] == o + '.py') and len(t_rep) > 1: # it is a test with args - check all args match what was passed, otherwise don't add this test t_args = t_rep[1:] all_args_found = True for targ in t_args: if not targ in passOn.split(' '): all_args_found = False if all_args_found: tests_to_run.append(t) found = True elif t_rep[0] == o or t_rep[0] == o + '.py': passOnSplit = [x for x in passOn.split(' ') if x != ''] found_non_framework_opt = False for p in passOnSplit: if p in test_script_opts: found_non_framework_opt = True if not found_non_framework_opt: tests_to_run.append(t) found = True if not found: print("Error: %s is not a known test." % o) sys.exit(1) # if no explicit tests specified, use the lists if not len(tests_to_run): if run_only_extended: tests_to_run = testScriptsExt else: tests_to_run += testScripts if run_extended: tests_to_run += testScriptsExt # weed out the disabled / skipped tests and print them beforehand # this allows earlier intervention in case a test is unexpectedly # skipped if not force_enable: trimmed_tests_to_run = [] for t in tests_to_run: if t.is_disabled(): print("Disabled testscript %s%s%s (reason: %s)" % (bold[1], t, bold[0], t.reason)) disabled.append(str(t)) elif t.is_skipped(): print("Skipping testscript %s%s%s on this platform (reason: %s)" % (bold[1], t, bold[0], t.reason)) skipped.append(str(t)) else: trimmed_tests_to_run.append(t) tests_to_run = trimmed_tests_to_run if len(tests_to_run) > 1 and run_parallel: # Populate cache subprocess.check_output([RPC_TESTS_DIR + 'create_cache.py'] + [flags]) tests_to_run = list(map(str,tests_to_run)) max_len_name = len(max(tests_to_run, key=len)) time_sum = 0 time0 = time.time() job_queue = RPCTestHandler(run_parallel, tests_to_run, flags) results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0] all_passed = True for _ in range(len(tests_to_run)): (name, stdout, stderr, passed, duration) = job_queue.get_next() test_passed.append(passed) all_passed = all_passed and passed time_sum += duration print('\n' + BOLD[1] + name + BOLD[0] + ":") print(stdout) print('stderr:\n' if not stderr == '' else '', stderr) results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration) print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration)) results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0] print(results) print("\nRuntime: %s s" % (int(time.time() - time0))) if coverage: coverage.report_rpc_coverage() print("Cleaning up coverage data") coverage.cleanup() if not showHelp: # show some overall results and aggregates print() print("%d test(s) passed / %d test(s) failed / %d test(s) executed" % (test_passed.count(True), test_passed.count(False), len(test_passed))) print("%d test(s) disabled / %d test(s) skipped due to platform" % (len(disabled), len(skipped))) # signal that tests have failed using exit code sys.exit(not all_passed) else: print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled") class RPCTestHandler: """ Trigger the testscrips passed in via the list. """ def __init__(self, num_tests_parallel, test_list=None, flags=None): assert(num_tests_parallel >= 1) self.num_jobs = num_tests_parallel self.test_list = test_list self.flags = flags self.num_running = 0 # In case there is a graveyard of zombie bitcoinds, we can apply a # pseudorandom offset to hopefully jump over them. # (625 is PORT_RANGE/MAX_NODES) self.portseed_offset = int(time.time() * 1000) % 625 self.jobs = [] def get_next(self): while self.num_running < self.num_jobs and self.test_list: # Add tests self.num_running += 1 t = self.test_list.pop(0) port_seed = ["--portseed={}".format(len(self.test_list) + self.portseed_offset)] log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16) log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16) self.jobs.append((t, time.time(), subprocess.Popen((RPC_TESTS_DIR + t).split() + self.flags.split() + port_seed, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE))) if not self.jobs: raise IndexError('pop from empty list') while True: # Return first proc that finishes time.sleep(.5) for j in self.jobs: (name, time0, proc) = j if os.getenv('TRAVIS') == 'true' and int(time.time() - time0) > 20 * 60: # In travis, timeout individual tests after 20 minutes (to stop tests hanging and not # providing useful output. proc.send_signal(signal.SIGINT) if proc.poll() is not None: (stdout, stderr) = proc.communicate(timeout=3) passed = stderr == "" and proc.returncode == 0 self.num_running -= 1 self.jobs.remove(j) return name, stdout, stderr, passed, int(time.time() - time0) print('.', end='', flush=True) class RPCCoverage(object): """ Coverage reporting utilities for pull-tester. Coverage calculation works by having each test script subprocess write coverage files into a particular directory. These files contain the RPC commands invoked during testing, as well as a complete listing of RPC commands per `bitcoin-cli help` (`rpc_interface.txt`). After all tests complete, the commands run are combined and diff'd against the complete list to calculate uncovered RPC commands. See also: qa/rpc-tests/test_framework/coverage.py """ def __init__(self): self.dir = tempfile.mkdtemp(prefix="coverage") self.flag = '--coveragedir %s' % self.dir def report_rpc_coverage(self): """ Print out RPC commands that were unexercised by tests. """ uncovered = self._get_uncovered_rpc_commands() if uncovered: print("Uncovered RPC commands:") print("".join((" - %s\n" % i) for i in sorted(uncovered))) else: print("All RPC commands covered.") def cleanup(self): return shutil.rmtree(self.dir) def _get_uncovered_rpc_commands(self): """ Return a set of currently untested RPC commands. """ # This is shared from `qa/rpc-tests/test-framework/coverage.py` REFERENCE_FILENAME = 'rpc_interface.txt' COVERAGE_FILE_PREFIX = 'coverage.' coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME) coverage_filenames = set() all_cmds = set() covered_cmds = set() if not os.path.isfile(coverage_ref_filename): raise RuntimeError("No coverage reference found") with open(coverage_ref_filename, 'r') as f: all_cmds.update([i.strip() for i in f.readlines()]) for root, dirs, files in os.walk(self.dir): for filename in files: if filename.startswith(COVERAGE_FILE_PREFIX): coverage_filenames.add(os.path.join(root, filename)) for filename in coverage_filenames: with open(filename, 'r') as f: covered_cmds.update([i.strip() for i in f.readlines()]) return all_cmds - covered_cmds if __name__ == '__main__': runtests()
[]
[]
[ "BITCOINCLI", "TRAVIS", "BITCOIND" ]
[]
["BITCOINCLI", "TRAVIS", "BITCOIND"]
python
3
0
service/debug/collector/main.go
package main import ( "os" "path" "github.com/micro/go-micro/v2" log "github.com/micro/go-micro/v2/logger" plugin "github.com/micro/micro/v2/service/debug/collector/micro" "github.com/netdata/go-orchestrator" "github.com/netdata/go-orchestrator/cli" "github.com/netdata/go-orchestrator/pkg/multipath" ) var ( cd, _ = os.Getwd() netdataConfig = multipath.New( os.Getenv("NETDATA_USER_CONFIG_DIR"), os.Getenv("NETDATA_STOCK_CONFIG_DIR"), path.Join(cd, "/../../../../etc/netdata"), path.Join(cd, "/../../../../usr/lib/netdata/conf.d"), ) ) func main() { // New Service service := micro.NewService( micro.Name("go.micro.debug.collector"), micro.Version("latest"), ) if len(os.Args) > 1 { os.Args = append(os.Args[:1], os.Args[2:]...) } // Initialise service service.Init() go func() { log.Fatal(service.Run()) }() // register the new plugin plugin.New(service.Client()).Register() netdata := orchestrator.New() netdata.Name = "micro.d" netdata.Option = &cli.Option{ UpdateEvery: 1, Debug: true, Module: "all", ConfigDir: netdataConfig, Version: false, } netdata.ConfigPath = netdataConfig if !netdata.Setup() { log.Fatal("Netdata failed to Setup()") } netdata.Serve() }
[ "\"NETDATA_USER_CONFIG_DIR\"", "\"NETDATA_STOCK_CONFIG_DIR\"" ]
[]
[ "NETDATA_STOCK_CONFIG_DIR", "NETDATA_USER_CONFIG_DIR" ]
[]
["NETDATA_STOCK_CONFIG_DIR", "NETDATA_USER_CONFIG_DIR"]
go
2
0
TrainHumanGoalie1LastShooterSwitch.py
import sys import csv import numpy as np import gpflow import os import pandas as pd import h5py from sklearn.model_selection import train_test_split import tensorflow as tf from scipy.cluster.vq import kmeans tf.set_random_seed(1234) import pickle import argparse import PKutils def train_model(**kwargs): npseed = kwargs['npseed'] iters = kwargs['iterations'] gpu = kwargs['gpu'] numInducingPoints = kwargs['IP'] print("npseed: " + str(npseed)) print("iterations: " + str(iters)) print("gpu: " + str(gpu)) print("IPs: " + str(numInducingPoints)) os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=str(gpu) print("Loading Data ....") Vnoswitchdf = pd.read_csv("LastSwitchThatTrial.csv") result = Vnoswitchdf["result"] testtrim = Vnoswitchdf[["goalieypos","ball_xpos","ball_ypos","goalie_yvel","ball_yvel","opp","tslc","subID"]] cputrialsdf = testtrim[testtrim["opp"]==0] #trials against computer goalie cputrialsdf_result = result.loc[cputrialsdf.index] humantrialsdf = testtrim[testtrim["opp"]==1] humantrialsdf_result = result.loc[humantrialsdf.index] humantrialsdf["subID"] = humantrialsdf["subID"].astype('int') goalie1trialsdf = humantrialsdf[humantrialsdf["subID"]<50] goalie1trialsdf_result = humantrialsdf_result.loc[goalie1trialsdf.index] goalie2trialsdf = humantrialsdf[humantrialsdf["subID"]>=50] goalie2trialsdf_result = humantrialsdf_result.loc[goalie2trialsdf.index] del goalie2trialsdf["subID"] del goalie1trialsdf["subID"] del cputrialsdf["subID"] # Train the GPs X_train, X_test = train_test_split(goalie1trialsdf, test_size=0.2, random_state=1) y_train, y_test = train_test_split(goalie1trialsdf_result, test_size=0.2, random_state=1) optimizer = 'Adam' mb = 256 np.random.seed(npseed) Ms = numInducingPoints X = np.array(X_train, dtype=float) Y = np.array(y_train, dtype=float) Y = np.expand_dims(Y,axis=-1) Z = kmeans(X_train, Ms, iter=1)[0] Z = np.array(Z, dtype=float) dimsize = X.shape[1] kernel = gpflow.kernels.RBF(input_dim=dimsize, ARD=True) m = gpflow.models.SVGP( X,Y, kern=kernel, likelihood=gpflow.likelihoods.Bernoulli(), Z=Z, minibatch_size=mb) m.feature.set_trainable(True) global_step = tf.get_variable("global_step", (), tf.int32, tf.zeros_initializer(), trainable=False) learning_rate = 0.001 #adam default experstring = 'Vnoswitch_goalie1_iters' + str(iters) + '_inducingpts' + str(numInducingPoints) + '_' + "_npseed" + str(npseed) fw = tf.summary.FileWriter("Vnoswitchtrain_logs/{}".format(experstring), m.graph) #define summary scalars for examination in tensorboard tf.summary.scalar("likelihood", m._build_likelihood()) tf.summary.scalar("lengthscales_goalieposy", tf.gather(m.kern.lengthscales._constrained_tensor, 0)) tf.summary.scalar("lengthscales_shooterposx", tf.gather(m.kern.lengthscales._constrained_tensor, 1)) tf.summary.scalar("lengthscales_shooterposy", tf.gather(m.kern.lengthscales._constrained_tensor, 2)) tf.summary.scalar("lengthscales_goalievely", tf.gather(m.kern.lengthscales._constrained_tensor, 3)) tf.summary.scalar("lengthscales_shootervely", tf.gather(m.kern.lengthscales._constrained_tensor, 4)) tf.summary.scalar("lengthscales_opp", tf.gather(m.kern.lengthscales._constrained_tensor, 5)) tf.summary.scalar("lengthscales_timesincelastchange", tf.gather(m.kern.lengthscales._constrained_tensor, 6)) mysum = tf.summary.merge_all() def loss_callback(summary): fw.add_summary(summary, loss_callback.iter) loss_callback.iter += 1 loss_callback.iter=0 print("Training Model...") gpflow.train.AdamOptimizer(learning_rate).minimize(m, maxiter=iters, var_list=[global_step], global_step=global_step, summary_op=mysum, file_writer=fw) #save model param_dict = {p[0].full_name.replace('SGPR', 'SGPU'): p[1] for p in zip(m.trainable_parameters, m.read_trainables())} with open('VnoswitchGPs/goalie1noswitchVmodel_'+str(numInducingPoints)+'IP_np'+str(npseed)+ '_iters' + str(iters) + '.pickle', 'wb') as handle: pickle.dump(param_dict, handle, protocol=pickle.HIGHEST_PROTOCOL) m.as_pandas_table().to_pickle('VnoswitchGPs/goalie1modelparams_'+str(numInducingPoints)+'IP_np'+str(npseed) + '_iters'+str(iters)) print("goalie1 Value GP Complete") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--npseed',default=1, type=int) parser.add_argument('--iterations',default=100000,type=int) parser.add_argument('--gpu',default=0, type=int) parser.add_argument('--IP', default=500, type=int) args = parser.parse_args() train_model(**vars(args))
[]
[]
[ "CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
python
2
0
selfdrive/controls/lib/long_mpc.py
import os import math import cereal.messaging as messaging from common.numpy_fast import clip, interp from selfdrive.swaglog import cloudlog from common.realtime import sec_since_boot from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU from selfdrive.controls.lib.longitudinal_mpc import libmpc_py from selfdrive.controls.lib.drive_helpers import MPC_COST_LONG LOG_MPC = os.environ.get('LOG_MPC', False) class LongitudinalMpc(): def __init__(self, mpc_id): self.mpc_id = mpc_id self.setup_mpc() self.v_mpc = 0.0 self.v_mpc_future = 0.0 self.a_mpc = 0.0 self.v_cruise = 0.0 self.prev_lead_status = False self.prev_lead_x = 0.0 self.new_lead = False self.last_cloudlog_t = 0.0 self.n_its = 0 self.duration = 0 # scc smoother self.cruise_gap = 0 def publish(self, pm): if LOG_MPC: qp_iterations = max(0, self.n_its) dat = messaging.new_message('liveLongitudinalMpc') dat.liveLongitudinalMpc.xEgo = list(self.mpc_solution[0].x_ego) dat.liveLongitudinalMpc.vEgo = list(self.mpc_solution[0].v_ego) dat.liveLongitudinalMpc.aEgo = list(self.mpc_solution[0].a_ego) dat.liveLongitudinalMpc.xLead = list(self.mpc_solution[0].x_l) dat.liveLongitudinalMpc.vLead = list(self.mpc_solution[0].v_l) dat.liveLongitudinalMpc.cost = self.mpc_solution[0].cost dat.liveLongitudinalMpc.aLeadTau = self.a_lead_tau dat.liveLongitudinalMpc.qpIterations = qp_iterations dat.liveLongitudinalMpc.mpcId = self.mpc_id dat.liveLongitudinalMpc.calculationTime = self.duration pm.send('liveLongitudinalMpc', dat) def setup_mpc(self): ffi, self.libmpc = libmpc_py.get_libmpc(self.mpc_id) self.libmpc.init(MPC_COST_LONG.TTC, MPC_COST_LONG.DISTANCE, MPC_COST_LONG.ACCELERATION, MPC_COST_LONG.JERK) self.mpc_solution = ffi.new("log_t *") self.cur_state = ffi.new("state_t *") self.cur_state[0].v_ego = 0 self.cur_state[0].a_ego = 0 self.a_lead_tau = _LEAD_ACCEL_TAU def set_cur_state(self, v, a): self.cur_state[0].v_ego = v self.cur_state[0].a_ego = a def update(self, CS, lead): v_ego = CS.vEgo # Setup current mpc state self.cur_state[0].x_ego = 0.0 if lead is not None and lead.status: x_lead = max(0, lead.dRel - 0.5) v_lead = max(0.0, lead.vLead) a_lead = lead.aLeadK if (v_lead < 0.1 or -a_lead / 2.0 > v_lead): v_lead = 0.0 a_lead = 0.0 self.a_lead_tau = max(lead.aLeadTau, (a_lead ** 2 * math.pi) / (2 * (v_lead + 0.01) ** 2)) self.new_lead = False if not self.prev_lead_status or abs(x_lead - self.prev_lead_x) > 2.5: self.libmpc.init_with_simulation(self.v_mpc, x_lead, v_lead, a_lead, self.a_lead_tau) self.new_lead = True self.prev_lead_status = True self.prev_lead_x = x_lead self.cur_state[0].x_l = x_lead self.cur_state[0].v_l = v_lead else: self.prev_lead_status = False # Fake a fast lead car, so mpc keeps running self.cur_state[0].x_l = 50.0 self.cur_state[0].v_l = v_ego + 10.0 a_lead = 0.0 self.a_lead_tau = _LEAD_ACCEL_TAU # Calculate mpc t = sec_since_boot() # scc smoother cruise_gap = int(clip(CS.cruiseGap, 1., 4.)) # TR = interp(float(cruise_gap), [1., 2., 3., 4.], [1.0, 1.3, 1.6, 2.0]) TR = interp(v_ego, [3., 30.], [1., 2.5]) if self.cruise_gap != cruise_gap: self.cruise_gap = cruise_gap self.n_its = self.libmpc.run_mpc(self.cur_state, self.mpc_solution, self.a_lead_tau, a_lead, TR) self.duration = int((sec_since_boot() - t) * 1e9) # Get solution. MPC timestep is 0.2 s, so interpolation to 0.05 s is needed self.v_mpc = self.mpc_solution[0].v_ego[1] self.a_mpc = self.mpc_solution[0].a_ego[1] self.v_mpc_future = self.mpc_solution[0].v_ego[10] # Reset if NaN or goes through lead car crashing = any(lead - ego < -50 for (lead, ego) in zip(self.mpc_solution[0].x_l, self.mpc_solution[0].x_ego)) nans = any(math.isnan(x) for x in self.mpc_solution[0].v_ego) backwards = min(self.mpc_solution[0].v_ego) < -0.01 if ((backwards or crashing) and self.prev_lead_status) or nans: if t > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = t cloudlog.warning("Longitudinal mpc %d reset - backwards: %s crashing: %s nan: %s" % ( self.mpc_id, backwards, crashing, nans)) self.libmpc.init(MPC_COST_LONG.TTC, MPC_COST_LONG.DISTANCE, MPC_COST_LONG.ACCELERATION, MPC_COST_LONG.JERK) self.cur_state[0].v_ego = v_ego self.cur_state[0].a_ego = 0.0 self.v_mpc = v_ego self.a_mpc = CS.aEgo self.prev_lead_status = False
[]
[]
[ "LOG_MPC" ]
[]
["LOG_MPC"]
python
1
0
reid/reid.py
# -*- coding:utf-8 -*- import sys import argparse from data_loader import Market1501, RandomIdentitySampler, ImageDataset import oneflow as flow from bisect import bisect_right import os import os.path as osp import numpy as np from utils.loggers import Logger from utils.distance import compute_distance_matrix from loss import TripletLoss, CrossEntropyLossLS from model import ResReid from lr_scheduler import WarmupMultiStepLR def _parse_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("--gpu_devices", type=str, default="0") parser.add_argument("--batch_size", type=int, default=64, required=False) parser.add_argument("--eval_batch_size", type=int, default=64, required=False) parser.add_argument("--num_classes", type=int, default=751, required=False) parser.add_argument("--lr", type=float, default=3.5e-04, required=False) parser.add_argument("--max_epoch", type=int, default=120, required=False) parser.add_argument("--step-size", type=list, default=[40, 70], required=False) parser.add_argument("--weight_t", type=float, default=0.5, required=False) parser.add_argument("--margin", type=float, default=0.3, required=False) parser.add_argument("--weight_decay", type=float, default=5e-4, required=False) parser.add_argument("--adam_beta1", type=float, default=0.9, required=False) parser.add_argument("--adam_beta2", type=float, default=0.999, required=False) parser.add_argument( "--gamma", type=float, default=0.1, required=False, help="learning rate decay multiplier", ) parser.add_argument( "--warmup", action="store_true", default=True, help="warm up lr scheduler" ) parser.add_argument("--warmup_factor", type=float, default=0.1, required=False) parser.add_argument("--warmup_iters", type=int, default=10, required=False) parser.add_argument("--epsilon", type=float, default=0.1, required=False) parser.add_argument( "--data_dir", type=str, default="./dataset", required=False, help="dataset directory", ) parser.add_argument("--image_height", type=int, default=256, required=False) parser.add_argument("--image_width", type=int, default=128, required=False) parser.add_argument( "--evaluate", action="store_true", default=False, help="train or eval" ) parser.add_argument("--eval_freq", type=int, default=20, required=False) parser.add_argument( "--dist_metric", type=str, choices=["euclidean", "cosine"], default="euclidean", help="euclidean or cosine", ) parser.add_argument("--rerank", type=bool, default=False) parser.add_argument( "--load_weights", type=str, default="./resnet50_pretrained_model", help="model load directory", ) parser.add_argument( "--log_dir", type=str, default="./output", required=False, help="log info save directory", ) parser.add_argument( "--flow_weight", type=str, default="./output/flow_weight", required=False, help="log info save directory", ) parser.add_argument("--num_instances", type=int, default=4) parser.add_argument( "opts", default=None, nargs=argparse.REMAINDER, help="Modify config options using the command-line", ) return parser.parse_args() def main(args): # log setting log_name = "log_test.log" if args.evaluate else "log_train.log" sys.stdout = Logger(osp.join(args.log_dir, log_name)) # cuda setting os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_devices print("Currently using GPU {}".format(os.environ["CUDA_VISIBLE_DEVICES"])) print("Building re-id model ") model = ResReid(args.num_classes) if args.load_weights: pretrain_models = flow.load(args.load_weights) model.load_state_dict(pretrain_models, strict=False) model = model.to("cuda") print("=> init dataset") dataset = Market1501(root=args.data_dir) if args.evaluate: evaluate(model, dataset) else: optimizer = flow.optim.Adam( model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(args.adam_beta1, args.adam_beta2), ) # lr scheduler if args.warmup: scheduler = WarmupMultiStepLR( optimizer, milestones=args.step_size, gamma=args.gamma, warmup_factor=args.warmup_factor, warmup_iters=args.warmup_iters, ) else: scheduler = flow.optim.lr_scheduler.LambdaLR( optimizer, lr_lambda=lambda epoch: args.lr ** bisect_right(args.step_size, epoch), ) train(model, dataset, args.num_classes, optimizer, scheduler) def train(model, dataset, num_classes, optimizer, scheduler): batch_size = args.batch_size is_best = False best_rank = 0 print("=> Start training") # loss criterion_t = TripletLoss(margin=args.margin).to("cuda") criterion_x = CrossEntropyLossLS(num_classes=num_classes, epsilon=args.epsilon).to( "cuda" ) weight_t = args.weight_t weight_x = 1.0 - args.weight_t _, train_id, _ = map(list, zip(*dataset.train)) train_dataset = ImageDataset( dataset.train, flag="train", process_size=(args.image_height, args.image_width) ) # *****training*******# for epoch in range(0, args.max_epoch): # shift to train model.train() indicies = [ x for x in RandomIdentitySampler(train_id, batch_size, args.num_instances) ] for i in range(len(indicies) // batch_size): try: # train_batch[0,1,2] are [imgs, pid, cam_id] imgs, pids, _ = train_dataset.__getbatch__( indicies[i * batch_size : (i + 1) * batch_size] ) except: imgs, pids, _ = train_dataset.__getbatch__(indicies[-batch_size:]) imgs = flow.Tensor(np.array(imgs)).to("cuda") pids = flow.Tensor(np.array(pids), dtype=flow.int32).to("cuda") outputs, features = model(imgs) loss_t = compute_loss(criterion_t, features, pids) loss_x = compute_loss(criterion_x, outputs, pids) loss = weight_t * loss_t + weight_x * loss_x loss.backward() optimizer.step() optimizer.zero_grad() scheduler.step() print( "epoch:", epoch + 1, "loss_t:", loss_t.numpy(), "loss_x:", loss_x.numpy(), "loss:", loss.numpy(), "lr:", optimizer.param_groups[0]["lr"], ) # *****testing********# if (epoch + 1) % args.eval_freq == 0 and (epoch + 1) != args.max_epoch: rank1, mAP = evaluate(model, dataset) if (rank1 + mAP) / 2.0 > best_rank: is_best = True else: is_best = False if is_best: flow.save(model.state_dict(), args.flow_weight + "_" + str(epoch)) print("=> End training") print("=> Final test") rank1, _ = evaluate(model, dataset) flow.save(model.state_dict(), args.flow_weight) def compute_loss(criterion, outputs, targets): if isinstance(outputs, (tuple, list)): loss = DeepSupervision(criterion, outputs, targets) else: loss = criterion(outputs, targets) return loss def DeepSupervision(criterion, xs, y): """DeepSupervision Applies criterion to each element in a list. Args: criterion: loss function xs: tuple of inputs y: ground truth """ loss = 0.0 for x in xs: loss += criterion(x, y) loss /= len(xs) return loss def evaluate(model, dataset): query_dataset = ImageDataset( dataset.query, flag="test", process_size=(args.image_height, args.image_width) ) gallery_dataset = ImageDataset( dataset.gallery, flag="test", process_size=(args.image_height, args.image_width) ) eval_batch = args.eval_batch_size model.eval() dist_metric = args.dist_metric # distance metric, ['euclidean', 'cosine'] rerank = args.rerank # use person re-ranking save_dir = args.log_dir print("Extracting features from query set ...") # query features, query person IDs and query camera IDs qf, q_pids, q_camids = [], [], [] q_ind = list(range(len(query_dataset))) for i in range((len(query_dataset) // eval_batch)): imgs, pids, camids = query_dataset.__getbatch__( q_ind[i * eval_batch : (i + 1) * eval_batch] ) imgs = flow.Tensor(np.array(imgs)).to("cuda") with flow.no_grad(): features = model(imgs) qf.append(features.numpy()) q_pids.extend(pids) q_camids.extend(camids) qf = np.concatenate(qf, 0) q_pids = np.asarray(q_pids) q_camids = np.asarray(q_camids) print("Done, obtained {}-by-{} matrix".format(qf.shape[0], qf.shape[1])) print("Extracting features from gallery set ...") # gallery features, gallery person IDs and gallery camera IDs gf, g_pids, g_camids = [], [], [] g_ind = list(range(len(gallery_dataset))) for i in range((len(gallery_dataset) // eval_batch)): imgs, pids, camids = gallery_dataset.__getbatch__( g_ind[i * eval_batch : (i + 1) * eval_batch] ) imgs = flow.Tensor(np.array(imgs)).to("cuda") with flow.no_grad(): features = model(imgs) gf.append(features.numpy()) g_pids.extend(pids) g_camids.extend(camids) gf = np.concatenate(gf, 0) g_pids = np.asarray(g_pids) g_camids = np.asarray(g_camids) print("Done, obtained {}-by-{} matrix".format(gf.shape[0], gf.shape[1])) print("Computing distance matrix with metric={} ...".format(dist_metric)) distmat = compute_distance_matrix(qf, gf, dist_metric) if rerank: print("Applying person re-ranking ...") distmat_qq = compute_distance_matrix(qf, qf, dist_metric) distmat_gg = compute_distance_matrix(gf, gf, dist_metric) distmat = re_ranking(distmat, distmat_qq, distmat_gg) print("Computing CMC and mAP ...") cmc, mAP = _eval(distmat, q_pids, g_pids, q_camids, g_camids) print("=".ljust(30, "=") + " Result " + "=".ljust(30, "=")) print("mAP: {:.1%}".format(mAP)) print("CMC curve") for r in [1, 5, 10]: print("Rank-{:<3}: {:.1%}".format(r, cmc[r - 1])) print("=".ljust(66, "=")) return cmc[0], mAP def _eval(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50): """Evaluation with market1501 metric Key: for each query identity, its gallery images from the same camera view are discarded. """ num_q, num_g = distmat.shape if num_g < max_rank: max_rank = num_g print("Note: number of gallery samples is quite small, got {}".format(num_g)) indices = np.argsort(distmat, axis=1) matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32) # compute cmc curve for each query all_cmc = [] all_AP = [] num_valid_q = 0.0 # number of valid query for q_idx in range(num_q): # get query pid and camid q_pid = q_pids[q_idx] q_camid = q_camids[q_idx] # remove gallery samples that have the same pid and camid with query order = indices[q_idx] remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid) keep = np.invert(remove) # compute cmc curve # binary vector, positions with value 1 are correct matches raw_cmc = matches[q_idx][keep] if not np.any(raw_cmc): # this condition is true when query identity does not appear in gallery continue cmc = raw_cmc.cumsum() cmc[cmc > 1] = 1 all_cmc.append(cmc[:max_rank]) num_valid_q += 1.0 # compute average precision # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision num_rel = raw_cmc.sum() tmp_cmc = raw_cmc.cumsum() tmp_cmc = [x / (i + 1.0) for i, x in enumerate(tmp_cmc)] tmp_cmc = np.asarray(tmp_cmc) * raw_cmc AP = tmp_cmc.sum() / num_rel all_AP.append(AP) assert num_valid_q > 0, "Error: all query identities do not appear in gallery" all_cmc = np.asarray(all_cmc).astype(np.float32) all_cmc = all_cmc.sum(0) / num_valid_q mAP = np.mean(all_AP) return all_cmc, mAP def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1=20, k2=6, lambda_value=0.3): # The following naming, e.g. gallery_num, is different from outer scope. # Don't care about it. original_dist = np.concatenate( [ np.concatenate([q_q_dist, q_g_dist], axis=1), np.concatenate([q_g_dist.T, g_g_dist], axis=1), ], axis=0, ) original_dist = np.power(original_dist, 2).astype(np.float32) original_dist = np.transpose(1.0 * original_dist / np.max(original_dist, axis=0)) V = np.zeros_like(original_dist).astype(np.float32) initial_rank = np.argsort(original_dist).astype(np.int32) query_num = q_g_dist.shape[0] gallery_num = q_g_dist.shape[0] + q_g_dist.shape[1] all_num = gallery_num for i in range(all_num): # k-reciprocal neighbors forward_k_neigh_index = initial_rank[i, : k1 + 1] backward_k_neigh_index = initial_rank[forward_k_neigh_index, : k1 + 1] fi = np.where(backward_k_neigh_index == i)[0] k_reciprocal_index = forward_k_neigh_index[fi] k_reciprocal_expansion_index = k_reciprocal_index for j in range(len(k_reciprocal_index)): candidate = k_reciprocal_index[j] candidate_forward_k_neigh_index = initial_rank[ candidate, : int(np.around(k1 / 2.0)) + 1 ] candidate_backward_k_neigh_index = initial_rank[ candidate_forward_k_neigh_index, : int(np.around(k1 / 2.0)) + 1 ] fi_candidate = np.where(candidate_backward_k_neigh_index == candidate)[0] candidate_k_reciprocal_index = candidate_forward_k_neigh_index[fi_candidate] if len( np.intersect1d(candidate_k_reciprocal_index, k_reciprocal_index) ) > 2.0 / 3 * len(candidate_k_reciprocal_index): k_reciprocal_expansion_index = np.append( k_reciprocal_expansion_index, candidate_k_reciprocal_index ) k_reciprocal_expansion_index = np.unique(k_reciprocal_expansion_index) weight = np.exp(-original_dist[i, k_reciprocal_expansion_index]) V[i, k_reciprocal_expansion_index] = 1.0 * weight / np.sum(weight) original_dist = original_dist[ :query_num, ] if k2 != 1: V_qe = np.zeros_like(V, dtype=np.float32) for i in range(all_num): V_qe[i, :] = np.mean(V[initial_rank[i, :k2], :], axis=0) V = V_qe del V_qe del initial_rank invIndex = [] for i in range(gallery_num): invIndex.append(np.where(V[:, i] != 0)[0]) jaccard_dist = np.zeros_like(original_dist, dtype=np.float32) # get jaccard_dist for i in range(query_num): temp_min = np.zeros(shape=[1, gallery_num], dtype=np.float32) indNonZero = np.where(V[i, :] != 0)[0] # q_i's k-reciprocal index indImages = [invIndex[ind] for ind in indNonZero] # for j in range(len(indNonZero)): temp_min[0, indImages[j]] = temp_min[0, indImages[j]] + np.minimum( V[i, indNonZero[j]], V[indImages[j], indNonZero[j]] # V_pigj, V_gigj ) jaccard_dist[i] = 1 - temp_min / (2.0 - temp_min) final_dist = jaccard_dist * (1 - lambda_value) + original_dist * lambda_value del original_dist del V del jaccard_dist final_dist = final_dist[:query_num, query_num:] return final_dist if __name__ == "__main__": args = _parse_args() main(args)
[]
[]
[ "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_VISIBLE_DEVICES"]
python
1
0
store/file/file_test.go
package file import ( "fmt" "os" "path/filepath" "strings" "testing" "time" "github.com/davecgh/go-spew/spew" "github.com/kr/pretty" "github.com/panovateam/go-micro/store" ) func cleanup(db string, s store.Store) { s.Close() dir := filepath.Join(DefaultDir, db+"/") os.RemoveAll(dir) } func TestFileStoreReInit(t *testing.T) { s := NewStore(store.Table("aaa")) defer cleanup(DefaultDatabase, s) s.Init(store.Table("bbb")) if s.Options().Table != "bbb" { t.Error("Init didn't reinitialise the store") } } func TestFileStoreBasic(t *testing.T) { s := NewStore() defer cleanup(DefaultDatabase, s) fileTest(s, t) } func TestFileStoreTable(t *testing.T) { s := NewStore(store.Table("testTable")) defer cleanup(DefaultDatabase, s) fileTest(s, t) } func TestFileStoreDatabase(t *testing.T) { s := NewStore(store.Database("testdb")) defer cleanup("testdb", s) fileTest(s, t) } func TestFileStoreDatabaseTable(t *testing.T) { s := NewStore(store.Table("testTable"), store.Database("testdb")) defer cleanup("testdb", s) fileTest(s, t) } func fileTest(s store.Store, t *testing.T) { if len(os.Getenv("IN_TRAVIS_CI")) == 0 { t.Logf("Options %s %v\n", s.String(), s.Options()) } // Read and Write an expiring Record if err := s.Write(&store.Record{ Key: "Hello", Value: []byte("World"), Expiry: time.Millisecond * 150, }); err != nil { t.Error(err) } if r, err := s.Read("Hello"); err != nil { t.Fatal(err) } else { if len(r) != 1 { t.Error("Read returned multiple records") } if r[0].Key != "Hello" { t.Errorf("Expected %s, got %s", "Hello", r[0].Key) } if string(r[0].Value) != "World" { t.Errorf("Expected %s, got %s", "World", r[0].Value) } } // wait for expiry time.Sleep(time.Millisecond * 200) if _, err := s.Read("Hello"); err != store.ErrNotFound { t.Errorf("Expected %# v, got %# v", store.ErrNotFound, err) } // Write 3 records with various expiry and get with Table records := []*store.Record{ &store.Record{ Key: "foo", Value: []byte("foofoo"), }, &store.Record{ Key: "foobar", Value: []byte("foobarfoobar"), Expiry: time.Millisecond * 100, }, } for _, r := range records { if err := s.Write(r); err != nil { t.Errorf("Couldn't write k: %s, v: %# v (%s)", r.Key, pretty.Formatter(r.Value), err) } } if results, err := s.Read("foo", store.ReadPrefix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 2 { t.Errorf("Expected 2 items, got %d", len(results)) //t.Logf("Table test: %v\n", spew.Sdump(results)) } } // wait for the expiry time.Sleep(time.Millisecond * 200) if results, err := s.Read("foo", store.ReadPrefix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else if len(results) != 1 { t.Errorf("Expected 1 item, got %d", len(results)) //t.Logf("Table test: %v\n", spew.Sdump(results)) } if err := s.Delete("foo"); err != nil { t.Errorf("Delete failed (%v)", err) } if results, err := s.Read("foo"); err != store.ErrNotFound { t.Errorf("Expected read failure read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 0 { t.Errorf("Expected 0 items, got %d (%# v)", len(results), spew.Sdump(results)) } } // Write 3 records with various expiry and get with Suffix records = []*store.Record{ &store.Record{ Key: "foo", Value: []byte("foofoo"), }, &store.Record{ Key: "barfoo", Value: []byte("barfoobarfoo"), Expiry: time.Millisecond * 100, }, &store.Record{ Key: "bazbarfoo", Value: []byte("bazbarfoobazbarfoo"), Expiry: 2 * time.Millisecond * 100, }, } for _, r := range records { if err := s.Write(r); err != nil { t.Errorf("Couldn't write k: %s, v: %# v (%s)", r.Key, pretty.Formatter(r.Value), err) } } if results, err := s.Read("foo", store.ReadSuffix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 3 { t.Errorf("Expected 3 items, got %d", len(results)) //t.Logf("Table test: %v\n", spew.Sdump(results)) } } time.Sleep(time.Millisecond * 100) if results, err := s.Read("foo", store.ReadSuffix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 2 { t.Errorf("Expected 2 items, got %d", len(results)) //t.Logf("Table test: %v\n", spew.Sdump(results)) } } time.Sleep(time.Millisecond * 100) if results, err := s.Read("foo", store.ReadSuffix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 1 { t.Errorf("Expected 1 item, got %d", len(results)) // t.Logf("Table test: %# v\n", spew.Sdump(results)) } } if err := s.Delete("foo"); err != nil { t.Errorf("Delete failed (%v)", err) } if results, err := s.Read("foo", store.ReadSuffix()); err != nil { t.Errorf("Couldn't read all \"foo\" keys, got %# v (%s)", spew.Sdump(results), err) } else { if len(results) != 0 { t.Errorf("Expected 0 items, got %d (%# v)", len(results), spew.Sdump(results)) } } // Test Table, Suffix and WriteOptions if err := s.Write(&store.Record{ Key: "foofoobarbar", Value: []byte("something"), }, store.WriteTTL(time.Millisecond*100)); err != nil { t.Error(err) } if err := s.Write(&store.Record{ Key: "foofoo", Value: []byte("something"), }, store.WriteExpiry(time.Now().Add(time.Millisecond*100))); err != nil { t.Error(err) } if err := s.Write(&store.Record{ Key: "barbar", Value: []byte("something"), // TTL has higher precedence than expiry }, store.WriteExpiry(time.Now().Add(time.Hour)), store.WriteTTL(time.Millisecond*100)); err != nil { t.Error(err) } if results, err := s.Read("foo", store.ReadPrefix(), store.ReadSuffix()); err != nil { t.Error(err) } else { if len(results) != 1 { t.Errorf("Expected 1 results, got %d: %# v", len(results), spew.Sdump(results)) } } time.Sleep(time.Millisecond * 100) if results, err := s.List(); err != nil { t.Errorf("List failed: %s", err) } else { if len(results) != 0 { t.Errorf("Expiry options were not effective, results :%v", spew.Sdump(results)) } } // write the following records for i := 0; i < 10; i++ { s.Write(&store.Record{ Key: fmt.Sprintf("a%d", i), Value: []byte{}, }) } // read back a few records if results, err := s.Read("a", store.ReadLimit(5), store.ReadPrefix()); err != nil { t.Error(err) } else { if len(results) != 5 { t.Fatal("Expected 5 results, got ", len(results)) } if !strings.HasPrefix(results[0].Key, "a") { t.Fatalf("Expected a prefix, got %s", results[0].Key) } } // read the rest back if results, err := s.Read("a", store.ReadLimit(30), store.ReadOffset(5), store.ReadPrefix()); err != nil { t.Fatal(err) } else { if len(results) != 5 { t.Fatal("Expected 5 results, got ", len(results)) } } }
[ "\"IN_TRAVIS_CI\"" ]
[]
[ "IN_TRAVIS_CI" ]
[]
["IN_TRAVIS_CI"]
go
1
0
vendor/github.com/HewlettPackard/oneview-golang/examples/server_hardware.go
package main import ( "fmt" "github.com/HewlettPackard/oneview-golang/ov" "os" "strconv" ) func main() { var ( ClientOV *ov.OVClient server_1 = "<server_hardware_name>" server_2 = "<server_hardware_name>" ) apiversion, _ := strconv.Atoi(os.Getenv("ONEVIEW_APIVERSION")) ovc := ClientOV.NewOVClient( os.Getenv("ONEVIEW_OV_USER"), os.Getenv("ONEVIEW_OV_PASSWORD"), os.Getenv("ONEVIEW_OV_DOMAIN"), os.Getenv("ONEVIEW_OV_ENDPOINT"), false, apiversion, "*") fmt.Println("Get server hardware list by name") serverName, err := ovc.GetServerHardwareByName(server_1) if err != nil { fmt.Println("Failed to fetch server hardware name: ", err) } else { fmt.Println("******************") fmt.Println("Server hardware details ") fmt.Println(serverName.Model) fmt.Println(serverName.URI) fmt.Println(serverName.UUID) fmt.Println("******************") fmt.Println("Server hardware IloIPAddress ") fmt.Println(serverName.GetIloIPAddress()) fmt.Println("******************") fmt.Println("Server hardware MpIPAddresses ") if ovc.IsHardwareSchemaV2() { for i := 0; i < len(serverName.MpHostInfo.MpIPAddresses); i++ { fmt.Println(serverName.MpHostInfo.MpIPAddresses[i].Address) } } } fmt.Println("Get server hardware list by url") fmt.Println("******************") ServerId, err := ovc.GetServerHardwareByUri(serverName.URI) if err == nil { fmt.Println(ServerId.URI) } else { fmt.Println("Failed to fetch server hardware : ", err) } fmt.Println("Get server-hardware list statistics specifying parameters") fmt.Println("******************") filters := []string{"name matches 'SY 660 Gen9 2'"} ServerList, err := ovc.GetServerHardwareList(filters, "", "", "", "") if err == nil { fmt.Println("Total server list :", ServerList.Total) } else { fmt.Println("Failed to fetch server List : ", err) } fmt.Println("Get firmware inventory for a server-hardware") fmt.Println("******************") firmware, err := ovc.GetServerFirmwareByUri(ServerId.URI) if err == nil { fmt.Println(firmware.ServerName) } else { fmt.Println("Failed to fetch Firmwares: ", err) } fmt.Println("******************") server2, err := ovc.GetServerHardwareByName(server_1) server1, err := ovc.GetServerHardwareByName(server_2) serverHarware, err := ovc.GetAvailableHardware(string(server2.URI), string(server1.URI)) if err == nil { fmt.Println(serverHarware.Type) } else { fmt.Println("Failed to fetch server hardware by URI: ", err) } fmt.Println("Get power status of a server ") fmt.Println("******************") powerState, err := serverName.GetPowerState() if err == nil { fmt.Println("Power state of the machine is ", powerState) } else { fmt.Println("Failed to fetch powerstate of the server: ", err) } //Trying to touggle power state of the server using put if powerState.String() == "On" { fmt.Println("Server is in powered on state ") serverName.PowerOff() powerState, _ := serverName.GetPowerState() fmt.Println("Power state of the machine is ", powerState) } else { fmt.Println("Server is in powered off state ") serverName.PowerOn() powerState, _ := serverName.GetPowerState() fmt.Println("Power state of the machine is ", powerState) } fmt.Println("Get ilo ipaddress of a server ") fmt.Println("******************") iloIpaddress := serverName.GetIloIPAddress() fmt.Println("ilo ip address of an server is =", iloIpaddress) }
[ "\"ONEVIEW_APIVERSION\"", "\"ONEVIEW_OV_USER\"", "\"ONEVIEW_OV_PASSWORD\"", "\"ONEVIEW_OV_DOMAIN\"", "\"ONEVIEW_OV_ENDPOINT\"" ]
[]
[ "ONEVIEW_OV_ENDPOINT", "ONEVIEW_OV_DOMAIN", "ONEVIEW_APIVERSION", "ONEVIEW_OV_PASSWORD", "ONEVIEW_OV_USER" ]
[]
["ONEVIEW_OV_ENDPOINT", "ONEVIEW_OV_DOMAIN", "ONEVIEW_APIVERSION", "ONEVIEW_OV_PASSWORD", "ONEVIEW_OV_USER"]
go
5
0
common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.conf; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.common.FileUtils; import org.apache.hadoop.hive.common.classification.InterfaceAudience; import org.apache.hadoop.hive.common.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.hive.common.type.TimestampTZUtil; import org.apache.hadoop.hive.conf.Validator.PatternSet; import org.apache.hadoop.hive.conf.Validator.RangeValidator; import org.apache.hadoop.hive.conf.Validator.RatioValidator; import org.apache.hadoop.hive.conf.Validator.SizeValidator; import org.apache.hadoop.hive.conf.Validator.StringSet; import org.apache.hadoop.hive.conf.Validator.TimeValidator; import org.apache.hadoop.hive.conf.Validator.WritableDirectoryValidator; import org.apache.hadoop.hive.shims.Utils; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.ssl.FileBasedKeyStoresFactory; import org.apache.hadoop.security.ssl.SSLFactory; import org.apache.hive.common.HiveCompat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.login.LoginException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Hive Configuration. */ public class HiveConf extends Configuration { protected String hiveJar; protected Properties origProp; protected String auxJars; private static final Logger LOG = LoggerFactory.getLogger(HiveConf.class); private static boolean loadMetastoreConfig = false; private static boolean loadHiveServer2Config = false; private static URL hiveDefaultURL = null; private static URL hiveSiteURL = null; private static URL hivemetastoreSiteUrl = null; private static URL hiveServer2SiteUrl = null; private static byte[] confVarByteArray = null; private static final Map<String, ConfVars> vars = new HashMap<String, ConfVars>(); private static final Map<String, ConfVars> metaConfs = new HashMap<String, ConfVars>(); private final List<String> restrictList = new ArrayList<String>(); private final Set<String> hiddenSet = new HashSet<String>(); private final List<String> rscList = new ArrayList<>(); private Pattern modWhiteListPattern = null; private volatile boolean isSparkConfigUpdated = false; private static final int LOG_PREFIX_LENGTH = 64; public boolean getSparkConfigUpdated() { return isSparkConfigUpdated; } public void setSparkConfigUpdated(boolean isSparkConfigUpdated) { this.isSparkConfigUpdated = isSparkConfigUpdated; } public interface EncoderDecoder<K, V> { V encode(K key); K decode(V value); } public static class URLEncoderDecoder implements EncoderDecoder<String, String> { @Override public String encode(String key) { try { return URLEncoder.encode(key, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return key; } } @Override public String decode(String value) { try { return URLDecoder.decode(value, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return value; } } } public static class EncoderDecoderFactory { public static final URLEncoderDecoder URL_ENCODER_DECODER = new URLEncoderDecoder(); } static { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = HiveConf.class.getClassLoader(); } hiveDefaultURL = classLoader.getResource("hive-default.xml"); // Look for hive-site.xml on the CLASSPATH and log its location if found. hiveSiteURL = findConfigFile(classLoader, "hive-site.xml", true); hivemetastoreSiteUrl = findConfigFile(classLoader, "hivemetastore-site.xml", false); hiveServer2SiteUrl = findConfigFile(classLoader, "hiveserver2-site.xml", false); for (ConfVars confVar : ConfVars.values()) { vars.put(confVar.varname, confVar); } Set<String> llapDaemonConfVarsSetLocal = new LinkedHashSet<>(); populateLlapDaemonVarsSet(llapDaemonConfVarsSetLocal); llapDaemonVarsSet = Collections.unmodifiableSet(llapDaemonConfVarsSetLocal); } private static URL findConfigFile(ClassLoader classLoader, String name, boolean doLog) { URL result = classLoader.getResource(name); if (result == null) { String confPath = System.getenv("HIVE_CONF_DIR"); result = checkConfigFile(new File(confPath, name)); if (result == null) { String homePath = System.getenv("HIVE_HOME"); String nameInConf = "conf" + File.separator + name; result = checkConfigFile(new File(homePath, nameInConf)); if (result == null) { URI jarUri = null; try { // Handle both file:// and jar:<url>!{entry} in the case of shaded hive libs URL sourceUrl = HiveConf.class.getProtectionDomain().getCodeSource().getLocation(); jarUri = sourceUrl.getProtocol().equalsIgnoreCase("jar") ? new URI(sourceUrl.getPath()) : sourceUrl.toURI(); } catch (Throwable e) { LOG.info("Cannot get jar URI", e); System.err.println("Cannot get jar URI: " + e.getMessage()); } // From the jar file, the parent is /lib folder File parent = new File(jarUri).getParentFile(); if (parent != null) { result = checkConfigFile(new File(parent.getParentFile(), nameInConf)); } } } } if (doLog) { LOG.info("Found configuration file {}", result); } return result; } private static URL checkConfigFile(File f) { try { return (f.exists() && f.isFile()) ? f.toURI().toURL() : null; } catch (Throwable e) { LOG.info("Error looking for config {}", f, e); System.err.println("Error looking for config " + f + ": " + e.getMessage()); return null; } } @InterfaceAudience.Private public static final String PREFIX_LLAP = "llap."; @InterfaceAudience.Private public static final String PREFIX_HIVE_LLAP = "hive.llap."; /** * Metastore related options that the db is initialized against. When a conf * var in this is list is changed, the metastore instance for the CLI will * be recreated so that the change will take effect. */ public static final HiveConf.ConfVars[] metaVars = { HiveConf.ConfVars.METASTOREWAREHOUSE, HiveConf.ConfVars.REPLDIR, HiveConf.ConfVars.METASTOREURIS, HiveConf.ConfVars.METASTORESELECTION, HiveConf.ConfVars.METASTORE_SERVER_PORT, HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, HiveConf.ConfVars.METASTORETHRIFTFAILURERETRIES, HiveConf.ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY, HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_LIFETIME, HiveConf.ConfVars.METASTORECONNECTURLHOOK, HiveConf.ConfVars.METASTORECONNECTURLKEY, HiveConf.ConfVars.METASTORESERVERMINTHREADS, HiveConf.ConfVars.METASTORESERVERMAXTHREADS, HiveConf.ConfVars.METASTORE_TCP_KEEP_ALIVE, HiveConf.ConfVars.METASTORE_INT_ORIGINAL, HiveConf.ConfVars.METASTORE_INT_ARCHIVED, HiveConf.ConfVars.METASTORE_INT_EXTRACTED, HiveConf.ConfVars.METASTORE_KERBEROS_KEYTAB_FILE, HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL, HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL, HiveConf.ConfVars.METASTORE_TOKEN_SIGNATURE, HiveConf.ConfVars.METASTORE_CACHE_PINOBJTYPES, HiveConf.ConfVars.METASTORE_CONNECTION_POOLING_TYPE, HiveConf.ConfVars.METASTORE_VALIDATE_TABLES, HiveConf.ConfVars.METASTORE_DATANUCLEUS_INIT_COL_INFO, HiveConf.ConfVars.METASTORE_VALIDATE_COLUMNS, HiveConf.ConfVars.METASTORE_VALIDATE_CONSTRAINTS, HiveConf.ConfVars.METASTORE_STORE_MANAGER_TYPE, HiveConf.ConfVars.METASTORE_TRANSACTION_ISOLATION, HiveConf.ConfVars.METASTORE_CACHE_LEVEL2, HiveConf.ConfVars.METASTORE_CACHE_LEVEL2_TYPE, HiveConf.ConfVars.METASTORE_IDENTIFIER_FACTORY, HiveConf.ConfVars.METASTORE_PLUGIN_REGISTRY_BUNDLE_CHECK, HiveConf.ConfVars.METASTORE_AUTHORIZATION_STORAGE_AUTH_CHECKS, HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_MAX, HiveConf.ConfVars.METASTORE_EVENT_LISTENERS, HiveConf.ConfVars.METASTORE_TRANSACTIONAL_EVENT_LISTENERS, HiveConf.ConfVars.METASTORE_EVENT_CLEAN_FREQ, HiveConf.ConfVars.METASTORE_EVENT_EXPIRY_DURATION, HiveConf.ConfVars.METASTORE_EVENT_MESSAGE_FACTORY, HiveConf.ConfVars.METASTORE_FILTER_HOOK, HiveConf.ConfVars.METASTORE_RAW_STORE_IMPL, HiveConf.ConfVars.METASTORE_END_FUNCTION_LISTENERS, HiveConf.ConfVars.METASTORE_PART_INHERIT_TBL_PROPS, HiveConf.ConfVars.METASTORE_BATCH_RETRIEVE_OBJECTS_MAX, HiveConf.ConfVars.METASTORE_INIT_HOOKS, HiveConf.ConfVars.METASTORE_PRE_EVENT_LISTENERS, HiveConf.ConfVars.HMSHANDLERATTEMPTS, HiveConf.ConfVars.HMSHANDLERINTERVAL, HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF, HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN, HiveConf.ConfVars.METASTORE_ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS, HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES, HiveConf.ConfVars.USERS_IN_ADMIN_ROLE, HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER, HiveConf.ConfVars.HIVE_TXN_MANAGER, HiveConf.ConfVars.HIVE_TXN_TIMEOUT, HiveConf.ConfVars.HIVE_TXN_OPERATIONAL_PROPERTIES, HiveConf.ConfVars.HIVE_TXN_HEARTBEAT_THREADPOOL_SIZE, HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH, HiveConf.ConfVars.HIVE_TXN_RETRYABLE_SQLEX_REGEX, HiveConf.ConfVars.HIVE_METASTORE_STATS_NDV_TUNER, HiveConf.ConfVars.HIVE_METASTORE_STATS_NDV_DENSITY_FUNCTION, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_ENABLED, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_SIZE, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_PARTITIONS, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_FPP, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_VARIANCE, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_TTL, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_READER_WAIT, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_MAX_FULL, HiveConf.ConfVars.METASTORE_AGGREGATE_STATS_CACHE_CLEAN_UNTIL, HiveConf.ConfVars.METASTORE_FASTPATH, HiveConf.ConfVars.METASTORE_HBASE_FILE_METADATA_THREADS, HiveConf.ConfVars.METASTORE_WM_DEFAULT_POOL_SIZE }; /** * User configurable Metastore vars */ public static final HiveConf.ConfVars[] metaConfVars = { HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL, HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL_DDL, HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, HiveConf.ConfVars.METASTORE_PARTITION_NAME_WHITELIST_PATTERN, HiveConf.ConfVars.METASTORE_CAPABILITY_CHECK, HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES }; static { for (ConfVars confVar : metaConfVars) { metaConfs.put(confVar.varname, confVar); } } public static final String HIVE_LLAP_DAEMON_SERVICE_PRINCIPAL_NAME = "hive.llap.daemon.service.principal"; public static final String HIVE_SERVER2_AUTHENTICATION_LDAP_USERMEMBERSHIPKEY_NAME = "hive.server2.authentication.ldap.userMembershipKey"; /** * dbVars are the parameters can be set per database. If these * parameters are set as a database property, when switching to that * database, the HiveConf variable will be changed. The change of these * parameters will effectively change the DFS and MapReduce clusters * for different databases. */ public static final HiveConf.ConfVars[] dbVars = { HiveConf.ConfVars.HADOOPBIN, HiveConf.ConfVars.METASTOREWAREHOUSE, HiveConf.ConfVars.SCRATCHDIR }; /** * encoded parameter values are ;-) encoded. Use decoder to get ;-) decoded string */ public static final HiveConf.ConfVars[] ENCODED_CONF = { ConfVars.HIVEQUERYSTRING }; /** * Variables used by LLAP daemons. * TODO: Eventually auto-populate this based on prefixes. The conf variables * will need to be renamed for this. */ private static final Set<String> llapDaemonVarsSet; private static void populateLlapDaemonVarsSet(Set<String> llapDaemonVarsSetLocal) { llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_ENABLED.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_MEMORY_MODE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_MIN_ALLOC.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_MAX_ALLOC.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_ARENA_COUNT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_MEMORY_MAX_SIZE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOCATOR_DIRECT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_USE_LRFU.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_LRFU_LAMBDA.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_CACHE_ALLOW_SYNTHETIC_FILEID.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_USE_FILEID_PATH.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_DECODING_METRICS_PERCENTILE_INTERVALS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ORC_ENABLE_TIME_COUNTERS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_IO_THREADPOOL_SIZE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_KERBEROS_PRINCIPAL.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_KERBEROS_KEYTAB_FILE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ZKSM_ZK_CONNECTION_STRING.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_SECURITY_ACL.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_ACL.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_SECURITY_ACL_DENY.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_ACL_DENY.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DELEGATION_TOKEN_LIFETIME.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_MANAGEMENT_RPC_PORT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_WEB_AUTO_AUTH.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_RPC_NUM_HANDLERS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WORK_DIRS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_YARN_SHUFFLE_PORT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_YARN_CONTAINER_MB.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SHUFFLE_DIR_WATCHER_ENABLED.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_HEARTBEAT_INTERVAL_MS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_CONNECTION_TIMEOUT_MS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_LIVENESS_CONNECTION_SLEEP_BETWEEN_RETRIES_MS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_NUM_EXECUTORS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_RPC_PORT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_MEMORY_PER_INSTANCE_MB.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_XMX_HEADROOM.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_VCPUS_PER_INSTANCE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_NUM_FILE_CLEANER_THREADS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_FILE_CLEANUP_DELAY_SECONDS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_SERVICE_REFRESH_INTERVAL.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_ALLOW_PERMANENT_FNS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_DOWNLOAD_PERMANENT_FNS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_SCHEDULER_WAIT_QUEUE_SIZE.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WAIT_QUEUE_COMPARATOR_CLASS_NAME.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_SCHEDULER_ENABLE_PREEMPTION.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_TASK_PREEMPTION_METRICS_INTERVALS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WEB_PORT.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_WEB_SSL.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_CONTAINER_ID.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_VALIDATE_ACLS.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_LOGGER.varname); llapDaemonVarsSetLocal.add(ConfVars.LLAP_DAEMON_AM_USE_FQDN.varname); } /** * Get a set containing configuration parameter names used by LLAP Server isntances * @return an unmodifiable set containing llap ConfVars */ public static final Set<String> getLlapDaemonConfVars() { return llapDaemonVarsSet; } /** * ConfVars. * * These are the default configuration properties for Hive. Each HiveConf * object is initialized as follows: * * 1) Hadoop configuration properties are applied. * 2) ConfVar properties with non-null values are overlayed. * 3) hive-site.xml properties are overlayed. * * WARNING: think twice before adding any Hadoop configuration properties * with non-null values to this list as they will override any values defined * in the underlying Hadoop configuration. */ public static enum ConfVars { // QL execution stuff SCRIPTWRAPPER("hive.exec.script.wrapper", null, ""), PLAN("hive.exec.plan", "", ""), STAGINGDIR("hive.exec.stagingdir", ".hive-staging", "Directory name that will be created inside table locations in order to support HDFS encryption. " + "This is replaces ${hive.exec.scratchdir} for query results with the exception of read-only tables. " + "In all cases ${hive.exec.scratchdir} is still used for other temporary files, such as job plans."), SCRATCHDIR("hive.exec.scratchdir", "/tmp/hive", "HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. " + "For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/<username> is created, " + "with ${hive.scratch.dir.permission}."), REPLDIR("hive.repl.rootdir","/user/hive/repl/", "HDFS root dir for all replication dumps."), REPLCMENABLED("hive.repl.cm.enabled", false, "Turn on ChangeManager, so delete files will go to cmrootdir."), REPLCMDIR("hive.repl.cmrootdir","/user/hive/cmroot/", "Root dir for ChangeManager, used for deleted files."), REPLCMRETIAN("hive.repl.cm.retain","24h", new TimeValidator(TimeUnit.HOURS), "Time to retain removed files in cmrootdir."), REPLCMINTERVAL("hive.repl.cm.interval","3600s", new TimeValidator(TimeUnit.SECONDS), "Inteval for cmroot cleanup thread."), REPL_FUNCTIONS_ROOT_DIR("hive.repl.replica.functions.root.dir","/user/hive/repl/functions/", "Root directory on the replica warehouse where the repl sub-system will store jars from the primary warehouse"), REPL_APPROX_MAX_LOAD_TASKS("hive.repl.approx.max.load.tasks", 10000, "Provide an approximation of the maximum number of tasks that should be executed before \n" + "dynamically generating the next set of tasks. The number is approximate as Hive \n" + "will stop at a slightly higher number, the reason being some events might lead to a \n" + "task increment that would cross the specified limit."), REPL_PARTITIONS_DUMP_PARALLELISM("hive.repl.partitions.dump.parallelism",100, "Number of threads that will be used to dump partition data information during repl dump."), REPL_DUMPDIR_CLEAN_FREQ("hive.repl.dumpdir.clean.freq", "0s", new TimeValidator(TimeUnit.SECONDS), "Frequency at which timer task runs to purge expired dump dirs."), REPL_DUMPDIR_TTL("hive.repl.dumpdir.ttl", "7d", new TimeValidator(TimeUnit.DAYS), "TTL of dump dirs before cleanup."), REPL_DUMP_METADATA_ONLY("hive.repl.dump.metadata.only", false, "Indicates whether replication dump only metadata information or data + metadata."), REPL_DUMP_INCLUDE_ACID_TABLES("hive.repl.dump.include.acid.tables", false, "Indicates if repl dump should include information about ACID tables. It should be \n" + "used in conjunction with 'hive.repl.dump.metadata.only' to enable copying of \n" + "metadata for acid tables which do not require the corresponding transaction \n" + "semantics to be applied on target. This can be removed when ACID table \n" + "replication is supported."), REPL_BOOTSTRAP_DUMP_OPEN_TXN_TIMEOUT("hive.repl.bootstrap.dump.open.txn.timeout", "1h", new TimeValidator(TimeUnit.HOURS), "Indicates the timeout for all transactions which are opened before triggering bootstrap REPL DUMP. " + "If these open transactions are not closed within the timeout value, then REPL DUMP will " + "forcefully abort those transactions and continue with bootstrap dump."), //https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/TransparentEncryption.html#Running_as_the_superuser REPL_ADD_RAW_RESERVED_NAMESPACE("hive.repl.add.raw.reserved.namespace", false, "For TDE with same encryption keys on source and target, allow Distcp super user to access \n" + "the raw bytes from filesystem without decrypting on source and then encrypting on target."), LOCALSCRATCHDIR("hive.exec.local.scratchdir", "${system:java.io.tmpdir}" + File.separator + "${system:user.name}", "Local scratch space for Hive jobs"), DOWNLOADED_RESOURCES_DIR("hive.downloaded.resources.dir", "${system:java.io.tmpdir}" + File.separator + "${hive.session.id}_resources", "Temporary local directory for added resources in the remote file system."), SCRATCHDIRPERMISSION("hive.scratch.dir.permission", "700", "The permission for the user specific scratch directories that get created."), SUBMITVIACHILD("hive.exec.submitviachild", false, ""), SUBMITLOCALTASKVIACHILD("hive.exec.submit.local.task.via.child", true, "Determines whether local tasks (typically mapjoin hashtable generation phase) runs in \n" + "separate JVM (true recommended) or not. \n" + "Avoids the overhead of spawning new JVM, but can lead to out-of-memory issues."), SCRIPTERRORLIMIT("hive.exec.script.maxerrsize", 100000, "Maximum number of bytes a script is allowed to emit to standard error (per map-reduce task). \n" + "This prevents runaway scripts from filling logs partitions to capacity"), ALLOWPARTIALCONSUMP("hive.exec.script.allow.partial.consumption", false, "When enabled, this option allows a user script to exit successfully without consuming \n" + "all the data from the standard input."), STREAMREPORTERPERFIX("stream.stderr.reporter.prefix", "reporter:", "Streaming jobs that log to standard error with this prefix can log counter or status information."), STREAMREPORTERENABLED("stream.stderr.reporter.enabled", true, "Enable consumption of status and counter messages for streaming jobs."), COMPRESSRESULT("hive.exec.compress.output", false, "This controls whether the final outputs of a query (to a local/HDFS file or a Hive table) is compressed. \n" + "The compression codec and other options are determined from Hadoop config variables mapred.output.compress*"), COMPRESSINTERMEDIATE("hive.exec.compress.intermediate", false, "This controls whether intermediate files produced by Hive between multiple map-reduce jobs are compressed. \n" + "The compression codec and other options are determined from Hadoop config variables mapred.output.compress*"), COMPRESSINTERMEDIATECODEC("hive.intermediate.compression.codec", "", ""), COMPRESSINTERMEDIATETYPE("hive.intermediate.compression.type", "", ""), BYTESPERREDUCER("hive.exec.reducers.bytes.per.reducer", (long) (256 * 1000 * 1000), "size per reducer.The default is 256Mb, i.e if the input size is 1G, it will use 4 reducers."), MAXREDUCERS("hive.exec.reducers.max", 1009, "max number of reducers will be used. If the one specified in the configuration parameter mapred.reduce.tasks is\n" + "negative, Hive will use this one as the max number of reducers when automatically determine number of reducers."), PREEXECHOOKS("hive.exec.pre.hooks", "", "Comma-separated list of pre-execution hooks to be invoked for each statement. \n" + "A pre-execution hook is specified as the name of a Java class which implements the \n" + "org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."), POSTEXECHOOKS("hive.exec.post.hooks", "", "Comma-separated list of post-execution hooks to be invoked for each statement. \n" + "A post-execution hook is specified as the name of a Java class which implements the \n" + "org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."), ONFAILUREHOOKS("hive.exec.failure.hooks", "", "Comma-separated list of on-failure hooks to be invoked for each statement. \n" + "An on-failure hook is specified as the name of Java class which implements the \n" + "org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext interface."), QUERYREDACTORHOOKS("hive.exec.query.redactor.hooks", "", "Comma-separated list of hooks to be invoked for each query which can \n" + "tranform the query before it's placed in the job.xml file. Must be a Java class which \n" + "extends from the org.apache.hadoop.hive.ql.hooks.Redactor abstract class."), CLIENTSTATSPUBLISHERS("hive.client.stats.publishers", "", "Comma-separated list of statistics publishers to be invoked on counters on each job. \n" + "A client stats publisher is specified as the name of a Java class which implements the \n" + "org.apache.hadoop.hive.ql.stats.ClientStatsPublisher interface."), ATSHOOKQUEUECAPACITY("hive.ats.hook.queue.capacity", 64, "Queue size for the ATS Hook executor. If the number of outstanding submissions \n" + "to the ATS executor exceed this amount, the Hive ATS Hook will not try to log queries to ATS."), EXECPARALLEL("hive.exec.parallel", false, "Whether to execute jobs in parallel"), EXECPARALLETHREADNUMBER("hive.exec.parallel.thread.number", 8, "How many jobs at most can be executed in parallel"), HIVESPECULATIVEEXECREDUCERS("hive.mapred.reduce.tasks.speculative.execution", true, "Whether speculative execution for reducers should be turned on. "), HIVECOUNTERSPULLINTERVAL("hive.exec.counters.pull.interval", 1000L, "The interval with which to poll the JobTracker for the counters the running job. \n" + "The smaller it is the more load there will be on the jobtracker, the higher it is the less granular the caught will be."), DYNAMICPARTITIONING("hive.exec.dynamic.partition", true, "Whether or not to allow dynamic partitions in DML/DDL."), DYNAMICPARTITIONINGMODE("hive.exec.dynamic.partition.mode", "strict", "In strict mode, the user must specify at least one static partition\n" + "in case the user accidentally overwrites all partitions.\n" + "In nonstrict mode all partitions are allowed to be dynamic."), DYNAMICPARTITIONMAXPARTS("hive.exec.max.dynamic.partitions", 1000, "Maximum number of dynamic partitions allowed to be created in total."), DYNAMICPARTITIONMAXPARTSPERNODE("hive.exec.max.dynamic.partitions.pernode", 100, "Maximum number of dynamic partitions allowed to be created in each mapper/reducer node."), MAXCREATEDFILES("hive.exec.max.created.files", 100000L, "Maximum number of HDFS files created by all mappers/reducers in a MapReduce job."), DEFAULTPARTITIONNAME("hive.exec.default.partition.name", "__HIVE_DEFAULT_PARTITION__", "The default partition name in case the dynamic partition column value is null/empty string or any other values that cannot be escaped. \n" + "This value must not contain any special character used in HDFS URI (e.g., ':', '%', '/' etc). \n" + "The user has to be aware that the dynamic partition value should not contain this value to avoid confusions."), DEFAULT_ZOOKEEPER_PARTITION_NAME("hive.lockmgr.zookeeper.default.partition.name", "__HIVE_DEFAULT_ZOOKEEPER_PARTITION__", ""), // Whether to show a link to the most failed task + debugging tips SHOW_JOB_FAIL_DEBUG_INFO("hive.exec.show.job.failure.debug.info", true, "If a job fails, whether to provide a link in the CLI to the task with the\n" + "most failures, along with debugging hints if applicable."), JOB_DEBUG_CAPTURE_STACKTRACES("hive.exec.job.debug.capture.stacktraces", true, "Whether or not stack traces parsed from the task logs of a sampled failed task \n" + "for each failed job should be stored in the SessionState"), JOB_DEBUG_TIMEOUT("hive.exec.job.debug.timeout", 30000, ""), TASKLOG_DEBUG_TIMEOUT("hive.exec.tasklog.debug.timeout", 20000, ""), OUTPUT_FILE_EXTENSION("hive.output.file.extension", null, "String used as a file extension for output files. \n" + "If not set, defaults to the codec extension for text files (e.g. \".gz\"), or no extension otherwise."), HIVE_IN_TEST("hive.in.test", false, "internal usage only, true in test mode", true), HIVE_IN_TEST_SSL("hive.in.ssl.test", false, "internal usage only, true in SSL test mode", true), // TODO: this needs to be removed; see TestReplicationScenarios* comments. HIVE_IN_TEST_REPL("hive.in.repl.test", false, "internal usage only, true in replication test mode", true), HIVE_IN_TEST_IDE("hive.in.ide.test", false, "internal usage only, true if test running in ide", true), HIVE_TESTING_SHORT_LOGS("hive.testing.short.logs", false, "internal usage only, used only in test mode. If set true, when requesting the " + "operation logs the short version (generated by LogDivertAppenderForTest) will be " + "returned"), HIVE_TESTING_REMOVE_LOGS("hive.testing.remove.logs", true, "internal usage only, used only in test mode. If set false, the operation logs, and the " + "operation log directory will not be removed, so they can be found after the test runs."), HIVE_IN_TEZ_TEST("hive.in.tez.test", false, "internal use only, true when in testing tez", true), HIVE_MAPJOIN_TESTING_NO_HASH_TABLE_LOAD("hive.mapjoin.testing.no.hash.table.load", false, "internal use only, true when in testing map join", true), LOCALMODEAUTO("hive.exec.mode.local.auto", false, "Let Hive determine whether to run in local mode automatically"), LOCALMODEMAXBYTES("hive.exec.mode.local.auto.inputbytes.max", 134217728L, "When hive.exec.mode.local.auto is true, input bytes should less than this for local mode."), LOCALMODEMAXINPUTFILES("hive.exec.mode.local.auto.input.files.max", 4, "When hive.exec.mode.local.auto is true, the number of tasks should less than this for local mode."), DROPIGNORESNONEXISTENT("hive.exec.drop.ignorenonexistent", true, "Do not report an error if DROP TABLE/VIEW/Index/Function specifies a non-existent table/view/function"), HIVEIGNOREMAPJOINHINT("hive.ignore.mapjoin.hint", true, "Ignore the mapjoin hint"), HIVE_FILE_MAX_FOOTER("hive.file.max.footer", 100, "maximum number of lines for footer user can define for a table file"), HIVE_RESULTSET_USE_UNIQUE_COLUMN_NAMES("hive.resultset.use.unique.column.names", true, "Make column names unique in the result set by qualifying column names with table alias if needed.\n" + "Table alias will be added to column names for queries of type \"select *\" or \n" + "if query explicitly uses table alias \"select r1.x..\"."), // Hadoop Configuration Properties // Properties with null values are ignored and exist only for the purpose of giving us // a symbolic name to reference in the Hive source code. Properties with non-null // values will override any values set in the underlying Hadoop configuration. HADOOPBIN("hadoop.bin.path", findHadoopBinary(), "", true), YARNBIN("yarn.bin.path", findYarnBinary(), "", true), MAPREDBIN("mapred.bin.path", findMapRedBinary(), "", true), HIVE_FS_HAR_IMPL("fs.har.impl", "org.apache.hadoop.hive.shims.HiveHarFileSystem", "The implementation for accessing Hadoop Archives. Note that this won't be applicable to Hadoop versions less than 0.20"), MAPREDMAXSPLITSIZE(FileInputFormat.SPLIT_MAXSIZE, 256000000L, "", true), MAPREDMINSPLITSIZE(FileInputFormat.SPLIT_MINSIZE, 1L, "", true), MAPREDMINSPLITSIZEPERNODE(CombineFileInputFormat.SPLIT_MINSIZE_PERNODE, 1L, "", true), MAPREDMINSPLITSIZEPERRACK(CombineFileInputFormat.SPLIT_MINSIZE_PERRACK, 1L, "", true), // The number of reduce tasks per job. Hadoop sets this value to 1 by default // By setting this property to -1, Hive will automatically determine the correct // number of reducers. HADOOPNUMREDUCERS("mapreduce.job.reduces", -1, "", true), METASTOREDBTYPE("hive.metastore.db.type", "DERBY", new StringSet("DERBY", "ORACLE", "MYSQL", "MSSQL", "POSTGRES"), "Type of database used by the metastore. Information schema & JDBCStorageHandler depend on it."), /** * @deprecated Use MetastoreConf.WAREHOUSE */ @Deprecated METASTOREWAREHOUSE("hive.metastore.warehouse.dir", "/user/hive/warehouse", "location of default database for the warehouse"), /** * @deprecated Use MetastoreConf.THRIFT_URIS */ @Deprecated METASTOREURIS("hive.metastore.uris", "", "Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore."), /** * @deprecated Use MetastoreConf.THRIFT_URI_SELECTION */ @Deprecated METASTORESELECTION("hive.metastore.uri.selection", "RANDOM", new StringSet("SEQUENTIAL", "RANDOM"), "Determines the selection mechanism used by metastore client to connect to remote " + "metastore. SEQUENTIAL implies that the first valid metastore from the URIs specified " + "as part of hive.metastore.uris will be picked. RANDOM implies that the metastore " + "will be picked randomly"), /** * @deprecated Use MetastoreConf.CAPABILITY_CHECK */ @Deprecated METASTORE_CAPABILITY_CHECK("hive.metastore.client.capability.check", true, "Whether to check client capabilities for potentially breaking API usage."), METASTORE_CLIENT_CACHE_ENABLED("hive.metastore.client.cache.enabled", false, "Whether to enable metastore client cache"), METASTORE_CLIENT_CACHE_EXPIRY_TIME("hive.metastore.client.cache.expiry.time", "120s", new TimeValidator(TimeUnit.SECONDS), "Expiry time for metastore client cache"), METASTORE_CLIENT_CACHE_INITIAL_CAPACITY("hive.metastore.client.cache.initial.capacity", 50, "Initial capacity for metastore client cache"), METASTORE_CLIENT_CACHE_MAX_CAPACITY("hive.metastore.client.cache.max.capacity", 50, "Max capacity for metastore client cache"), METASTORE_CLIENT_CACHE_STATS_ENABLED("hive.metastore.client.cache.stats.enabled", false, "Whether to enable metastore client cache stats"), METASTORE_FASTPATH("hive.metastore.fastpath", false, "Used to avoid all of the proxies and object copies in the metastore. Note, if this is " + "set, you MUST use a local metastore (hive.metastore.uris must be empty) otherwise " + "undefined and most likely undesired behavior will result"), /** * @deprecated Use MetastoreConf.FS_HANDLER_THREADS_COUNT */ @Deprecated METASTORE_FS_HANDLER_THREADS_COUNT("hive.metastore.fshandler.threads", 15, "Number of threads to be allocated for metastore handler for fs operations."), /** * @deprecated Use MetastoreConf.FILE_METADATA_THREADS */ @Deprecated METASTORE_HBASE_FILE_METADATA_THREADS("hive.metastore.hbase.file.metadata.threads", 1, "Number of threads to use to read file metadata in background to cache it."), /** * @deprecated Use MetastoreConf.URI_RESOLVER */ @Deprecated METASTORE_URI_RESOLVER("hive.metastore.uri.resolver", "", "If set, fully qualified class name of resolver for hive metastore uri's"), /** * @deprecated Use MetastoreConf.THRIFT_CONNECTION_RETRIES */ @Deprecated METASTORETHRIFTCONNECTIONRETRIES("hive.metastore.connect.retries", 3, "Number of retries while opening a connection to metastore"), /** * @deprecated Use MetastoreConf.THRIFT_FAILURE_RETRIES */ @Deprecated METASTORETHRIFTFAILURERETRIES("hive.metastore.failure.retries", 1, "Number of retries upon failure of Thrift metastore calls"), /** * @deprecated Use MetastoreConf.SERVER_PORT */ @Deprecated METASTORE_SERVER_PORT("hive.metastore.port", 9083, "Hive metastore listener port"), /** * @deprecated Use MetastoreConf.CLIENT_CONNECT_RETRY_DELAY */ @Deprecated METASTORE_CLIENT_CONNECT_RETRY_DELAY("hive.metastore.client.connect.retry.delay", "1s", new TimeValidator(TimeUnit.SECONDS), "Number of seconds for the client to wait between consecutive connection attempts"), /** * @deprecated Use MetastoreConf.CLIENT_SOCKET_TIMEOUT */ @Deprecated METASTORE_CLIENT_SOCKET_TIMEOUT("hive.metastore.client.socket.timeout", "600s", new TimeValidator(TimeUnit.SECONDS), "MetaStore Client socket timeout in seconds"), /** * @deprecated Use MetastoreConf.CLIENT_SOCKET_LIFETIME */ @Deprecated METASTORE_CLIENT_SOCKET_LIFETIME("hive.metastore.client.socket.lifetime", "0s", new TimeValidator(TimeUnit.SECONDS), "MetaStore Client socket lifetime in seconds. After this time is exceeded, client\n" + "reconnects on the next MetaStore operation. A value of 0s means the connection\n" + "has an infinite lifetime."), /** * @deprecated Use MetastoreConf.PWD */ @Deprecated METASTOREPWD("javax.jdo.option.ConnectionPassword", "mine", "password to use against metastore database"), /** * @deprecated Use MetastoreConf.CONNECT_URL_HOOK */ @Deprecated METASTORECONNECTURLHOOK("hive.metastore.ds.connection.url.hook", "", "Name of the hook to use for retrieving the JDO connection URL. If empty, the value in javax.jdo.option.ConnectionURL is used"), /** * @deprecated Use MetastoreConf.MULTITHREADED */ @Deprecated METASTOREMULTITHREADED("javax.jdo.option.Multithreaded", true, "Set this to true if multiple threads access metastore through JDO concurrently."), /** * @deprecated Use MetastoreConf.CONNECT_URL_KEY */ @Deprecated METASTORECONNECTURLKEY("javax.jdo.option.ConnectionURL", "jdbc:derby:;databaseName=metastore_db;create=true", "JDBC connect string for a JDBC metastore.\n" + "To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.\n" + "For example, jdbc:postgresql://myhost/db?ssl=true for postgres database."), /** * @deprecated Use MetastoreConf.DBACCESS_SSL_PROPS */ @Deprecated METASTORE_DBACCESS_SSL_PROPS("hive.metastore.dbaccess.ssl.properties", "", "Comma-separated SSL properties for metastore to access database when JDO connection URL\n" + "enables SSL access. e.g. javax.net.ssl.trustStore=/tmp/truststore,javax.net.ssl.trustStorePassword=pwd."), /** * @deprecated Use MetastoreConf.HMS_HANDLER_ATTEMPTS */ @Deprecated HMSHANDLERATTEMPTS("hive.hmshandler.retry.attempts", 10, "The number of times to retry a HMSHandler call if there were a connection error."), /** * @deprecated Use MetastoreConf.HMS_HANDLER_INTERVAL */ @Deprecated HMSHANDLERINTERVAL("hive.hmshandler.retry.interval", "2000ms", new TimeValidator(TimeUnit.MILLISECONDS), "The time between HMSHandler retry attempts on failure."), /** * @deprecated Use MetastoreConf.HMS_HANDLER_FORCE_RELOAD_CONF */ @Deprecated HMSHANDLERFORCERELOADCONF("hive.hmshandler.force.reload.conf", false, "Whether to force reloading of the HMSHandler configuration (including\n" + "the connection URL, before the next metastore query that accesses the\n" + "datastore. Once reloaded, this value is reset to false. Used for\n" + "testing only."), /** * @deprecated Use MetastoreConf.SERVER_MAX_MESSAGE_SIZE */ @Deprecated METASTORESERVERMAXMESSAGESIZE("hive.metastore.server.max.message.size", 100*1024*1024L, "Maximum message size in bytes a HMS will accept."), /** * @deprecated Use MetastoreConf.SERVER_MIN_THREADS */ @Deprecated METASTORESERVERMINTHREADS("hive.metastore.server.min.threads", 200, "Minimum number of worker threads in the Thrift server's pool."), /** * @deprecated Use MetastoreConf.SERVER_MAX_THREADS */ @Deprecated METASTORESERVERMAXTHREADS("hive.metastore.server.max.threads", 1000, "Maximum number of worker threads in the Thrift server's pool."), /** * @deprecated Use MetastoreConf.TCP_KEEP_ALIVE */ @Deprecated METASTORE_TCP_KEEP_ALIVE("hive.metastore.server.tcp.keepalive", true, "Whether to enable TCP keepalive for the metastore server. Keepalive will prevent accumulation of half-open connections."), /** * @deprecated Use MetastoreConf.WM_DEFAULT_POOL_SIZE */ @Deprecated METASTORE_WM_DEFAULT_POOL_SIZE("hive.metastore.wm.default.pool.size", 4, "The size of a default pool to create when creating an empty resource plan;\n" + "If not positive, no default pool will be created."), METASTORE_INT_ORIGINAL("hive.metastore.archive.intermediate.original", "_INTERMEDIATE_ORIGINAL", "Intermediate dir suffixes used for archiving. Not important what they\n" + "are, as long as collisions are avoided"), METASTORE_INT_ARCHIVED("hive.metastore.archive.intermediate.archived", "_INTERMEDIATE_ARCHIVED", ""), METASTORE_INT_EXTRACTED("hive.metastore.archive.intermediate.extracted", "_INTERMEDIATE_EXTRACTED", ""), /** * @deprecated Use MetastoreConf.KERBEROS_KEYTAB_FILE */ @Deprecated METASTORE_KERBEROS_KEYTAB_FILE("hive.metastore.kerberos.keytab.file", "", "The path to the Kerberos Keytab file containing the metastore Thrift server's service principal."), /** * @deprecated Use MetastoreConf.KERBEROS_PRINCIPAL */ @Deprecated METASTORE_KERBEROS_PRINCIPAL("hive.metastore.kerberos.principal", "hive-metastore/[email protected]", "The service principal for the metastore Thrift server. \n" + "The special string _HOST will be replaced automatically with the correct host name."), /** * @deprecated Use MetastoreConf.CLIENT_KERBEROS_PRINCIPAL */ @Deprecated METASTORE_CLIENT_KERBEROS_PRINCIPAL("hive.metastore.client.kerberos.principal", "", // E.g. "hive-metastore/[email protected]". "The Kerberos principal associated with the HA cluster of hcat_servers."), /** * @deprecated Use MetastoreConf.USE_THRIFT_SASL */ @Deprecated METASTORE_USE_THRIFT_SASL("hive.metastore.sasl.enabled", false, "If true, the metastore Thrift interface will be secured with SASL. Clients must authenticate with Kerberos."), /** * @deprecated Use MetastoreConf.USE_THRIFT_FRAMED_TRANSPORT */ @Deprecated METASTORE_USE_THRIFT_FRAMED_TRANSPORT("hive.metastore.thrift.framed.transport.enabled", false, "If true, the metastore Thrift interface will use TFramedTransport. When false (default) a standard TTransport is used."), /** * @deprecated Use MetastoreConf.USE_THRIFT_COMPACT_PROTOCOL */ @Deprecated METASTORE_USE_THRIFT_COMPACT_PROTOCOL("hive.metastore.thrift.compact.protocol.enabled", false, "If true, the metastore Thrift interface will use TCompactProtocol. When false (default) TBinaryProtocol will be used.\n" + "Setting it to true will break compatibility with older clients running TBinaryProtocol."), /** * @deprecated Use MetastoreConf.TOKEN_SIGNATURE */ @Deprecated METASTORE_TOKEN_SIGNATURE("hive.metastore.token.signature", "", "The delegation token service name to match when selecting a token from the current user's tokens."), /** * @deprecated Use MetastoreConf.DELEGATION_TOKEN_STORE_CLS */ @Deprecated METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_CLS("hive.cluster.delegation.token.store.class", "org.apache.hadoop.hive.thrift.MemoryTokenStore", "The delegation token store implementation. Set to org.apache.hadoop.hive.thrift.ZooKeeperTokenStore for load-balanced cluster."), METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_CONNECTSTR( "hive.cluster.delegation.token.store.zookeeper.connectString", "", "The ZooKeeper token store connect string. You can re-use the configuration value\n" + "set in hive.zookeeper.quorum, by leaving this parameter unset."), METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_ZNODE( "hive.cluster.delegation.token.store.zookeeper.znode", "/hivedelegation", "The root path for token store data. Note that this is used by both HiveServer2 and\n" + "MetaStore to store delegation Token. One directory gets created for each of them.\n" + "The final directory names would have the servername appended to it (HIVESERVER2,\n" + "METASTORE)."), METASTORE_CLUSTER_DELEGATION_TOKEN_STORE_ZK_ACL( "hive.cluster.delegation.token.store.zookeeper.acl", "", "ACL for token store entries. Comma separated list of ACL entries. For example:\n" + "sasl:hive/[email protected]:cdrwa,sasl:hive/[email protected]:cdrwa\n" + "Defaults to all permissions for the hiveserver2/metastore process user."), /** * @deprecated Use MetastoreConf.CACHE_PINOBJTYPES */ @Deprecated METASTORE_CACHE_PINOBJTYPES("hive.metastore.cache.pinobjtypes", "Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order", "List of comma separated metastore object types that should be pinned in the cache"), /** * @deprecated Use MetastoreConf.CONNECTION_POOLING_TYPE */ @Deprecated METASTORE_CONNECTION_POOLING_TYPE("datanucleus.connectionPoolingType", "HikariCP", new StringSet("BONECP", "DBCP", "HikariCP", "NONE"), "Specify connection pool library for datanucleus"), /** * @deprecated Use MetastoreConf.CONNECTION_POOLING_MAX_CONNECTIONS */ @Deprecated METASTORE_CONNECTION_POOLING_MAX_CONNECTIONS("datanucleus.connectionPool.maxPoolSize", 10, "Specify the maximum number of connections in the connection pool. Note: The configured size will be used by\n" + "2 connection pools (TxnHandler and ObjectStore). When configuring the max connection pool size, it is\n" + "recommended to take into account the number of metastore instances and the number of HiveServer2 instances\n" + "configured with embedded metastore. To get optimal performance, set config to meet the following condition\n"+ "(2 * pool_size * metastore_instances + 2 * pool_size * HS2_instances_with_embedded_metastore) = \n" + "(2 * physical_core_count + hard_disk_count)."), // Workaround for DN bug on Postgres: // http://www.datanucleus.org/servlet/forum/viewthread_thread,7985_offset /** * @deprecated Use MetastoreConf.DATANUCLEUS_INIT_COL_INFO */ @Deprecated METASTORE_DATANUCLEUS_INIT_COL_INFO("datanucleus.rdbms.initializeColumnInfo", "NONE", "initializeColumnInfo setting for DataNucleus; set to NONE at least on Postgres."), /** * @deprecated Use MetastoreConf.VALIDATE_TABLES */ @Deprecated METASTORE_VALIDATE_TABLES("datanucleus.schema.validateTables", false, "validates existing schema against code. turn this on if you want to verify existing schema"), /** * @deprecated Use MetastoreConf.VALIDATE_COLUMNS */ @Deprecated METASTORE_VALIDATE_COLUMNS("datanucleus.schema.validateColumns", false, "validates existing schema against code. turn this on if you want to verify existing schema"), /** * @deprecated Use MetastoreConf.VALIDATE_CONSTRAINTS */ @Deprecated METASTORE_VALIDATE_CONSTRAINTS("datanucleus.schema.validateConstraints", false, "validates existing schema against code. turn this on if you want to verify existing schema"), /** * @deprecated Use MetastoreConf.STORE_MANAGER_TYPE */ @Deprecated METASTORE_STORE_MANAGER_TYPE("datanucleus.storeManagerType", "rdbms", "metadata store type"), @Deprecated METASTORE_AUTO_CREATE_SCHEMA("datanucleus.schema.autoCreateSchema", false, "Datanucleus autoCreateSchema"), @Deprecated METASTORE_AUTO_CREATE_TABLES("datanucleus.schema.autoCreateTables", false, "Datanucleus autoCreateTables"), @Deprecated METASTORE_AUTO_CREATE_COLUMNS("datanucleus.schema.autoCreateColumns", false, "Datanucleus autoCreateColumns"), @Deprecated METASTORE_MYSQL_ENGINE("datanucleus.rdbms.mysql.engineType","ndbcluster", "MySQL engine to use"), METASTORE_SCHEMA_VERIFICATION("hive.metastore.schema.verification", true, "Enforce metastore schema version consistency.\n" + "True: Verify that version information stored in is compatible with one from Hive jars. Also disable automatic\n" + " schema migration attempt. Users are required to manually migrate schema after Hive upgrade which ensures\n" + " proper metastore schema migration. (Default)\n" + "False: Warn if the version information stored in metastore doesn't match with one from in Hive jars."), /** * @deprecated Use MetastoreConf.SCHEMA_VERIFICATION_RECORD_VERSION */ @Deprecated METASTORE_SCHEMA_VERIFICATION_RECORD_VERSION("hive.metastore.schema.verification.record.version", false, "When true the current MS version is recorded in the VERSION table. If this is disabled and verification is\n" + " enabled the MS will be unusable."), /** * @deprecated Use MetastoreConf.SCHEMA_INFO_CLASS */ @Deprecated METASTORE_SCHEMA_INFO_CLASS("hive.metastore.schema.info.class", "org.apache.hadoop.hive.metastore.MetaStoreSchemaInfo", "Fully qualified class name for the metastore schema information class \n" + "which is used by schematool to fetch the schema information.\n" + " This class should implement the IMetaStoreSchemaInfo interface"), /** * @deprecated Use MetastoreConf.DATANUCLEUS_TRANSACTION_ISOLATION */ @Deprecated METASTORE_TRANSACTION_ISOLATION("datanucleus.transactionIsolation", "read-committed", "Default transaction isolation level for identity generation."), /** * @deprecated Use MetastoreConf.DATANUCLEUS_CACHE_LEVEL2 */ @Deprecated METASTORE_CACHE_LEVEL2("datanucleus.cache.level2", false, "Use a level 2 cache. Turn this off if metadata is changed independently of Hive metastore server"), METASTORE_CACHE_LEVEL2_TYPE("datanucleus.cache.level2.type", "none", ""), /** * @deprecated Use MetastoreConf.IDENTIFIER_FACTORY */ @Deprecated METASTORE_IDENTIFIER_FACTORY("datanucleus.identifierFactory", "datanucleus1", "Name of the identifier factory to use when generating table/column names etc. \n" + "'datanucleus1' is used for backward compatibility with DataNucleus v1"), /** * @deprecated Use MetastoreConf.DATANUCLEUS_USE_LEGACY_VALUE_STRATEGY */ @Deprecated METASTORE_USE_LEGACY_VALUE_STRATEGY("datanucleus.rdbms.useLegacyNativeValueStrategy", true, ""), /** * @deprecated Use MetastoreConf.DATANUCLEUS_PLUGIN_REGISTRY_BUNDLE_CHECK */ @Deprecated METASTORE_PLUGIN_REGISTRY_BUNDLE_CHECK("datanucleus.plugin.pluginRegistryBundleCheck", "LOG", "Defines what happens when plugin bundles are found and are duplicated [EXCEPTION|LOG|NONE]"), /** * @deprecated Use MetastoreConf.BATCH_RETRIEVE_MAX */ @Deprecated METASTORE_BATCH_RETRIEVE_MAX("hive.metastore.batch.retrieve.max", 300, "Maximum number of objects (tables/partitions) can be retrieved from metastore in one batch. \n" + "The higher the number, the less the number of round trips is needed to the Hive metastore server, \n" + "but it may also cause higher memory requirement at the client side."), /** * @deprecated Use MetastoreConf.BATCH_RETRIEVE_OBJECTS_MAX */ @Deprecated METASTORE_BATCH_RETRIEVE_OBJECTS_MAX( "hive.metastore.batch.retrieve.table.partition.max", 1000, "Maximum number of objects that metastore internally retrieves in one batch."), /** * @deprecated Use MetastoreConf.INIT_HOOKS */ @Deprecated METASTORE_INIT_HOOKS("hive.metastore.init.hooks", "", "A comma separated list of hooks to be invoked at the beginning of HMSHandler initialization. \n" + "An init hook is specified as the name of Java class which extends org.apache.hadoop.hive.metastore.MetaStoreInitListener."), /** * @deprecated Use MetastoreConf.PRE_EVENT_LISTENERS */ @Deprecated METASTORE_PRE_EVENT_LISTENERS("hive.metastore.pre.event.listeners", "", "List of comma separated listeners for metastore events."), /** * @deprecated Use MetastoreConf.EVENT_LISTENERS */ @Deprecated METASTORE_EVENT_LISTENERS("hive.metastore.event.listeners", "", "A comma separated list of Java classes that implement the org.apache.hadoop.hive.metastore.MetaStoreEventListener" + " interface. The metastore event and corresponding listener method will be invoked in separate JDO transactions. " + "Alternatively, configure hive.metastore.transactional.event.listeners to ensure both are invoked in same JDO transaction."), /** * @deprecated Use MetastoreConf.TRANSACTIONAL_EVENT_LISTENERS */ @Deprecated METASTORE_TRANSACTIONAL_EVENT_LISTENERS("hive.metastore.transactional.event.listeners", "", "A comma separated list of Java classes that implement the org.apache.hadoop.hive.metastore.MetaStoreEventListener" + " interface. Both the metastore event and corresponding listener method will be invoked in the same JDO transaction."), /** * @deprecated Use MetastoreConf.NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES */ @Deprecated NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES("hive.notification.sequence.lock.max.retries", 5, "Number of retries required to acquire a lock when getting the next notification sequential ID for entries " + "in the NOTIFICATION_LOG table."), /** * @deprecated Use MetastoreConf.NOTIFICATION_SEQUENCE_LOCK_RETRY_SLEEP_INTERVAL */ @Deprecated NOTIFICATION_SEQUENCE_LOCK_RETRY_SLEEP_INTERVAL("hive.notification.sequence.lock.retry.sleep.interval", 500L, new TimeValidator(TimeUnit.MILLISECONDS), "Sleep interval between retries to acquire a notification lock as described part of property " + NOTIFICATION_SEQUENCE_LOCK_MAX_RETRIES.name()), /** * @deprecated Use MetastoreConf.EVENT_DB_LISTENER_TTL */ @Deprecated METASTORE_EVENT_DB_LISTENER_TTL("hive.metastore.event.db.listener.timetolive", "86400s", new TimeValidator(TimeUnit.SECONDS), "time after which events will be removed from the database listener queue"), /** * @deprecated Use MetastoreConf.EVENT_DB_NOTIFICATION_API_AUTH */ @Deprecated METASTORE_EVENT_DB_NOTIFICATION_API_AUTH("hive.metastore.event.db.notification.api.auth", true, "Should metastore do authorization against database notification related APIs such as get_next_notification.\n" + "If set to true, then only the superusers in proxy settings have the permission"), /** * @deprecated Use MetastoreConf.AUTHORIZATION_STORAGE_AUTH_CHECKS */ @Deprecated METASTORE_AUTHORIZATION_STORAGE_AUTH_CHECKS("hive.metastore.authorization.storage.checks", false, "Should the metastore do authorization checks against the underlying storage (usually hdfs) \n" + "for operations like drop-partition (disallow the drop-partition if the user in\n" + "question doesn't have permissions to delete the corresponding directory\n" + "on the storage)."), METASTORE_AUTHORIZATION_EXTERNALTABLE_DROP_CHECK("hive.metastore.authorization.storage.check.externaltable.drop", true, "Should StorageBasedAuthorization check permission of the storage before dropping external table.\n" + "StorageBasedAuthorization already does this check for managed table. For external table however,\n" + "anyone who has read permission of the directory could drop external table, which is surprising.\n" + "The flag is set to false by default to maintain backward compatibility."), /** * @deprecated Use MetastoreConf.EVENT_CLEAN_FREQ */ @Deprecated METASTORE_EVENT_CLEAN_FREQ("hive.metastore.event.clean.freq", "0s", new TimeValidator(TimeUnit.SECONDS), "Frequency at which timer task runs to purge expired events in metastore."), /** * @deprecated Use MetastoreConf.EVENT_EXPIRY_DURATION */ @Deprecated METASTORE_EVENT_EXPIRY_DURATION("hive.metastore.event.expiry.duration", "0s", new TimeValidator(TimeUnit.SECONDS), "Duration after which events expire from events table"), /** * @deprecated Use MetastoreConf.EVENT_MESSAGE_FACTORY */ @Deprecated METASTORE_EVENT_MESSAGE_FACTORY("hive.metastore.event.message.factory", "org.apache.hadoop.hive.metastore.messaging.json.JSONMessageFactory", "Factory class for making encoding and decoding messages in the events generated."), /** * @deprecated Use MetastoreConf.EXECUTE_SET_UGI */ @Deprecated METASTORE_EXECUTE_SET_UGI("hive.metastore.execute.setugi", true, "In unsecure mode, setting this property to true will cause the metastore to execute DFS operations using \n" + "the client's reported user and group permissions. Note that this property must be set on \n" + "both the client and server sides. Further note that its best effort. \n" + "If client sets its to true and server sets it to false, client setting will be ignored."), /** * @deprecated Use MetastoreConf.PARTITION_NAME_WHITELIST_PATTERN */ @Deprecated METASTORE_PARTITION_NAME_WHITELIST_PATTERN("hive.metastore.partition.name.whitelist.pattern", "", "Partition names will be checked against this regex pattern and rejected if not matched."), /** * @deprecated Use MetastoreConf.INTEGER_JDO_PUSHDOWN */ @Deprecated METASTORE_INTEGER_JDO_PUSHDOWN("hive.metastore.integral.jdo.pushdown", false, "Allow JDO query pushdown for integral partition columns in metastore. Off by default. This\n" + "improves metastore perf for integral columns, especially if there's a large number of partitions.\n" + "However, it doesn't work correctly with integral values that are not normalized (e.g. have\n" + "leading zeroes, like 0012). If metastore direct SQL is enabled and works, this optimization\n" + "is also irrelevant."), /** * @deprecated Use MetastoreConf.TRY_DIRECT_SQL */ @Deprecated METASTORE_TRY_DIRECT_SQL("hive.metastore.try.direct.sql", true, "Whether the Hive metastore should try to use direct SQL queries instead of the\n" + "DataNucleus for certain read paths. This can improve metastore performance when\n" + "fetching many partitions or column statistics by orders of magnitude; however, it\n" + "is not guaranteed to work on all RDBMS-es and all versions. In case of SQL failures,\n" + "the metastore will fall back to the DataNucleus, so it's safe even if SQL doesn't\n" + "work for all queries on your datastore. If all SQL queries fail (for example, your\n" + "metastore is backed by MongoDB), you might want to disable this to save the\n" + "try-and-fall-back cost."), /** * @deprecated Use MetastoreConf.DIRECT_SQL_PARTITION_BATCH_SIZE */ @Deprecated METASTORE_DIRECT_SQL_PARTITION_BATCH_SIZE("hive.metastore.direct.sql.batch.size", 0, "Batch size for partition and other object retrieval from the underlying DB in direct\n" + "SQL. For some DBs like Oracle and MSSQL, there are hardcoded or perf-based limitations\n" + "that necessitate this. For DBs that can handle the queries, this isn't necessary and\n" + "may impede performance. -1 means no batching, 0 means automatic batching."), /** * @deprecated Use MetastoreConf.TRY_DIRECT_SQL_DDL */ @Deprecated METASTORE_TRY_DIRECT_SQL_DDL("hive.metastore.try.direct.sql.ddl", true, "Same as hive.metastore.try.direct.sql, for read statements within a transaction that\n" + "modifies metastore data. Due to non-standard behavior in Postgres, if a direct SQL\n" + "select query has incorrect syntax or something similar inside a transaction, the\n" + "entire transaction will fail and fall-back to DataNucleus will not be possible. You\n" + "should disable the usage of direct SQL inside transactions if that happens in your case."), /** * @deprecated Use MetastoreConf.DIRECT_SQL_MAX_QUERY_LENGTH */ @Deprecated METASTORE_DIRECT_SQL_MAX_QUERY_LENGTH("hive.direct.sql.max.query.length", 100, "The maximum\n" + " size of a query string (in KB)."), /** * @deprecated Use MetastoreConf.DIRECT_SQL_MAX_ELEMENTS_IN_CLAUSE */ @Deprecated METASTORE_DIRECT_SQL_MAX_ELEMENTS_IN_CLAUSE("hive.direct.sql.max.elements.in.clause", 1000, "The maximum number of values in a IN clause. Once exceeded, it will be broken into\n" + " multiple OR separated IN clauses."), /** * @deprecated Use MetastoreConf.DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE */ @Deprecated METASTORE_DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE("hive.direct.sql.max.elements.values.clause", 1000, "The maximum number of values in a VALUES clause for INSERT statement."), /** * @deprecated Use MetastoreConf.ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS */ @Deprecated METASTORE_ORM_RETRIEVE_MAPNULLS_AS_EMPTY_STRINGS("hive.metastore.orm.retrieveMapNullsAsEmptyStrings",false, "Thrift does not support nulls in maps, so any nulls present in maps retrieved from ORM must " + "either be pruned or converted to empty strings. Some backing dbs such as Oracle persist empty strings " + "as nulls, so we should set this parameter if we wish to reverse that behaviour. For others, " + "pruning is the correct behaviour"), /** * @deprecated Use MetastoreConf.DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES */ @Deprecated METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES( "hive.metastore.disallow.incompatible.col.type.changes", true, "If true (default is false), ALTER TABLE operations which change the type of a\n" + "column (say STRING) to an incompatible type (say MAP) are disallowed.\n" + "RCFile default SerDe (ColumnarSerDe) serializes the values in such a way that the\n" + "datatypes can be converted from string to any type. The map is also serialized as\n" + "a string, which can be read as a string as well. However, with any binary\n" + "serialization, this is not true. Blocking the ALTER TABLE prevents ClassCastExceptions\n" + "when subsequently trying to access old partitions.\n" + "\n" + "Primitive types like INT, STRING, BIGINT, etc., are compatible with each other and are\n" + "not blocked.\n" + "\n" + "See HIVE-4409 for more details."), /** * @deprecated Use MetastoreConf.LIMIT_PARTITION_REQUEST */ @Deprecated METASTORE_LIMIT_PARTITION_REQUEST("hive.metastore.limit.partition.request", -1, "This limits the number of partitions that can be requested from the metastore for a given table.\n" + "The default value \"-1\" means no limit."), NEWTABLEDEFAULTPARA("hive.table.parameters.default", "", "Default property values for newly created tables"), DDL_CTL_PARAMETERS_WHITELIST("hive.ddl.createtablelike.properties.whitelist", "", "Table Properties to copy over when executing a Create Table Like."), /** * @deprecated Use MetastoreConf.RAW_STORE_IMPL */ @Deprecated METASTORE_RAW_STORE_IMPL("hive.metastore.rawstore.impl", "org.apache.hadoop.hive.metastore.ObjectStore", "Name of the class that implements org.apache.hadoop.hive.metastore.rawstore interface. \n" + "This class is used to store and retrieval of raw metadata objects such as table, database"), /** * @deprecated Use MetastoreConf.TXN_STORE_IMPL */ @Deprecated METASTORE_TXN_STORE_IMPL("hive.metastore.txn.store.impl", "org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler", "Name of class that implements org.apache.hadoop.hive.metastore.txn.TxnStore. This " + "class is used to store and retrieve transactions and locks"), /** * @deprecated Use MetastoreConf.CONNECTION_DRIVER */ @Deprecated METASTORE_CONNECTION_DRIVER("javax.jdo.option.ConnectionDriverName", "org.apache.derby.jdbc.EmbeddedDriver", "Driver class name for a JDBC metastore"), /** * @deprecated Use MetastoreConf.MANAGER_FACTORY_CLASS */ @Deprecated METASTORE_MANAGER_FACTORY_CLASS("javax.jdo.PersistenceManagerFactoryClass", "org.datanucleus.api.jdo.JDOPersistenceManagerFactory", "class implementing the jdo persistence"), /** * @deprecated Use MetastoreConf.EXPRESSION_PROXY_CLASS */ @Deprecated METASTORE_EXPRESSION_PROXY_CLASS("hive.metastore.expression.proxy", "org.apache.hadoop.hive.ql.optimizer.ppr.PartitionExpressionForMetastore", ""), /** * @deprecated Use MetastoreConf.DETACH_ALL_ON_COMMIT */ @Deprecated METASTORE_DETACH_ALL_ON_COMMIT("javax.jdo.option.DetachAllOnCommit", true, "Detaches all objects from session so that they can be used after transaction is committed"), /** * @deprecated Use MetastoreConf.NON_TRANSACTIONAL_READ */ @Deprecated METASTORE_NON_TRANSACTIONAL_READ("javax.jdo.option.NonTransactionalRead", true, "Reads outside of transactions"), /** * @deprecated Use MetastoreConf.CONNECTION_USER_NAME */ @Deprecated METASTORE_CONNECTION_USER_NAME("javax.jdo.option.ConnectionUserName", "APP", "Username to use against metastore database"), /** * @deprecated Use MetastoreConf.HOPSMETADATACONSISTENCY */ @Deprecated HOPSMETADATACONSISTENCY("hops.metadata.consistent", true, "Whether or not to enforce HopsFS/Hive metadata consistency"), /** * @deprecated Use MetastoreConf.END_FUNCTION_LISTENERS */ @Deprecated METASTORE_END_FUNCTION_LISTENERS("hive.metastore.end.function.listeners", "", "List of comma separated listeners for the end of metastore functions."), /** * @deprecated Use MetastoreConf.PART_INHERIT_TBL_PROPS */ @Deprecated METASTORE_PART_INHERIT_TBL_PROPS("hive.metastore.partition.inherit.table.properties", "", "List of comma separated keys occurring in table properties which will get inherited to newly created partitions. \n" + "* implies all the keys will get inherited."), /** * @deprecated Use MetastoreConf.FILTER_HOOK */ @Deprecated METASTORE_FILTER_HOOK("hive.metastore.filter.hook", "org.apache.hadoop.hive.metastore.DefaultMetaStoreFilterHookImpl", "Metastore hook class for filtering the metadata read results. If hive.security.authorization.manager" + "is set to instance of HiveAuthorizerFactory, then this value is ignored."), FIRE_EVENTS_FOR_DML("hive.metastore.dml.events", false, "If true, the metastore will be asked" + " to fire events for DML operations"), METASTORE_CLIENT_DROP_PARTITIONS_WITH_EXPRESSIONS("hive.metastore.client.drop.partitions.using.expressions", true, "Choose whether dropping partitions with HCatClient pushes the partition-predicate to the metastore, " + "or drops partitions iteratively"), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_ENABLED */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_ENABLED("hive.metastore.aggregate.stats.cache.enabled", true, "Whether aggregate stats caching is enabled or not."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_SIZE */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_SIZE("hive.metastore.aggregate.stats.cache.size", 10000, "Maximum number of aggregate stats nodes that we will place in the metastore aggregate stats cache."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_PARTITIONS */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_MAX_PARTITIONS("hive.metastore.aggregate.stats.cache.max.partitions", 10000, "Maximum number of partitions that are aggregated per cache node."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_FPP */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_FPP("hive.metastore.aggregate.stats.cache.fpp", (float) 0.01, "Maximum false positive probability for the Bloom Filter used in each aggregate stats cache node (default 1%)."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_VARIANCE */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_MAX_VARIANCE("hive.metastore.aggregate.stats.cache.max.variance", (float) 0.01, "Maximum tolerable variance in number of partitions between a cached node and our request (default 1%)."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_TTL */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_TTL("hive.metastore.aggregate.stats.cache.ttl", "600s", new TimeValidator(TimeUnit.SECONDS), "Number of seconds for a cached node to be active in the cache before they become stale."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_MAX_WRITER_WAIT("hive.metastore.aggregate.stats.cache.max.writer.wait", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Number of milliseconds a writer will wait to acquire the writelock before giving up."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_READER_WAIT */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_MAX_READER_WAIT("hive.metastore.aggregate.stats.cache.max.reader.wait", "1000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Number of milliseconds a reader will wait to acquire the readlock before giving up."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_MAX_FULL */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_MAX_FULL("hive.metastore.aggregate.stats.cache.max.full", (float) 0.9, "Maximum cache full % after which the cache cleaner thread kicks in."), /** * @deprecated Use MetastoreConf.AGGREGATE_STATS_CACHE_CLEAN_UNTIL */ @Deprecated METASTORE_AGGREGATE_STATS_CACHE_CLEAN_UNTIL("hive.metastore.aggregate.stats.cache.clean.until", (float) 0.8, "The cleaner thread cleans until cache reaches this % full size."), /** * @deprecated Use MetastoreConf.METRICS_ENABLED */ @Deprecated METASTORE_METRICS("hive.metastore.metrics.enabled", false, "Enable metrics on the metastore."), /** * @deprecated Use MetastoreConf.INIT_METADATA_COUNT_ENABLED */ @Deprecated METASTORE_INIT_METADATA_COUNT_ENABLED("hive.metastore.initial.metadata.count.enabled", true, "Enable a metadata count at metastore startup for metrics."), // SSL settings // Keystore and truststore information are read from the ssl-server.xml file which contains the information // about the machine certificates. // Parameters for exporting metadata on table drop (requires the use of the) // org.apache.hadoop.hive.ql.parse.MetaDataExportListener preevent listener /** * @deprecated Use MetastoreConf.METADATA_EXPORT_LOCATION */ @Deprecated METADATA_EXPORT_LOCATION("hive.metadata.export.location", "", "When used in conjunction with the org.apache.hadoop.hive.ql.parse.MetaDataExportListener pre event listener, \n" + "it is the location to which the metadata will be exported. The default is an empty string, which results in the \n" + "metadata being exported to the current user's home directory on HDFS."), /** * @deprecated Use MetastoreConf.MOVE_EXPORTED_METADATA_TO_TRASH */ @Deprecated MOVE_EXPORTED_METADATA_TO_TRASH("hive.metadata.move.exported.metadata.to.trash", true, "When used in conjunction with the org.apache.hadoop.hive.ql.parse.MetaDataExportListener pre event listener, \n" + "this setting determines if the metadata that is exported will subsequently be moved to the user's trash directory \n" + "alongside the dropped table data. This ensures that the metadata will be cleaned up along with the dropped table data."), // CLI CLIIGNOREERRORS("hive.cli.errors.ignore", false, ""), CLIPRINTCURRENTDB("hive.cli.print.current.db", false, "Whether to include the current database in the Hive prompt."), CLIPROMPT("hive.cli.prompt", "hive", "Command line prompt configuration value. Other hiveconf can be used in this configuration value. \n" + "Variable substitution will only be invoked at the Hive CLI startup."), CLIPRETTYOUTPUTNUMCOLS("hive.cli.pretty.output.num.cols", -1, "The number of columns to use when formatting output generated by the DESCRIBE PRETTY table_name command.\n" + "If the value of this property is -1, then Hive will use the auto-detected terminal width."), /** * @deprecated Use MetastoreConf.FS_HANDLER_CLS */ @Deprecated HIVE_METASTORE_FS_HANDLER_CLS("hive.metastore.fs.handler.class", "org.apache.hadoop.hive.metastore.HiveMetaStoreFsImpl", ""), // Things we log in the jobconf // session identifier HIVESESSIONID("hive.session.id", "", ""), // whether session is running in silent mode or not HIVESESSIONSILENT("hive.session.silent", false, ""), HIVE_LOCAL_TIME_ZONE("hive.local.time.zone", "LOCAL", "Sets the time-zone for displaying and interpreting time stamps. If this property value is set to\n" + "LOCAL, it is not specified, or it is not a correct time-zone, the system default time-zone will be\n " + "used instead. Time-zone IDs can be specified as region-based zone IDs (based on IANA time-zone data),\n" + "abbreviated zone IDs, or offset IDs."), HIVE_SESSION_HISTORY_ENABLED("hive.session.history.enabled", false, "Whether to log Hive query, query plan, runtime statistics etc."), HIVEQUERYSTRING("hive.query.string", "", "Query being executed (might be multiple per a session)"), HIVEQUERYID("hive.query.id", "", "ID for query being executed (might be multiple per a session)"), HIVEJOBNAMELENGTH("hive.jobname.length", 50, "max jobname length"), // hive jar HIVEJAR("hive.jar.path", "", "The location of hive_cli.jar that is used when submitting jobs in a separate jvm."), HIVEAUXJARS("hive.aux.jars.path", "", "The location of the plugin jars that contain implementations of user defined functions and serdes."), // reloadable jars HIVERELOADABLEJARS("hive.reloadable.aux.jars.path", "", "The locations of the plugin jars, which can be a comma-separated folders or jars. Jars can be renewed\n" + "by executing reload command. And these jars can be " + "used as the auxiliary classes like creating a UDF or SerDe."), // hive added files and jars HIVEADDEDFILES("hive.added.files.path", "", "This an internal parameter."), HIVEADDEDJARS("hive.added.jars.path", "", "This an internal parameter."), HIVEADDEDARCHIVES("hive.added.archives.path", "", "This an internal parameter."), HIVEADDFILESUSEHDFSLOCATION("hive.resource.use.hdfs.location", true, "Reference HDFS based files/jars directly instead of " + "copy to session based HDFS scratch directory, to make distributed cache more useful."), HIVE_CURRENT_DATABASE("hive.current.database", "", "Database name used by current session. Internal usage only.", true), // for hive script operator HIVES_AUTO_PROGRESS_TIMEOUT("hive.auto.progress.timeout", "0s", new TimeValidator(TimeUnit.SECONDS), "How long to run autoprogressor for the script/UDTF operators.\n" + "Set to 0 for forever."), HIVESCRIPTAUTOPROGRESS("hive.script.auto.progress", false, "Whether Hive Transform/Map/Reduce Clause should automatically send progress information to TaskTracker \n" + "to avoid the task getting killed because of inactivity. Hive sends progress information when the script is \n" + "outputting to stderr. This option removes the need of periodically producing stderr messages, \n" + "but users should be cautious because this may prevent infinite loops in the scripts to be killed by TaskTracker."), HIVESCRIPTIDENVVAR("hive.script.operator.id.env.var", "HIVE_SCRIPT_OPERATOR_ID", "Name of the environment variable that holds the unique script operator ID in the user's \n" + "transform function (the custom mapper/reducer that the user has specified in the query)"), HIVESCRIPTTRUNCATEENV("hive.script.operator.truncate.env", false, "Truncate each environment variable for external script in scripts operator to 20KB (to fit system limits)"), HIVESCRIPT_ENV_BLACKLIST("hive.script.operator.env.blacklist", "hive.txn.valid.txns,hive.txn.tables.valid.writeids,hive.txn.valid.writeids,hive.script.operator.env.blacklist", "Comma separated list of keys from the configuration file not to convert to environment " + "variables when invoking the script operator"), HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT("hive.strict.checks.orderby.no.limit", false, "Enabling strict large query checks disallows the following:\n" + " Orderby without limit.\n" + "Note that this check currently does not consider data size, only the query pattern."), HIVE_STRICT_CHECKS_NO_PARTITION_FILTER("hive.strict.checks.no.partition.filter", false, "Enabling strict large query checks disallows the following:\n" + " No partition being picked up for a query against partitioned table.\n" + "Note that this check currently does not consider data size, only the query pattern."), HIVE_STRICT_CHECKS_TYPE_SAFETY("hive.strict.checks.type.safety", true, "Enabling strict type safety checks disallows the following:\n" + " Comparing bigints and strings.\n" + " Comparing bigints and doubles."), HIVE_STRICT_CHECKS_CARTESIAN("hive.strict.checks.cartesian.product", false, "Enabling strict Cartesian join checks disallows the following:\n" + " Cartesian product (cross join)."), HIVE_STRICT_CHECKS_BUCKETING("hive.strict.checks.bucketing", true, "Enabling strict bucketing checks disallows the following:\n" + " Load into bucketed tables."), @Deprecated HIVEMAPREDMODE("hive.mapred.mode", null, "Deprecated; use hive.strict.checks.* settings instead."), HIVEALIAS("hive.alias", "", ""), HIVEMAPSIDEAGGREGATE("hive.map.aggr", true, "Whether to use map-side aggregation in Hive Group By queries"), HIVEGROUPBYSKEW("hive.groupby.skewindata", false, "Whether there is skew in data to optimize group by queries"), HIVEJOINEMITINTERVAL("hive.join.emit.interval", 1000, "How many rows in the right-most join operand Hive should buffer before emitting the join result."), HIVEJOINCACHESIZE("hive.join.cache.size", 25000, "How many rows in the joining tables (except the streaming table) should be cached in memory."), HIVE_PUSH_RESIDUAL_INNER("hive.join.inner.residual", false, "Whether to push non-equi filter predicates within inner joins. This can improve efficiency in " + "the evaluation of certain joins, since we will not be emitting rows which are thrown away by " + "a Filter operator straight away. However, currently vectorization does not support them, thus " + "enabling it is only recommended when vectorization is disabled."), // CBO related HIVE_CBO_ENABLED("hive.cbo.enable", true, "Flag to control enabling Cost Based Optimizations using Calcite framework."), HIVE_CBO_CNF_NODES_LIMIT("hive.cbo.cnf.maxnodes", -1, "When converting to conjunctive normal form (CNF), fail if" + "the expression exceeds this threshold; the threshold is expressed in terms of number of nodes (leaves and" + "interior nodes). -1 to not set up a threshold."), HIVE_CBO_RETPATH_HIVEOP("hive.cbo.returnpath.hiveop", false, "Flag to control calcite plan to hive operator conversion"), HIVE_CBO_EXTENDED_COST_MODEL("hive.cbo.costmodel.extended", false, "Flag to control enabling the extended cost model based on" + "CPU, IO and cardinality. Otherwise, the cost model is based on cardinality."), HIVE_CBO_COST_MODEL_CPU("hive.cbo.costmodel.cpu", "0.000001", "Default cost of a comparison"), HIVE_CBO_COST_MODEL_NET("hive.cbo.costmodel.network", "150.0", "Default cost of a transferring a byte over network;" + " expressed as multiple of CPU cost"), HIVE_CBO_COST_MODEL_LFS_WRITE("hive.cbo.costmodel.local.fs.write", "4.0", "Default cost of writing a byte to local FS;" + " expressed as multiple of NETWORK cost"), HIVE_CBO_COST_MODEL_LFS_READ("hive.cbo.costmodel.local.fs.read", "4.0", "Default cost of reading a byte from local FS;" + " expressed as multiple of NETWORK cost"), HIVE_CBO_COST_MODEL_HDFS_WRITE("hive.cbo.costmodel.hdfs.write", "10.0", "Default cost of writing a byte to HDFS;" + " expressed as multiple of Local FS write cost"), HIVE_CBO_COST_MODEL_HDFS_READ("hive.cbo.costmodel.hdfs.read", "1.5", "Default cost of reading a byte from HDFS;" + " expressed as multiple of Local FS read cost"), HIVE_CBO_SHOW_WARNINGS("hive.cbo.show.warnings", true, "Toggle display of CBO warnings like missing column stats"), AGGR_JOIN_TRANSPOSE("hive.transpose.aggr.join", false, "push aggregates through join"), SEMIJOIN_CONVERSION("hive.optimize.semijoin.conversion", true, "convert group by followed by inner equi join into semijoin"), HIVE_COLUMN_ALIGNMENT("hive.order.columnalignment", true, "Flag to control whether we want to try to align" + "columns in operators such as Aggregate or Join so that we try to reduce the number of shuffling stages"), // materialized views HIVE_MATERIALIZED_VIEW_ENABLE_AUTO_REWRITING("hive.materializedview.rewriting", false, "Whether to try to rewrite queries using the materialized views enabled for rewriting"), HIVE_MATERIALIZED_VIEW_REWRITING_SELECTION_STRATEGY("hive.materializedview.rewriting.strategy", "heuristic", new StringSet("heuristic", "costbased"), "The strategy that should be used to cost and select the materialized view rewriting. \n" + " heuristic: Always try to select the plan using the materialized view if rewriting produced one," + "choosing the plan with lower cost among possible plans containing a materialized view\n" + " costbased: Fully cost-based strategy, always use plan with lower cost, independently on whether " + "it uses a materialized view or not"), HIVE_MATERIALIZED_VIEW_REWRITING_TIME_WINDOW("hive.materializedview.rewriting.time.window", "0s", new TimeValidator(TimeUnit.SECONDS), "Time window, specified in seconds, after which outdated materialized views become invalid for automatic query rewriting.\n" + "For instance, if a materialized view is created and afterwards one of its source tables is changed at " + "moment in time t0, the materialized view will not be considered for rewriting anymore after t0 plus " + "the value assigned to this property. Default value 0 means that the materialized view cannot be " + "outdated to be used automatically in query rewriting."), HIVE_MATERIALIZED_VIEW_REWRITING_INCREMENTAL("hive.materializedview.rewriting.incremental", true, "Whether to try to execute incremental rewritings based on outdated materializations and\n" + "current content of tables. Default value of true effectively amounts to enabling incremental\n" + "rebuild for the materializations too."), HIVE_MATERIALIZED_VIEW_REBUILD_INCREMENTAL("hive.materializedview.rebuild.incremental", true, "Whether to try to execute incremental rebuild for the materialized views. Incremental rebuild\n" + "tries to modify the original materialization contents to reflect the latest changes to the\n" + "materialized view source tables, instead of rebuilding the contents fully. Incremental rebuild\n" + "is based on the materialized view algebraic incremental rewriting. Hence, this requires\n" + "hive.materializedview.rewriting.incremental to be true."), HIVE_MATERIALIZED_VIEW_FILE_FORMAT("hive.materializedview.fileformat", "ORC", new StringSet("none", "TextFile", "SequenceFile", "RCfile", "ORC"), "Default file format for CREATE MATERIALIZED VIEW statement"), HIVE_MATERIALIZED_VIEW_SERDE("hive.materializedview.serde", "org.apache.hadoop.hive.ql.io.orc.OrcSerde", "Default SerDe used for materialized views"), HIVE_MATERIALIZATIONS_INVALIDATION_CACHE_IMPL("hive.metastore.materializations.invalidation.impl", "DEFAULT", new StringSet("DEFAULT", "DISABLE"), "The implementation that we should use for the materializations invalidation cache. \n" + " DEFAULT: Default implementation for invalidation cache\n" + " DISABLE: Disable invalidation cache (debugging purposes)"), HIVE_MATERIALIZATIONS_INVALIDATION_CACHE_CLEAN_FREQUENCY("hive.metastore.materializations.invalidation.clean.frequency", "3600s", new TimeValidator(TimeUnit.SECONDS), "Frequency at which timer task runs to remove unnecessary transactions information from" + "materializations invalidation cache."), HIVE_MATERIALIZATIONS_INVALIDATION_CACHE_EXPIRY_DURATION("hive.metastore.materializations.invalidation.max.duration", "86400s", new TimeValidator(TimeUnit.SECONDS), "Maximum duration for query producing a materialization. After this time, transactions" + "information that is not relevant for materializations can be removed from invalidation cache."), // hive.mapjoin.bucket.cache.size has been replaced by hive.smbjoin.cache.row, // need to remove by hive .13. Also, do not change default (see SMB operator) HIVEMAPJOINBUCKETCACHESIZE("hive.mapjoin.bucket.cache.size", 100, ""), HIVEMAPJOINUSEOPTIMIZEDTABLE("hive.mapjoin.optimized.hashtable", true, "Whether Hive should use memory-optimized hash table for MapJoin.\n" + "Only works on Tez and Spark, because memory-optimized hashtable cannot be serialized."), HIVEMAPJOINOPTIMIZEDTABLEPROBEPERCENT("hive.mapjoin.optimized.hashtable.probe.percent", (float) 0.5, "Probing space percentage of the optimized hashtable"), HIVEUSEHYBRIDGRACEHASHJOIN("hive.mapjoin.hybridgrace.hashtable", true, "Whether to use hybrid" + "grace hash join as the join method for mapjoin. Tez only."), HIVEHYBRIDGRACEHASHJOINMEMCHECKFREQ("hive.mapjoin.hybridgrace.memcheckfrequency", 1024, "For " + "hybrid grace hash join, how often (how many rows apart) we check if memory is full. " + "This number should be power of 2."), HIVEHYBRIDGRACEHASHJOINMINWBSIZE("hive.mapjoin.hybridgrace.minwbsize", 524288, "For hybrid grace" + "Hash join, the minimum write buffer size used by optimized hashtable. Default is 512 KB."), HIVEHYBRIDGRACEHASHJOINMINNUMPARTITIONS("hive.mapjoin.hybridgrace.minnumpartitions", 16, "For" + "Hybrid grace hash join, the minimum number of partitions to create."), HIVEHASHTABLEWBSIZE("hive.mapjoin.optimized.hashtable.wbsize", 8 * 1024 * 1024, "Optimized hashtable (see hive.mapjoin.optimized.hashtable) uses a chain of buffers to\n" + "store data. This is one buffer size. HT may be slightly faster if this is larger, but for small\n" + "joins unnecessary memory will be allocated and then trimmed."), HIVEHYBRIDGRACEHASHJOINBLOOMFILTER("hive.mapjoin.hybridgrace.bloomfilter", true, "Whether to " + "use BloomFilter in Hybrid grace hash join to minimize unnecessary spilling."), HIVESMBJOINCACHEROWS("hive.smbjoin.cache.rows", 10000, "How many rows with the same key value should be cached in memory per smb joined table."), HIVEGROUPBYMAPINTERVAL("hive.groupby.mapaggr.checkinterval", 100000, "Number of rows after which size of the grouping keys/aggregation classes is performed"), HIVEMAPAGGRHASHMEMORY("hive.map.aggr.hash.percentmemory", (float) 0.5, "Portion of total memory to be used by map-side group aggregation hash table"), HIVEMAPJOINFOLLOWEDBYMAPAGGRHASHMEMORY("hive.mapjoin.followby.map.aggr.hash.percentmemory", (float) 0.3, "Portion of total memory to be used by map-side group aggregation hash table, when this group by is followed by map join"), HIVEMAPAGGRMEMORYTHRESHOLD("hive.map.aggr.hash.force.flush.memory.threshold", (float) 0.9, "The max memory to be used by map-side group aggregation hash table.\n" + "If the memory usage is higher than this number, force to flush data"), HIVEMAPAGGRHASHMINREDUCTION("hive.map.aggr.hash.min.reduction", (float) 0.5, "Hash aggregation will be turned off if the ratio between hash table size and input rows is bigger than this number. \n" + "Set to 1 to make sure hash aggregation is never turned off."), HIVEMULTIGROUPBYSINGLEREDUCER("hive.multigroupby.singlereducer", true, "Whether to optimize multi group by query to generate single M/R job plan. If the multi group by query has \n" + "common group by keys, it will be optimized to generate single M/R job."), HIVE_MAP_GROUPBY_SORT("hive.map.groupby.sorted", true, "If the bucketing/sorting properties of the table exactly match the grouping key, whether to perform \n" + "the group by in the mapper by using BucketizedHiveInputFormat. The only downside to this\n" + "is that it limits the number of mappers to the number of files."), HIVE_GROUPBY_POSITION_ALIAS("hive.groupby.position.alias", false, "Whether to enable using Column Position Alias in Group By"), HIVE_ORDERBY_POSITION_ALIAS("hive.orderby.position.alias", true, "Whether to enable using Column Position Alias in Order By"), @Deprecated HIVE_GROUPBY_ORDERBY_POSITION_ALIAS("hive.groupby.orderby.position.alias", false, "Whether to enable using Column Position Alias in Group By or Order By (deprecated).\n" + "Use " + HIVE_ORDERBY_POSITION_ALIAS.varname + " or " + HIVE_GROUPBY_POSITION_ALIAS.varname + " instead"), HIVE_NEW_JOB_GROUPING_SET_CARDINALITY("hive.new.job.grouping.set.cardinality", 30, "Whether a new map-reduce job should be launched for grouping sets/rollups/cubes.\n" + "For a query like: select a, b, c, count(1) from T group by a, b, c with rollup;\n" + "4 rows are created per row: (a, b, c), (a, b, null), (a, null, null), (null, null, null).\n" + "This can lead to explosion across map-reduce boundary if the cardinality of T is very high,\n" + "and map-side aggregation does not do a very good job. \n" + "\n" + "This parameter decides if Hive should add an additional map-reduce job. If the grouping set\n" + "cardinality (4 in the example above), is more than this value, a new MR job is added under the\n" + "assumption that the original group by will reduce the data size."), HIVE_GROUPBY_LIMIT_EXTRASTEP("hive.groupby.limit.extrastep", true, "This parameter decides if Hive should \n" + "create new MR job for sorting final output"), // Max file num and size used to do a single copy (after that, distcp is used) HIVE_EXEC_COPYFILE_MAXNUMFILES("hive.exec.copyfile.maxnumfiles", 1L, "Maximum number of files Hive uses to do sequential HDFS copies between directories." + "Distributed copies (distcp) will be used instead for larger numbers of files so that copies can be done faster."), HIVE_EXEC_COPYFILE_MAXSIZE("hive.exec.copyfile.maxsize", 32L * 1024 * 1024 /*32M*/, "Maximum file size (in bytes) that Hive uses to do single HDFS copies between directories." + "Distributed copies (distcp) will be used instead for bigger files so that copies can be done faster."), // for hive udtf operator HIVEUDTFAUTOPROGRESS("hive.udtf.auto.progress", false, "Whether Hive should automatically send progress information to TaskTracker \n" + "when using UDTF's to prevent the task getting killed because of inactivity. Users should be cautious \n" + "because this may prevent TaskTracker from killing tasks with infinite loops."), HIVEDEFAULTFILEFORMAT("hive.default.fileformat", "TextFile", new StringSet("TextFile", "SequenceFile", "RCfile", "ORC", "parquet"), "Default file format for CREATE TABLE statement. Users can explicitly override it by CREATE TABLE ... STORED AS [FORMAT]"), HIVEDEFAULTMANAGEDFILEFORMAT("hive.default.fileformat.managed", "none", new StringSet("none", "TextFile", "SequenceFile", "RCfile", "ORC", "parquet"), "Default file format for CREATE TABLE statement applied to managed tables only. External tables will be \n" + "created with format specified by hive.default.fileformat. Leaving this null will result in using hive.default.fileformat \n" + "for all tables."), HIVEQUERYRESULTFILEFORMAT("hive.query.result.fileformat", "SequenceFile", new StringSet("TextFile", "SequenceFile", "RCfile", "Llap"), "Default file format for storing result of the query."), HIVECHECKFILEFORMAT("hive.fileformat.check", true, "Whether to check file format or not when loading data files"), // default serde for rcfile HIVEDEFAULTRCFILESERDE("hive.default.rcfile.serde", "org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe", "The default SerDe Hive will use for the RCFile format"), HIVEDEFAULTSERDE("hive.default.serde", "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe", "The default SerDe Hive will use for storage formats that do not specify a SerDe."), /** * @deprecated Use MetastoreConf.SERDES_USING_METASTORE_FOR_SCHEMA */ @Deprecated SERDESUSINGMETASTOREFORSCHEMA("hive.serdes.using.metastore.for.schema", "org.apache.hadoop.hive.ql.io.orc.OrcSerde," + "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe," + "org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe," + "org.apache.hadoop.hive.serde2.dynamic_type.DynamicSerDe," + "org.apache.hadoop.hive.serde2.MetadataTypedColumnsetSerDe," + "org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe," + "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe," + "org.apache.hadoop.hive.serde2.lazybinary.LazyBinarySerDe", "SerDes retrieving schema from metastore. This is an internal parameter."), @Deprecated HIVE_LEGACY_SCHEMA_FOR_ALL_SERDES("hive.legacy.schema.for.all.serdes", false, "A backward compatibility setting for external metastore users that do not handle \n" + SERDESUSINGMETASTOREFORSCHEMA.varname + " correctly. This may be removed at any time."), HIVEHISTORYFILELOC("hive.querylog.location", "${system:java.io.tmpdir}" + File.separator + "${system:user.name}", "Location of Hive run time structured log file"), HIVE_LOG_INCREMENTAL_PLAN_PROGRESS("hive.querylog.enable.plan.progress", true, "Whether to log the plan's progress every time a job's progress is checked.\n" + "These logs are written to the location specified by hive.querylog.location"), HIVE_LOG_INCREMENTAL_PLAN_PROGRESS_INTERVAL("hive.querylog.plan.progress.interval", "60000ms", new TimeValidator(TimeUnit.MILLISECONDS), "The interval to wait between logging the plan's progress.\n" + "If there is a whole number percentage change in the progress of the mappers or the reducers,\n" + "the progress is logged regardless of this value.\n" + "The actual interval will be the ceiling of (this value divided by the value of\n" + "hive.exec.counters.pull.interval) multiplied by the value of hive.exec.counters.pull.interval\n" + "I.e. if it is not divide evenly by the value of hive.exec.counters.pull.interval it will be\n" + "logged less frequently than specified.\n" + "This only has an effect if hive.querylog.enable.plan.progress is set to true."), HIVESCRIPTSERDE("hive.script.serde", "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe", "The default SerDe for transmitting input data to and reading output data from the user scripts. "), HIVESCRIPTRECORDREADER("hive.script.recordreader", "org.apache.hadoop.hive.ql.exec.TextRecordReader", "The default record reader for reading data from the user scripts. "), HIVESCRIPTRECORDWRITER("hive.script.recordwriter", "org.apache.hadoop.hive.ql.exec.TextRecordWriter", "The default record writer for writing data to the user scripts. "), HIVESCRIPTESCAPE("hive.transform.escape.input", false, "This adds an option to escape special chars (newlines, carriage returns and\n" + "tabs) when they are passed to the user script. This is useful if the Hive tables\n" + "can contain data that contains special characters."), HIVEBINARYRECORDMAX("hive.binary.record.max.length", 1000, "Read from a binary stream and treat each hive.binary.record.max.length bytes as a record. \n" + "The last record before the end of stream can have less than hive.binary.record.max.length bytes"), HIVEHADOOPMAXMEM("hive.mapred.local.mem", 0, "mapper/reducer memory in local mode"), //small table file size HIVESMALLTABLESFILESIZE("hive.mapjoin.smalltable.filesize", 25000000L, "The threshold for the input file size of the small tables; if the file size is smaller \n" + "than this threshold, it will try to convert the common join into map join"), HIVE_SCHEMA_EVOLUTION("hive.exec.schema.evolution", true, "Use schema evolution to convert self-describing file format's data to the schema desired by the reader."), /** Don't use this directly - use AcidUtils! */ HIVE_TRANSACTIONAL_TABLE_SCAN("hive.transactional.table.scan", false, "internal usage only -- do transaction (ACID or insert-only) table scan.", true), HIVE_TRANSACTIONAL_NUM_EVENTS_IN_MEMORY("hive.transactional.events.mem", 10000000, "Vectorized ACID readers can often load all the delete events from all the delete deltas\n" + "into memory to optimize for performance. To prevent out-of-memory errors, this is a rough heuristic\n" + "that limits the total number of delete events that can be loaded into memory at once.\n" + "Roughly it has been set to 10 million delete events per bucket (~160 MB).\n"), HIVESAMPLERANDOMNUM("hive.sample.seednumber", 0, "A number used to percentage sampling. By changing this number, user will change the subsets of data sampled."), // test mode in hive mode HIVETESTMODE("hive.test.mode", false, "Whether Hive is running in test mode. If yes, it turns on sampling and prefixes the output tablename.", false), HIVEEXIMTESTMODE("hive.exim.test.mode", false, "The subset of test mode that only enables custom path handling for ExIm.", false), HIVETESTMODEPREFIX("hive.test.mode.prefix", "test_", "In test mode, specifies prefixes for the output table", false), HIVETESTMODESAMPLEFREQ("hive.test.mode.samplefreq", 32, "In test mode, specifies sampling frequency for table, which is not bucketed,\n" + "For example, the following query:\n" + " INSERT OVERWRITE TABLE dest SELECT col1 from src\n" + "would be converted to\n" + " INSERT OVERWRITE TABLE test_dest\n" + " SELECT col1 from src TABLESAMPLE (BUCKET 1 out of 32 on rand(1))", false), HIVETESTMODENOSAMPLE("hive.test.mode.nosamplelist", "", "In test mode, specifies comma separated table names which would not apply sampling", false), HIVETESTMODEDUMMYSTATAGGR("hive.test.dummystats.aggregator", "", "internal variable for test", false), HIVETESTMODEDUMMYSTATPUB("hive.test.dummystats.publisher", "", "internal variable for test", false), HIVETESTCURRENTTIMESTAMP("hive.test.currenttimestamp", null, "current timestamp for test", false), HIVETESTMODEROLLBACKTXN("hive.test.rollbacktxn", false, "For testing only. Will mark every ACID transaction aborted", false), HIVETESTMODEFAILCOMPACTION("hive.test.fail.compaction", false, "For testing only. Will cause CompactorMR to fail.", false), HIVETESTMODEFAILHEARTBEATER("hive.test.fail.heartbeater", false, "For testing only. Will cause Heartbeater to fail.", false), TESTMODE_BUCKET_CODEC_VERSION("hive.test.bucketcodec.version", 1, "For testing only. Will make ACID subsystem write RecordIdentifier.bucketId in specified\n" + "format", false), HIVEMERGEMAPFILES("hive.merge.mapfiles", true, "Merge small files at the end of a map-only job"), HIVEMERGEMAPREDFILES("hive.merge.mapredfiles", false, "Merge small files at the end of a map-reduce job"), HIVEMERGETEZFILES("hive.merge.tezfiles", false, "Merge small files at the end of a Tez DAG"), HIVEMERGESPARKFILES("hive.merge.sparkfiles", false, "Merge small files at the end of a Spark DAG Transformation"), HIVEMERGEMAPFILESSIZE("hive.merge.size.per.task", (long) (256 * 1000 * 1000), "Size of merged files at the end of the job"), HIVEMERGEMAPFILESAVGSIZE("hive.merge.smallfiles.avgsize", (long) (16 * 1000 * 1000), "When the average output file size of a job is less than this number, Hive will start an additional \n" + "map-reduce job to merge the output files into bigger files. This is only done for map-only jobs \n" + "if hive.merge.mapfiles is true, and for map-reduce jobs if hive.merge.mapredfiles is true."), HIVEMERGERCFILEBLOCKLEVEL("hive.merge.rcfile.block.level", true, ""), HIVEMERGEORCFILESTRIPELEVEL("hive.merge.orcfile.stripe.level", true, "When hive.merge.mapfiles, hive.merge.mapredfiles or hive.merge.tezfiles is enabled\n" + "while writing a table with ORC file format, enabling this config will do stripe-level\n" + "fast merge for small ORC files. Note that enabling this config will not honor the\n" + "padding tolerance config (hive.exec.orc.block.padding.tolerance)."), HIVE_ORC_CODEC_POOL("hive.use.orc.codec.pool", false, "Whether to use codec pool in ORC. Disable if there are bugs with codec reuse."), HIVEUSEEXPLICITRCFILEHEADER("hive.exec.rcfile.use.explicit.header", true, "If this is set the header for RCFiles will simply be RCF. If this is not\n" + "set the header will be that borrowed from sequence files, e.g. SEQ- followed\n" + "by the input and output RCFile formats."), HIVEUSERCFILESYNCCACHE("hive.exec.rcfile.use.sync.cache", true, ""), HIVE_RCFILE_RECORD_INTERVAL("hive.io.rcfile.record.interval", Integer.MAX_VALUE, ""), HIVE_RCFILE_COLUMN_NUMBER_CONF("hive.io.rcfile.column.number.conf", 0, ""), HIVE_RCFILE_TOLERATE_CORRUPTIONS("hive.io.rcfile.tolerate.corruptions", false, ""), HIVE_RCFILE_RECORD_BUFFER_SIZE("hive.io.rcfile.record.buffer.size", 4194304, ""), // 4M PARQUET_MEMORY_POOL_RATIO("parquet.memory.pool.ratio", 0.5f, "Maximum fraction of heap that can be used by Parquet file writers in one task.\n" + "It is for avoiding OutOfMemory error in tasks. Work with Parquet 1.6.0 and above.\n" + "This config parameter is defined in Parquet, so that it does not start with 'hive.'."), HIVE_PARQUET_TIMESTAMP_SKIP_CONVERSION("hive.parquet.timestamp.skip.conversion", false, "Current Hive implementation of parquet stores timestamps to UTC, this flag allows skipping of the conversion" + "on reading parquet files from other tools"), HIVE_INT_TIMESTAMP_CONVERSION_IN_SECONDS("hive.int.timestamp.conversion.in.seconds", false, "Boolean/tinyint/smallint/int/bigint value is interpreted as milliseconds during the timestamp conversion.\n" + "Set this flag to true to interpret the value as seconds to be consistent with float/double." ), HIVE_ORC_BASE_DELTA_RATIO("hive.exec.orc.base.delta.ratio", 8, "The ratio of base writer and\n" + "delta writer in terms of STRIPE_SIZE and BUFFER_SIZE."), HIVE_ORC_DELTA_STREAMING_OPTIMIZATIONS_ENABLED("hive.exec.orc.delta.streaming.optimizations.enabled", false, "Whether to enable streaming optimizations for ORC delta files. This will disable ORC's internal indexes,\n" + "disable compression, enable fast encoding and disable dictionary encoding."), HIVE_ORC_SPLIT_STRATEGY("hive.exec.orc.split.strategy", "HYBRID", new StringSet("HYBRID", "BI", "ETL"), "This is not a user level config. BI strategy is used when the requirement is to spend less time in split generation" + " as opposed to query execution (split generation does not read or cache file footers)." + " ETL strategy is used when spending little more time in split generation is acceptable" + " (split generation reads and caches file footers). HYBRID chooses between the above strategies" + " based on heuristics."), // hive streaming ingest settings HIVE_STREAMING_AUTO_FLUSH_ENABLED("hive.streaming.auto.flush.enabled", true, "Whether to enable memory \n" + "monitoring and automatic flushing of open record updaters during streaming ingest. This is an expert level \n" + "setting and disabling this may have severe performance impact under memory pressure."), HIVE_HEAP_MEMORY_MONITOR_USAGE_THRESHOLD("hive.heap.memory.monitor.usage.threshold", 0.7f, "Hive streaming does automatic memory management across all open record writers. This threshold will let the \n" + "memory monitor take an action (flush open files) when heap memory usage exceeded this threshold."), HIVE_STREAMING_AUTO_FLUSH_CHECK_INTERVAL_SIZE("hive.streaming.auto.flush.check.interval.size", "100Mb", new SizeValidator(), "Hive streaming ingest has auto flush mechanism to flush all open record updaters under memory pressure.\n" + "When memory usage exceed hive.heap.memory.monitor.default.usage.threshold, the auto-flush mechanism will \n" + "wait until this size (default 100Mb) of records are ingested before triggering flush."), HIVE_CLASSLOADER_SHADE_PREFIX("hive.classloader.shade.prefix", "", "During reflective instantiation of a class\n" + "(input, output formats, serde etc.), when classloader throws ClassNotFoundException, as a fallback this\n" + "shade prefix will be used before class reference and retried."), HIVE_ORC_MS_FOOTER_CACHE_ENABLED("hive.orc.splits.ms.footer.cache.enabled", false, "Whether to enable using file metadata cache in metastore for ORC file footers."), HIVE_ORC_MS_FOOTER_CACHE_PPD("hive.orc.splits.ms.footer.cache.ppd.enabled", true, "Whether to enable file footer cache PPD (hive.orc.splits.ms.footer.cache.enabled\n" + "must also be set to true for this to work)."), HIVE_ORC_INCLUDE_FILE_FOOTER_IN_SPLITS("hive.orc.splits.include.file.footer", false, "If turned on splits generated by orc will include metadata about the stripes in the file. This\n" + "data is read remotely (from the client or HS2 machine) and sent to all the tasks."), HIVE_ORC_SPLIT_DIRECTORY_BATCH_MS("hive.orc.splits.directory.batch.ms", 0, "How long, in ms, to wait to batch input directories for processing during ORC split\n" + "generation. 0 means process directories individually. This can increase the number of\n" + "metastore calls if metastore metadata cache is used."), HIVE_ORC_INCLUDE_FILE_ID_IN_SPLITS("hive.orc.splits.include.fileid", true, "Include file ID in splits on file systems that support it."), HIVE_ORC_ALLOW_SYNTHETIC_FILE_ID_IN_SPLITS("hive.orc.splits.allow.synthetic.fileid", true, "Allow synthetic file ID in splits on file systems that don't have a native one."), HIVE_ORC_CACHE_STRIPE_DETAILS_MEMORY_SIZE("hive.orc.cache.stripe.details.mem.size", "256Mb", new SizeValidator(), "Maximum size of orc splits cached in the client."), HIVE_ORC_COMPUTE_SPLITS_NUM_THREADS("hive.orc.compute.splits.num.threads", 10, "How many threads orc should use to create splits in parallel."), HIVE_ORC_CACHE_USE_SOFT_REFERENCES("hive.orc.cache.use.soft.references", false, "By default, the cache that ORC input format uses to store orc file footer use hard\n" + "references for the cached object. Setting this to true can help avoid out of memory\n" + "issues under memory pressure (in some cases) at the cost of slight unpredictability in\n" + "overall query performance."), HIVE_IO_SARG_CACHE_MAX_WEIGHT_MB("hive.io.sarg.cache.max.weight.mb", 10, "The max weight allowed for the SearchArgument Cache. By default, the cache allows a max-weight of 10MB, " + "after which entries will be evicted."), HIVE_LAZYSIMPLE_EXTENDED_BOOLEAN_LITERAL("hive.lazysimple.extended_boolean_literal", false, "LazySimpleSerde uses this property to determine if it treats 'T', 't', 'F', 'f',\n" + "'1', and '0' as extended, legal boolean literal, in addition to 'TRUE' and 'FALSE'.\n" + "The default is false, which means only 'TRUE' and 'FALSE' are treated as legal\n" + "boolean literal."), HIVESKEWJOIN("hive.optimize.skewjoin", false, "Whether to enable skew join optimization. \n" + "The algorithm is as follows: At runtime, detect the keys with a large skew. Instead of\n" + "processing those keys, store them temporarily in an HDFS directory. In a follow-up map-reduce\n" + "job, process those skewed keys. The same key need not be skewed for all the tables, and so,\n" + "the follow-up map-reduce job (for the skewed keys) would be much faster, since it would be a\n" + "map-join."), HIVEDYNAMICPARTITIONHASHJOIN("hive.optimize.dynamic.partition.hashjoin", false, "Whether to enable dynamically partitioned hash join optimization. \n" + "This setting is also dependent on enabling hive.auto.convert.join"), HIVECONVERTJOIN("hive.auto.convert.join", true, "Whether Hive enables the optimization about converting common join into mapjoin based on the input file size"), HIVECONVERTJOINNOCONDITIONALTASK("hive.auto.convert.join.noconditionaltask", true, "Whether Hive enables the optimization about converting common join into mapjoin based on the input file size. \n" + "If this parameter is on, and the sum of size for n-1 of the tables/partitions for a n-way join is smaller than the\n" + "specified size, the join is directly converted to a mapjoin (there is no conditional task)."), HIVECONVERTJOINNOCONDITIONALTASKTHRESHOLD("hive.auto.convert.join.noconditionaltask.size", 10000000L, "If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" + "However, if it is on, and the sum of size for n-1 of the tables/partitions for a n-way join is smaller than this size, \n" + "the join is directly converted to a mapjoin(there is no conditional task). The default is 10MB"), HIVECONVERTJOINUSENONSTAGED("hive.auto.convert.join.use.nonstaged", false, "For conditional joins, if input stream from a small alias can be directly applied to join operator without \n" + "filtering or projection, the alias need not to be pre-staged in distributed cache via mapred local task.\n" + "Currently, this is not working with vectorization or tez execution engine."), HIVESKEWJOINKEY("hive.skewjoin.key", 100000, "Determine if we get a skew key in join. If we see more than the specified number of rows with the same key in join operator,\n" + "we think the key as a skew join key. "), HIVESKEWJOINMAPJOINNUMMAPTASK("hive.skewjoin.mapjoin.map.tasks", 10000, "Determine the number of map task used in the follow up map join job for a skew join.\n" + "It should be used together with hive.skewjoin.mapjoin.min.split to perform a fine grained control."), HIVESKEWJOINMAPJOINMINSPLIT("hive.skewjoin.mapjoin.min.split", 33554432L, "Determine the number of map task at most used in the follow up map join job for a skew join by specifying \n" + "the minimum split size. It should be used together with hive.skewjoin.mapjoin.map.tasks to perform a fine grained control."), HIVESENDHEARTBEAT("hive.heartbeat.interval", 1000, "Send a heartbeat after this interval - used by mapjoin and filter operators"), HIVELIMITMAXROWSIZE("hive.limit.row.max.size", 100000L, "When trying a smaller subset of data for simple LIMIT, how much size we need to guarantee each row to have at least."), HIVELIMITOPTLIMITFILE("hive.limit.optimize.limit.file", 10, "When trying a smaller subset of data for simple LIMIT, maximum number of files we can sample."), HIVELIMITOPTENABLE("hive.limit.optimize.enable", false, "Whether to enable to optimization to trying a smaller subset of data for simple LIMIT first."), HIVELIMITOPTMAXFETCH("hive.limit.optimize.fetch.max", 50000, "Maximum number of rows allowed for a smaller subset of data for simple LIMIT, if it is a fetch query. \n" + "Insert queries are not restricted by this limit."), HIVELIMITPUSHDOWNMEMORYUSAGE("hive.limit.pushdown.memory.usage", 0.1f, new RatioValidator(), "The fraction of available memory to be used for buffering rows in Reducesink operator for limit pushdown optimization."), HIVECONVERTJOINMAXENTRIESHASHTABLE("hive.auto.convert.join.hashtable.max.entries", 21000000L, "If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" + "However, if it is on, and the predicted number of entries in hashtable for a given join \n" + "input is larger than this number, the join will not be converted to a mapjoin. \n" + "The value \"-1\" means no limit."), HIVECONVERTJOINMAXSHUFFLESIZE("hive.auto.convert.join.shuffle.max.size", 10000000L, "If hive.auto.convert.join.noconditionaltask is off, this parameter does not take affect. \n" + "However, if it is on, and the predicted size of the larger input for a given join is greater \n" + "than this number, the join will not be converted to a dynamically partitioned hash join. \n" + "The value \"-1\" means no limit."), HIVEHASHTABLEKEYCOUNTADJUSTMENT("hive.hashtable.key.count.adjustment", 2.0f, "Adjustment to mapjoin hashtable size derived from table and column statistics; the estimate" + " of the number of keys is divided by this value. If the value is 0, statistics are not used" + "and hive.hashtable.initialCapacity is used instead."), HIVEHASHTABLETHRESHOLD("hive.hashtable.initialCapacity", 100000, "Initial capacity of " + "mapjoin hashtable if statistics are absent, or if hive.hashtable.key.count.adjustment is set to 0"), HIVEHASHTABLELOADFACTOR("hive.hashtable.loadfactor", (float) 0.75, ""), HIVEHASHTABLEFOLLOWBYGBYMAXMEMORYUSAGE("hive.mapjoin.followby.gby.localtask.max.memory.usage", (float) 0.55, "This number means how much memory the local task can take to hold the key/value into an in-memory hash table \n" + "when this map join is followed by a group by. If the local task's memory usage is more than this number, \n" + "the local task will abort by itself. It means the data of the small table is too large to be held in memory."), HIVEHASHTABLEMAXMEMORYUSAGE("hive.mapjoin.localtask.max.memory.usage", (float) 0.90, "This number means how much memory the local task can take to hold the key/value into an in-memory hash table. \n" + "If the local task's memory usage is more than this number, the local task will abort by itself. \n" + "It means the data of the small table is too large to be held in memory."), HIVEHASHTABLESCALE("hive.mapjoin.check.memory.rows", (long)100000, "The number means after how many rows processed it needs to check the memory usage"), HIVEDEBUGLOCALTASK("hive.debug.localtask",false, ""), HIVEINPUTFORMAT("hive.input.format", "org.apache.hadoop.hive.ql.io.CombineHiveInputFormat", "The default input format. Set this to HiveInputFormat if you encounter problems with CombineHiveInputFormat."), HIVETEZINPUTFORMAT("hive.tez.input.format", "org.apache.hadoop.hive.ql.io.HiveInputFormat", "The default input format for tez. Tez groups splits in the AM."), HIVETEZCONTAINERSIZE("hive.tez.container.size", -1, "By default Tez will spawn containers of the size of a mapper. This can be used to overwrite."), HIVETEZCPUVCORES("hive.tez.cpu.vcores", -1, "By default Tez will ask for however many cpus map-reduce is configured to use per container.\n" + "This can be used to overwrite."), HIVETEZJAVAOPTS("hive.tez.java.opts", null, "By default Tez will use the Java options from map tasks. This can be used to overwrite."), HIVETEZLOGLEVEL("hive.tez.log.level", "INFO", "The log level to use for tasks executing as part of the DAG.\n" + "Used only if hive.tez.java.opts is used to configure Java options."), HIVETEZHS2USERACCESS("hive.tez.hs2.user.access", true, "Whether to grant access to the hs2/hive user for queries"), HIVEQUERYNAME ("hive.query.name", null, "This named is used by Tez to set the dag name. This name in turn will appear on \n" + "the Tez UI representing the work that was done. Used by Spark to set the query name, will show up in the\n" + "Spark UI."), HIVEOPTIMIZEBUCKETINGSORTING("hive.optimize.bucketingsorting", true, "Don't create a reducer for enforcing \n" + "bucketing/sorting for queries of the form: \n" + "insert overwrite table T2 select * from T1;\n" + "where T1 and T2 are bucketed/sorted by the same keys into the same number of buckets."), HIVEPARTITIONER("hive.mapred.partitioner", "org.apache.hadoop.hive.ql.io.DefaultHivePartitioner", ""), HIVEENFORCESORTMERGEBUCKETMAPJOIN("hive.enforce.sortmergebucketmapjoin", false, "If the user asked for sort-merge bucketed map-side join, and it cannot be performed, should the query fail or not ?"), HIVEENFORCEBUCKETMAPJOIN("hive.enforce.bucketmapjoin", false, "If the user asked for bucketed map-side join, and it cannot be performed, \n" + "should the query fail or not ? For example, if the buckets in the tables being joined are\n" + "not a multiple of each other, bucketed map-side join cannot be performed, and the\n" + "query will fail if hive.enforce.bucketmapjoin is set to true."), HIVE_ENFORCE_NOT_NULL_CONSTRAINT("hive.constraint.notnull.enforce", true, "Should \"IS NOT NULL \" constraint be enforced?"), HIVE_AUTO_SORTMERGE_JOIN("hive.auto.convert.sortmerge.join", false, "Will the join be automatically converted to a sort-merge join, if the joined tables pass the criteria for sort-merge join."), HIVE_AUTO_SORTMERGE_JOIN_REDUCE("hive.auto.convert.sortmerge.join.reduce.side", true, "Whether hive.auto.convert.sortmerge.join (if enabled) should be applied to reduce side."), HIVE_AUTO_SORTMERGE_JOIN_BIGTABLE_SELECTOR( "hive.auto.convert.sortmerge.join.bigtable.selection.policy", "org.apache.hadoop.hive.ql.optimizer.AvgPartitionSizeBasedBigTableSelectorForAutoSMJ", "The policy to choose the big table for automatic conversion to sort-merge join. \n" + "By default, the table with the largest partitions is assigned the big table. All policies are:\n" + ". based on position of the table - the leftmost table is selected\n" + "org.apache.hadoop.hive.ql.optimizer.LeftmostBigTableSMJ.\n" + ". based on total size (all the partitions selected in the query) of the table \n" + "org.apache.hadoop.hive.ql.optimizer.TableSizeBasedBigTableSelectorForAutoSMJ.\n" + ". based on average size (all the partitions selected in the query) of the table \n" + "org.apache.hadoop.hive.ql.optimizer.AvgPartitionSizeBasedBigTableSelectorForAutoSMJ.\n" + "New policies can be added in future."), HIVE_AUTO_SORTMERGE_JOIN_TOMAPJOIN( "hive.auto.convert.sortmerge.join.to.mapjoin", false, "If hive.auto.convert.sortmerge.join is set to true, and a join was converted to a sort-merge join, \n" + "this parameter decides whether each table should be tried as a big table, and effectively a map-join should be\n" + "tried. That would create a conditional task with n+1 children for a n-way join (1 child for each table as the\n" + "big table), and the backup task will be the sort-merge join. In some cases, a map-join would be faster than a\n" + "sort-merge join, if there is no advantage of having the output bucketed and sorted. For example, if a very big sorted\n" + "and bucketed table with few files (say 10 files) are being joined with a very small sorter and bucketed table\n" + "with few files (10 files), the sort-merge join will only use 10 mappers, and a simple map-only join might be faster\n" + "if the complete small table can fit in memory, and a map-join can be performed."), HIVESCRIPTOPERATORTRUST("hive.exec.script.trust", false, ""), HIVEROWOFFSET("hive.exec.rowoffset", false, "Whether to provide the row offset virtual column"), // Optimizer HIVEOPTINDEXFILTER("hive.optimize.index.filter", true, "Whether to enable automatic use of indexes"), HIVEOPTPPD("hive.optimize.ppd", true, "Whether to enable predicate pushdown"), HIVEOPTPPD_WINDOWING("hive.optimize.ppd.windowing", true, "Whether to enable predicate pushdown through windowing"), HIVEPPDRECOGNIZETRANSITIVITY("hive.ppd.recognizetransivity", true, "Whether to transitively replicate predicate filters over equijoin conditions."), HIVEPPDREMOVEDUPLICATEFILTERS("hive.ppd.remove.duplicatefilters", true, "During query optimization, filters may be pushed down in the operator tree. \n" + "If this config is true only pushed down filters remain in the operator tree, \n" + "and the original filter is removed. If this config is false, the original filter \n" + "is also left in the operator tree at the original place."), HIVEPOINTLOOKUPOPTIMIZER("hive.optimize.point.lookup", true, "Whether to transform OR clauses in Filter operators into IN clauses"), HIVEPOINTLOOKUPOPTIMIZERMIN("hive.optimize.point.lookup.min", 31, "Minimum number of OR clauses needed to transform into IN clauses"), HIVECOUNTDISTINCTOPTIMIZER("hive.optimize.countdistinct", true, "Whether to transform count distinct into two stages"), HIVEPARTITIONCOLUMNSEPARATOR("hive.optimize.partition.columns.separate", true, "Extract partition columns from IN clauses"), // Constant propagation optimizer HIVEOPTCONSTANTPROPAGATION("hive.optimize.constant.propagation", true, "Whether to enable constant propagation optimizer"), HIVEIDENTITYPROJECTREMOVER("hive.optimize.remove.identity.project", true, "Removes identity project from operator tree"), HIVEMETADATAONLYQUERIES("hive.optimize.metadataonly", false, "Whether to eliminate scans of the tables from which no columns are selected. Note\n" + "that, when selecting from empty tables with data files, this can produce incorrect\n" + "results, so it's disabled by default. It works correctly for normal tables."), HIVENULLSCANOPTIMIZE("hive.optimize.null.scan", true, "Dont scan relations which are guaranteed to not generate any rows"), HIVEOPTPPD_STORAGE("hive.optimize.ppd.storage", true, "Whether to push predicates down to storage handlers"), HIVEOPTGROUPBY("hive.optimize.groupby", true, "Whether to enable the bucketed group by from bucketed partitions/tables."), HIVEOPTBUCKETMAPJOIN("hive.optimize.bucketmapjoin", false, "Whether to try bucket mapjoin"), HIVEOPTSORTMERGEBUCKETMAPJOIN("hive.optimize.bucketmapjoin.sortedmerge", false, "Whether to try sorted bucket merge map join"), HIVEOPTREDUCEDEDUPLICATION("hive.optimize.reducededuplication", true, "Remove extra map-reduce jobs if the data is already clustered by the same key which needs to be used again. \n" + "This should always be set to true. Since it is a new feature, it has been made configurable."), HIVEOPTREDUCEDEDUPLICATIONMINREDUCER("hive.optimize.reducededuplication.min.reducer", 4, "Reduce deduplication merges two RSs by moving key/parts/reducer-num of the child RS to parent RS. \n" + "That means if reducer-num of the child RS is fixed (order by or forced bucketing) and small, it can make very slow, single MR.\n" + "The optimization will be automatically disabled if number of reducers would be less than specified value."), HIVEOPTJOINREDUCEDEDUPLICATION("hive.optimize.joinreducededuplication", true, "Remove extra shuffle/sorting operations after join algorithm selection has been executed. \n" + "Currently it only works with Apache Tez. This should always be set to true. \n" + "Since it is a new feature, it has been made configurable."), HIVEOPTSORTDYNAMICPARTITION("hive.optimize.sort.dynamic.partition", false, "When enabled dynamic partitioning column will be globally sorted.\n" + "This way we can keep only one record writer open for each partition value\n" + "in the reducer thereby reducing the memory pressure on reducers."), HIVESAMPLINGFORORDERBY("hive.optimize.sampling.orderby", false, "Uses sampling on order-by clause for parallel execution."), HIVESAMPLINGNUMBERFORORDERBY("hive.optimize.sampling.orderby.number", 1000, "Total number of samples to be obtained."), HIVESAMPLINGPERCENTFORORDERBY("hive.optimize.sampling.orderby.percent", 0.1f, new RatioValidator(), "Probability with which a row will be chosen."), HIVE_REMOVE_ORDERBY_IN_SUBQUERY("hive.remove.orderby.in.subquery", true, "If set to true, order/sort by without limit in sub queries will be removed."), HIVEOPTIMIZEDISTINCTREWRITE("hive.optimize.distinct.rewrite", true, "When applicable this " + "optimization rewrites distinct aggregates from a single stage to multi-stage " + "aggregation. This may not be optimal in all cases. Ideally, whether to trigger it or " + "not should be cost based decision. Until Hive formalizes cost model for this, this is config driven."), // whether to optimize union followed by select followed by filesink // It creates sub-directories in the final output, so should not be turned on in systems // where MAPREDUCE-1501 is not present HIVE_OPTIMIZE_UNION_REMOVE("hive.optimize.union.remove", false, "Whether to remove the union and push the operators between union and the filesink above union. \n" + "This avoids an extra scan of the output by union. This is independently useful for union\n" + "queries, and specially useful when hive.optimize.skewjoin.compiletime is set to true, since an\n" + "extra union is inserted.\n" + "\n" + "The merge is triggered if either of hive.merge.mapfiles or hive.merge.mapredfiles is set to true.\n" + "If the user has set hive.merge.mapfiles to true and hive.merge.mapredfiles to false, the idea was the\n" + "number of reducers are few, so the number of files anyway are small. However, with this optimization,\n" + "we are increasing the number of files possibly by a big margin. So, we merge aggressively."), HIVEOPTCORRELATION("hive.optimize.correlation", false, "exploit intra-query correlations."), HIVE_OPTIMIZE_LIMIT_TRANSPOSE("hive.optimize.limittranspose", false, "Whether to push a limit through left/right outer join or union. If the value is true and the size of the outer\n" + "input is reduced enough (as specified in hive.optimize.limittranspose.reduction), the limit is pushed\n" + "to the outer input or union; to remain semantically correct, the limit is kept on top of the join or the union too."), HIVE_OPTIMIZE_LIMIT_TRANSPOSE_REDUCTION_PERCENTAGE("hive.optimize.limittranspose.reductionpercentage", 1.0f, "When hive.optimize.limittranspose is true, this variable specifies the minimal reduction of the\n" + "size of the outer input of the join or input of the union that we should get in order to apply the rule."), HIVE_OPTIMIZE_LIMIT_TRANSPOSE_REDUCTION_TUPLES("hive.optimize.limittranspose.reductiontuples", (long) 0, "When hive.optimize.limittranspose is true, this variable specifies the minimal reduction in the\n" + "number of tuples of the outer input of the join or the input of the union that you should get in order to apply the rule."), HIVE_OPTIMIZE_REDUCE_WITH_STATS("hive.optimize.filter.stats.reduction", false, "Whether to simplify comparison\n" + "expressions in filter operators using column stats"), HIVE_OPTIMIZE_SKEWJOIN_COMPILETIME("hive.optimize.skewjoin.compiletime", false, "Whether to create a separate plan for skewed keys for the tables in the join.\n" + "This is based on the skewed keys stored in the metadata. At compile time, the plan is broken\n" + "into different joins: one for the skewed keys, and the other for the remaining keys. And then,\n" + "a union is performed for the 2 joins generated above. So unless the same skewed key is present\n" + "in both the joined tables, the join for the skewed key will be performed as a map-side join.\n" + "\n" + "The main difference between this parameter and hive.optimize.skewjoin is that this parameter\n" + "uses the skew information stored in the metastore to optimize the plan at compile time itself.\n" + "If there is no skew information in the metadata, this parameter will not have any affect.\n" + "Both hive.optimize.skewjoin.compiletime and hive.optimize.skewjoin should be set to true.\n" + "Ideally, hive.optimize.skewjoin should be renamed as hive.optimize.skewjoin.runtime, but not doing\n" + "so for backward compatibility.\n" + "\n" + "If the skew information is correctly stored in the metadata, hive.optimize.skewjoin.compiletime\n" + "would change the query plan to take care of it, and hive.optimize.skewjoin will be a no-op."), HIVE_SHARED_WORK_OPTIMIZATION("hive.optimize.shared.work", true, "Whether to enable shared work optimizer. The optimizer finds scan operator over the same table\n" + "and follow-up operators in the query plan and merges them if they meet some preconditions. Tez only."), HIVE_SHARED_WORK_EXTENDED_OPTIMIZATION("hive.optimize.shared.work.extended", true, "Whether to enable shared work extended optimizer. The optimizer tries to merge equal operators\n" + "after a work boundary after shared work optimizer has been executed. Requires hive.optimize.shared.work\n" + "to be set to true. Tez only."), HIVE_COMBINE_EQUIVALENT_WORK_OPTIMIZATION("hive.combine.equivalent.work.optimization", true, "Whether to " + "combine equivalent work objects during physical optimization.\n This optimization looks for equivalent " + "work objects and combines them if they meet certain preconditions. Spark only."), HIVE_REMOVE_SQ_COUNT_CHECK("hive.optimize.remove.sq_count_check", false, "Whether to remove an extra join with sq_count_check for scalar subqueries " + "with constant group by keys."), HIVE_OPTIMIZE_TABLE_PROPERTIES_FROM_SERDE("hive.optimize.update.table.properties.from.serde", false, "Whether to update table-properties by initializing tables' SerDe instances during logical-optimization. \n" + "By doing so, certain SerDe classes (like AvroSerDe) can pre-calculate table-specific information, and \n" + "store it in table-properties, to be used later in the SerDe, while running the job."), HIVE_OPTIMIZE_TABLE_PROPERTIES_FROM_SERDE_LIST("hive.optimize.update.table.properties.from.serde.list", "org.apache.hadoop.hive.serde2.avro.AvroSerDe", "The comma-separated list of SerDe classes that are considered when enhancing table-properties \n" + "during logical optimization."), // CTE HIVE_CTE_MATERIALIZE_THRESHOLD("hive.optimize.cte.materialize.threshold", -1, "If the number of references to a CTE clause exceeds this threshold, Hive will materialize it\n" + "before executing the main query block. -1 will disable this feature."), // Statistics HIVE_STATS_ESTIMATE_STATS("hive.stats.estimate", true, "Estimate statistics in absence of statistics."), HIVE_STATS_NDV_ESTIMATE_PERC("hive.stats.ndv.estimate.percent", (float)20, "This many percentage of rows will be estimated as count distinct in absence of statistics."), HIVE_STATS_NUM_NULLS_ESTIMATE_PERC("hive.stats.num.nulls.estimate.percent", (float)5, "This many percentage of rows will be estimated as number of nulls in absence of statistics."), HIVESTATSAUTOGATHER("hive.stats.autogather", true, "A flag to gather statistics (only basic) automatically during the INSERT OVERWRITE command."), HIVESTATSCOLAUTOGATHER("hive.stats.column.autogather", true, "A flag to gather column statistics automatically."), HIVESTATSDBCLASS("hive.stats.dbclass", "fs", new PatternSet("custom", "fs"), "The storage that stores temporary Hive statistics. In filesystem based statistics collection ('fs'), \n" + "each task writes statistics it has collected in a file on the filesystem, which will be aggregated \n" + "after the job has finished. Supported values are fs (filesystem) and custom as defined in StatsSetupConst.java."), // StatsSetupConst.StatDB /** * @deprecated Use MetastoreConf.STATS_DEFAULT_PUBLISHER */ @Deprecated HIVE_STATS_DEFAULT_PUBLISHER("hive.stats.default.publisher", "", "The Java class (implementing the StatsPublisher interface) that is used by default if hive.stats.dbclass is custom type."), /** * @deprecated Use MetastoreConf.STATS_DEFAULT_AGGRETATOR */ @Deprecated HIVE_STATS_DEFAULT_AGGREGATOR("hive.stats.default.aggregator", "", "The Java class (implementing the StatsAggregator interface) that is used by default if hive.stats.dbclass is custom type."), CLIENT_STATS_COUNTERS("hive.client.stats.counters", "", "Subset of counters that should be of interest for hive.client.stats.publishers (when one wants to limit their publishing). \n" + "Non-display names should be used"), //Subset of counters that should be of interest for hive.client.stats.publishers (when one wants to limit their publishing). Non-display names should be used". HIVE_STATS_RELIABLE("hive.stats.reliable", false, "Whether queries will fail because stats cannot be collected completely accurately. \n" + "If this is set to true, reading/writing from/into a partition may fail because the stats\n" + "could not be computed accurately."), HIVE_STATS_COLLECT_PART_LEVEL_STATS("hive.analyze.stmt.collect.partlevel.stats", true, "analyze table T compute statistics for columns. Queries like these should compute partition" + "level stats for partitioned table even when no part spec is specified."), HIVE_STATS_GATHER_NUM_THREADS("hive.stats.gather.num.threads", 10, "Number of threads used by noscan analyze command for partitioned tables.\n" + "This is applicable only for file formats that implement StatsProvidingRecordReader (like ORC)."), // Collect table access keys information for operators that can benefit from bucketing HIVE_STATS_COLLECT_TABLEKEYS("hive.stats.collect.tablekeys", false, "Whether join and group by keys on tables are derived and maintained in the QueryPlan.\n" + "This is useful to identify how tables are accessed and to determine if they should be bucketed."), // Collect column access information HIVE_STATS_COLLECT_SCANCOLS("hive.stats.collect.scancols", false, "Whether column accesses are tracked in the QueryPlan.\n" + "This is useful to identify how tables are accessed and to determine if there are wasted columns that can be trimmed."), HIVE_STATS_NDV_ALGO("hive.stats.ndv.algo", "hll", new PatternSet("hll", "fm"), "hll and fm stand for HyperLogLog and FM-sketch, respectively for computing ndv."), /** * @deprecated Use MetastoreConf.STATS_FETCH_BITVECTOR */ @Deprecated HIVE_STATS_FETCH_BITVECTOR("hive.stats.fetch.bitvector", false, "Whether we fetch bitvector when we compute ndv. Users can turn it off if they want to use old schema"), // standard error allowed for ndv estimates for FM-sketch. A lower value indicates higher accuracy and a // higher compute cost. HIVE_STATS_NDV_ERROR("hive.stats.ndv.error", (float)20.0, "Standard error expressed in percentage. Provides a tradeoff between accuracy and compute cost. \n" + "A lower value for error indicates higher accuracy and a higher compute cost."), /** * @deprecated Use MetastoreConf.STATS_NDV_TUNER */ @Deprecated HIVE_METASTORE_STATS_NDV_TUNER("hive.metastore.stats.ndv.tuner", (float)0.0, "Provides a tunable parameter between the lower bound and the higher bound of ndv for aggregate ndv across all the partitions. \n" + "The lower bound is equal to the maximum of ndv of all the partitions. The higher bound is equal to the sum of ndv of all the partitions.\n" + "Its value should be between 0.0 (i.e., choose lower bound) and 1.0 (i.e., choose higher bound)"), /** * @deprecated Use MetastoreConf.STATS_NDV_DENSITY_FUNCTION */ @Deprecated HIVE_METASTORE_STATS_NDV_DENSITY_FUNCTION("hive.metastore.stats.ndv.densityfunction", false, "Whether to use density function to estimate the NDV for the whole table based on the NDV of partitions"), HIVE_STATS_KEY_PREFIX("hive.stats.key.prefix", "", "", true), // internal usage only // if length of variable length data type cannot be determined this length will be used. HIVE_STATS_MAX_VARIABLE_LENGTH("hive.stats.max.variable.length", 100, "To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" + "average row size is multiplied with the total number of rows coming out of each operator.\n" + "Average row size is computed from average column size of all columns in the row. In the absence\n" + "of column statistics, for variable length columns (like string, bytes etc.), this value will be\n" + "used. For fixed length columns their corresponding Java equivalent sizes are used\n" + "(float - 4 bytes, double - 8 bytes etc.)."), // if number of elements in list cannot be determined, this value will be used HIVE_STATS_LIST_NUM_ENTRIES("hive.stats.list.num.entries", 10, "To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" + "average row size is multiplied with the total number of rows coming out of each operator.\n" + "Average row size is computed from average column size of all columns in the row. In the absence\n" + "of column statistics and for variable length complex columns like list, the average number of\n" + "entries/values can be specified using this config."), // if number of elements in map cannot be determined, this value will be used HIVE_STATS_MAP_NUM_ENTRIES("hive.stats.map.num.entries", 10, "To estimate the size of data flowing through operators in Hive/Tez(for reducer estimation etc.),\n" + "average row size is multiplied with the total number of rows coming out of each operator.\n" + "Average row size is computed from average column size of all columns in the row. In the absence\n" + "of column statistics and for variable length complex columns like map, the average number of\n" + "entries/values can be specified using this config."), // statistics annotation fetches column statistics for all required columns which can // be very expensive sometimes HIVE_STATS_FETCH_COLUMN_STATS("hive.stats.fetch.column.stats", false, "Annotation of operator tree with statistics information requires column statistics.\n" + "Column statistics are fetched from metastore. Fetching column statistics for each needed column\n" + "can be expensive when the number of columns is high. This flag can be used to disable fetching\n" + "of column statistics from metastore."), // in the absence of column statistics, the estimated number of rows/data size that will // be emitted from join operator will depend on this factor HIVE_STATS_JOIN_FACTOR("hive.stats.join.factor", (float) 1.1, "Hive/Tez optimizer estimates the data size flowing through each of the operators. JOIN operator\n" + "uses column statistics to estimate the number of rows flowing out of it and hence the data size.\n" + "In the absence of column statistics, this factor determines the amount of rows that flows out\n" + "of JOIN operator."), HIVE_STATS_CORRELATED_MULTI_KEY_JOINS("hive.stats.correlated.multi.key.joins", true, "When estimating output rows for a join involving multiple columns, the default behavior assumes" + "the columns are independent. Setting this flag to true will cause the estimator to assume" + "the columns are correlated."), // in the absence of uncompressed/raw data size, total file size will be used for statistics // annotation. But the file may be compressed, encoded and serialized which may be lesser in size // than the actual uncompressed/raw data size. This factor will be multiplied to file size to estimate // the raw data size. HIVE_STATS_DESERIALIZATION_FACTOR("hive.stats.deserialization.factor", (float) 10.0, "Hive/Tez optimizer estimates the data size flowing through each of the operators. In the absence\n" + "of basic statistics like number of rows and data size, file size is used to estimate the number\n" + "of rows and data size. Since files in tables/partitions are serialized (and optionally\n" + "compressed) the estimates of number of rows and data size cannot be reliably determined.\n" + "This factor is multiplied with the file size to account for serialization and compression."), HIVE_STATS_IN_CLAUSE_FACTOR("hive.stats.filter.in.factor", (float) 1.0, "Currently column distribution is assumed to be uniform. This can lead to overestimation/underestimation\n" + "in the number of rows filtered by a certain operator, which in turn might lead to overprovision or\n" + "underprovision of resources. This factor is applied to the cardinality estimation of IN clauses in\n" + "filter operators."), HIVE_STATS_IN_MIN_RATIO("hive.stats.filter.in.min.ratio", (float) 0.05, "Output estimation of an IN filter can't be lower than this ratio"), // Concurrency HIVE_SUPPORT_CONCURRENCY("hive.support.concurrency", false, "Whether Hive supports concurrency control or not. \n" + "A ZooKeeper instance must be up and running when using zookeeper Hive lock manager "), HIVE_LOCK_MANAGER("hive.lock.manager", "org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager", ""), HIVE_LOCK_NUMRETRIES("hive.lock.numretries", 100, "The number of times you want to try to get all the locks"), HIVE_UNLOCK_NUMRETRIES("hive.unlock.numretries", 10, "The number of times you want to retry to do one unlock"), HIVE_LOCK_SLEEP_BETWEEN_RETRIES("hive.lock.sleep.between.retries", "60s", new TimeValidator(TimeUnit.SECONDS, 0L, false, Long.MAX_VALUE, false), "The maximum sleep time between various retries"), HIVE_LOCK_MAPRED_ONLY("hive.lock.mapred.only.operation", false, "This param is to control whether or not only do lock on queries\n" + "that need to execute at least one mapred job."), HIVE_LOCK_QUERY_STRING_MAX_LENGTH("hive.lock.query.string.max.length", 1000000, "The maximum length of the query string to store in the lock.\n" + "The default value is 1000000, since the data limit of a znode is 1MB"), // Zookeeper related configs HIVE_ZOOKEEPER_QUORUM("hive.zookeeper.quorum", "", "List of ZooKeeper servers to talk to. This is needed for: \n" + "1. Read/write locks - when hive.lock.manager is set to \n" + "org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager, \n" + "2. When HiveServer2 supports service discovery via Zookeeper.\n" + "3. For delegation token storage if zookeeper store is used, if\n" + "hive.cluster.delegation.token.store.zookeeper.connectString is not set\n" + "4. LLAP daemon registry service\n" + "5. Leader selection for privilege synchronizer"), HIVE_ZOOKEEPER_CLIENT_PORT("hive.zookeeper.client.port", "2181", "The port of ZooKeeper servers to talk to.\n" + "If the list of Zookeeper servers specified in hive.zookeeper.quorum\n" + "does not contain port numbers, this value is used."), HIVE_ZOOKEEPER_SESSION_TIMEOUT("hive.zookeeper.session.timeout", "1200000ms", new TimeValidator(TimeUnit.MILLISECONDS), "ZooKeeper client's session timeout (in milliseconds). The client is disconnected, and as a result, all locks released, \n" + "if a heartbeat is not sent in the timeout."), HIVE_ZOOKEEPER_CONNECTION_TIMEOUT("hive.zookeeper.connection.timeout", "15s", new TimeValidator(TimeUnit.SECONDS), "ZooKeeper client's connection timeout in seconds. Connection timeout * hive.zookeeper.connection.max.retries\n" + "with exponential backoff is when curator client deems connection is lost to zookeeper."), HIVE_ZOOKEEPER_NAMESPACE("hive.zookeeper.namespace", "hive_zookeeper_namespace", "The parent node under which all ZooKeeper nodes are created."), HIVE_ZOOKEEPER_CLEAN_EXTRA_NODES("hive.zookeeper.clean.extra.nodes", false, "Clean extra nodes at the end of the session."), HIVE_ZOOKEEPER_CONNECTION_MAX_RETRIES("hive.zookeeper.connection.max.retries", 3, "Max number of times to retry when connecting to the ZooKeeper server."), HIVE_ZOOKEEPER_CONNECTION_BASESLEEPTIME("hive.zookeeper.connection.basesleeptime", "1000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Initial amount of time (in milliseconds) to wait between retries\n" + "when connecting to the ZooKeeper server when using ExponentialBackoffRetry policy."), // Transactions HIVE_TXN_MANAGER("hive.txn.manager", "org.apache.hadoop.hive.ql.lockmgr.DummyTxnManager", "Set to org.apache.hadoop.hive.ql.lockmgr.DbTxnManager as part of turning on Hive\n" + "transactions, which also requires appropriate settings for hive.compactor.initiator.on,\n" + "hive.compactor.worker.threads, hive.support.concurrency (true),\n" + "and hive.exec.dynamic.partition.mode (nonstrict).\n" + "The default DummyTxnManager replicates pre-Hive-0.13 behavior and provides\n" + "no transactions."), HIVE_TXN_STRICT_LOCKING_MODE("hive.txn.strict.locking.mode", true, "In strict mode non-ACID\n" + "resources use standard R/W lock semantics, e.g. INSERT will acquire exclusive lock.\n" + "In nonstrict mode, for non-ACID resources, INSERT will only acquire shared lock, which\n" + "allows two concurrent writes to the same partition but still lets lock manager prevent\n" + "DROP TABLE etc. when the table is being written to"), TXN_OVERWRITE_X_LOCK("hive.txn.xlock.iow", true, "Ensures commands with OVERWRITE (such as INSERT OVERWRITE) acquire Exclusive locks for\b" + "transactional tables. This ensures that inserts (w/o overwrite) running concurrently\n" + "are not hidden by the INSERT OVERWRITE."), /** * @deprecated Use MetastoreConf.TXN_TIMEOUT */ @Deprecated HIVE_TXN_TIMEOUT("hive.txn.timeout", "300s", new TimeValidator(TimeUnit.SECONDS), "time after which transactions are declared aborted if the client has not sent a heartbeat."), /** * @deprecated Use MetastoreConf.TXN_HEARTBEAT_THREADPOOL_SIZE */ @Deprecated HIVE_TXN_HEARTBEAT_THREADPOOL_SIZE("hive.txn.heartbeat.threadpool.size", 5, "The number of " + "threads to use for heartbeating. For Hive CLI, 1 is enough. For HiveServer2, we need a few"), TXN_MGR_DUMP_LOCK_STATE_ON_ACQUIRE_TIMEOUT("hive.txn.manager.dump.lock.state.on.acquire.timeout", false, "Set this to true so that when attempt to acquire a lock on resource times out, the current state" + " of the lock manager is dumped to log file. This is for debugging. See also " + "hive.lock.numretries and hive.lock.sleep.between.retries."), HIVE_TXN_OPERATIONAL_PROPERTIES("hive.txn.operational.properties", 1, "1: Enable split-update feature found in the newer version of Hive ACID subsystem\n" + "4: Make the table 'quarter-acid' as it only supports insert. But it doesn't require ORC or bucketing.\n" + "This is intended to be used as an internal property for future versions of ACID. (See\n" + "HIVE-14035 for details. User sets it tblproperites via transactional_properties.)", true), /** * @deprecated Use MetastoreConf.MAX_OPEN_TXNS */ @Deprecated HIVE_MAX_OPEN_TXNS("hive.max.open.txns", 100000, "Maximum number of open transactions. If \n" + "current open transactions reach this limit, future open transaction requests will be \n" + "rejected, until this number goes below the limit."), /** * @deprecated Use MetastoreConf.COUNT_OPEN_TXNS_INTERVAL */ @Deprecated HIVE_COUNT_OPEN_TXNS_INTERVAL("hive.count.open.txns.interval", "1s", new TimeValidator(TimeUnit.SECONDS), "Time in seconds between checks to count open transactions."), /** * @deprecated Use MetastoreConf.TXN_MAX_OPEN_BATCH */ @Deprecated HIVE_TXN_MAX_OPEN_BATCH("hive.txn.max.open.batch", 1000, "Maximum number of transactions that can be fetched in one call to open_txns().\n" + "This controls how many transactions streaming agents such as Flume or Storm open\n" + "simultaneously. The streaming agent then writes that number of entries into a single\n" + "file (per Flume agent or Storm bolt). Thus increasing this value decreases the number\n" + "of delta files created by streaming agents. But it also increases the number of open\n" + "transactions that Hive has to track at any given time, which may negatively affect\n" + "read performance."), /** * @deprecated Use MetastoreConf.TXN_RETRYABLE_SQLEX_REGEX */ @Deprecated HIVE_TXN_RETRYABLE_SQLEX_REGEX("hive.txn.retryable.sqlex.regex", "", "Comma separated list\n" + "of regular expression patterns for SQL state, error code, and error message of\n" + "retryable SQLExceptions, that's suitable for the metastore DB.\n" + "For example: Can't serialize.*,40001$,^Deadlock,.*ORA-08176.*\n" + "The string that the regex will be matched against is of the following form, where ex is a SQLException:\n" + "ex.getMessage() + \" (SQLState=\" + ex.getSQLState() + \", ErrorCode=\" + ex.getErrorCode() + \")\""), /** * @deprecated Use MetastoreConf.COMPACTOR_INITIATOR_ON */ @Deprecated HIVE_COMPACTOR_INITIATOR_ON("hive.compactor.initiator.on", false, "Whether to run the initiator and cleaner threads on this metastore instance or not.\n" + "Set this to true on one instance of the Thrift metastore service as part of turning\n" + "on Hive transactions. For a complete list of parameters required for turning on\n" + "transactions, see hive.txn.manager."), /** * @deprecated Use MetastoreConf.COMPACTOR_WORKER_THREADS */ @Deprecated HIVE_COMPACTOR_WORKER_THREADS("hive.compactor.worker.threads", 0, "How many compactor worker threads to run on this metastore instance. Set this to a\n" + "positive number on one or more instances of the Thrift metastore service as part of\n" + "turning on Hive transactions. For a complete list of parameters required for turning\n" + "on transactions, see hive.txn.manager.\n" + "Worker threads spawn MapReduce jobs to do compactions. They do not do the compactions\n" + "themselves. Increasing the number of worker threads will decrease the time it takes\n" + "tables or partitions to be compacted once they are determined to need compaction.\n" + "It will also increase the background load on the Hadoop cluster as more MapReduce jobs\n" + "will be running in the background."), HIVE_COMPACTOR_WORKER_TIMEOUT("hive.compactor.worker.timeout", "86400s", new TimeValidator(TimeUnit.SECONDS), "Time in seconds after which a compaction job will be declared failed and the\n" + "compaction re-queued."), HIVE_COMPACTOR_CHECK_INTERVAL("hive.compactor.check.interval", "300s", new TimeValidator(TimeUnit.SECONDS), "Time in seconds between checks to see if any tables or partitions need to be\n" + "compacted. This should be kept high because each check for compaction requires\n" + "many calls against the NameNode.\n" + "Decreasing this value will reduce the time it takes for compaction to be started\n" + "for a table or partition that requires compaction. However, checking if compaction\n" + "is needed requires several calls to the NameNode for each table or partition that\n" + "has had a transaction done on it since the last major compaction. So decreasing this\n" + "value will increase the load on the NameNode."), HIVE_COMPACTOR_DELTA_NUM_THRESHOLD("hive.compactor.delta.num.threshold", 10, "Number of delta directories in a table or partition that will trigger a minor\n" + "compaction."), HIVE_COMPACTOR_DELTA_PCT_THRESHOLD("hive.compactor.delta.pct.threshold", 0.1f, "Percentage (fractional) size of the delta files relative to the base that will trigger\n" + "a major compaction. (1.0 = 100%, so the default 0.1 = 10%.)"), COMPACTOR_MAX_NUM_DELTA("hive.compactor.max.num.delta", 500, "Maximum number of delta files that " + "the compactor will attempt to handle in a single job."), HIVE_COMPACTOR_ABORTEDTXN_THRESHOLD("hive.compactor.abortedtxn.threshold", 1000, "Number of aborted transactions involving a given table or partition that will trigger\n" + "a major compaction."), /** * @deprecated Use MetastoreConf.COMPACTOR_INITIATOR_FAILED_THRESHOLD */ @Deprecated COMPACTOR_INITIATOR_FAILED_THRESHOLD("hive.compactor.initiator.failed.compacts.threshold", 2, new RangeValidator(1, 20), "Number of consecutive compaction failures (per table/partition) " + "after which automatic compactions will not be scheduled any more. Note that this must be less " + "than hive.compactor.history.retention.failed."), HIVE_COMPACTOR_CLEANER_RUN_INTERVAL("hive.compactor.cleaner.run.interval", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Time between runs of the cleaner thread"), COMPACTOR_JOB_QUEUE("hive.compactor.job.queue", "", "Used to specify name of Hadoop queue to which\n" + "Compaction jobs will be submitted. Set to empty string to let Hadoop choose the queue."), TRANSACTIONAL_CONCATENATE_NOBLOCK("hive.transactional.concatenate.noblock", false, "Will cause 'alter table T concatenate' to be non-blocking"), HIVE_COMPACTOR_COMPACT_MM("hive.compactor.compact.insert.only", true, "Whether the compactor should compact insert-only tables. A safety switch."), /** * @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_SUCCEEDED */ @Deprecated COMPACTOR_HISTORY_RETENTION_SUCCEEDED("hive.compactor.history.retention.succeeded", 3, new RangeValidator(0, 100), "Determines how many successful compaction records will be " + "retained in compaction history for a given table/partition."), /** * @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_FAILED */ @Deprecated COMPACTOR_HISTORY_RETENTION_FAILED("hive.compactor.history.retention.failed", 3, new RangeValidator(0, 100), "Determines how many failed compaction records will be " + "retained in compaction history for a given table/partition."), /** * @deprecated Use MetastoreConf.COMPACTOR_HISTORY_RETENTION_ATTEMPTED */ @Deprecated COMPACTOR_HISTORY_RETENTION_ATTEMPTED("hive.compactor.history.retention.attempted", 2, new RangeValidator(0, 100), "Determines how many attempted compaction records will be " + "retained in compaction history for a given table/partition."), /** * @deprecated Use MetastoreConf.COMPACTOR_HISTORY_REAPER_INTERVAL */ @Deprecated COMPACTOR_HISTORY_REAPER_INTERVAL("hive.compactor.history.reaper.interval", "2m", new TimeValidator(TimeUnit.MILLISECONDS), "Determines how often compaction history reaper runs"), /** * @deprecated Use MetastoreConf.TIMEDOUT_TXN_REAPER_START */ @Deprecated HIVE_TIMEDOUT_TXN_REAPER_START("hive.timedout.txn.reaper.start", "100s", new TimeValidator(TimeUnit.MILLISECONDS), "Time delay of 1st reaper run after metastore start"), /** * @deprecated Use MetastoreConf.TIMEDOUT_TXN_REAPER_INTERVAL */ @Deprecated HIVE_TIMEDOUT_TXN_REAPER_INTERVAL("hive.timedout.txn.reaper.interval", "180s", new TimeValidator(TimeUnit.MILLISECONDS), "Time interval describing how often the reaper runs"), /** * @deprecated Use MetastoreConf.WRITE_SET_REAPER_INTERVAL */ @Deprecated WRITE_SET_REAPER_INTERVAL("hive.writeset.reaper.interval", "60s", new TimeValidator(TimeUnit.MILLISECONDS), "Frequency of WriteSet reaper runs"), MERGE_CARDINALITY_VIOLATION_CHECK("hive.merge.cardinality.check", true, "Set to true to ensure that each SQL Merge statement ensures that for each row in the target\n" + "table there is at most 1 matching row in the source table per SQL Specification."), // For Druid storage handler HIVE_DRUID_INDEXING_GRANULARITY("hive.druid.indexer.segments.granularity", "DAY", new PatternSet("YEAR", "MONTH", "WEEK", "DAY", "HOUR", "MINUTE", "SECOND"), "Granularity for the segments created by the Druid storage handler" ), HIVE_DRUID_MAX_PARTITION_SIZE("hive.druid.indexer.partition.size.max", 5000000, "Maximum number of records per segment partition" ), HIVE_DRUID_MAX_ROW_IN_MEMORY("hive.druid.indexer.memory.rownum.max", 75000, "Maximum number of records in memory while storing data in Druid" ), HIVE_DRUID_BROKER_DEFAULT_ADDRESS("hive.druid.broker.address.default", "localhost:8082", "Address of the Druid broker. If we are querying Druid from Hive, this address needs to be\n" + "declared" ), HIVE_DRUID_COORDINATOR_DEFAULT_ADDRESS("hive.druid.coordinator.address.default", "localhost:8081", "Address of the Druid coordinator. It is used to check the load status of newly created segments" ), HIVE_DRUID_OVERLORD_DEFAULT_ADDRESS("hive.druid.overlord.address.default", "localhost:8090", "Address of the Druid overlord. It is used to submit indexing tasks to druid." ), HIVE_DRUID_SELECT_THRESHOLD("hive.druid.select.threshold", 10000, "Takes only effect when hive.druid.select.distribute is set to false. \n" + "When we can split a Select query, this is the maximum number of rows that we try to retrieve\n" + "per query. In order to do that, we obtain the estimated size for the complete result. If the\n" + "number of records of the query results is larger than this threshold, we split the query in\n" + "total number of rows/threshold parts across the time dimension. Note that we assume the\n" + "records to be split uniformly across the time dimension."), HIVE_DRUID_NUM_HTTP_CONNECTION("hive.druid.http.numConnection", 20, "Number of connections used by\n" + "the HTTP client."), HIVE_DRUID_HTTP_READ_TIMEOUT("hive.druid.http.read.timeout", "PT1M", "Read timeout period for the HTTP\n" + "client in ISO8601 format (for example P2W, P3M, PT1H30M, PT0.750S), default is period of 1 minute."), HIVE_DRUID_SLEEP_TIME("hive.druid.sleep.time", "PT10S", "Sleep time between retries in ISO8601 format (for example P2W, P3M, PT1H30M, PT0.750S), default is period of 10 seconds." ), HIVE_DRUID_BASE_PERSIST_DIRECTORY("hive.druid.basePersistDirectory", "", "Local temporary directory used to persist intermediate indexing state, will default to JVM system property java.io.tmpdir." ), DRUID_SEGMENT_DIRECTORY("hive.druid.storage.storageDirectory", "/druid/segments" , "druid deep storage location."), DRUID_METADATA_BASE("hive.druid.metadata.base", "druid", "Default prefix for metadata tables"), DRUID_METADATA_DB_TYPE("hive.druid.metadata.db.type", "mysql", new PatternSet("mysql", "postgresql", "derby"), "Type of the metadata database." ), DRUID_METADATA_DB_USERNAME("hive.druid.metadata.username", "", "Username to connect to Type of the metadata DB." ), DRUID_METADATA_DB_PASSWORD("hive.druid.metadata.password", "", "Password to connect to Type of the metadata DB." ), DRUID_METADATA_DB_URI("hive.druid.metadata.uri", "", "URI to connect to the database (for example jdbc:mysql://hostname:port/DBName)." ), DRUID_WORKING_DIR("hive.druid.working.directory", "/tmp/workingDirectory", "Default hdfs working directory used to store some intermediate metadata" ), HIVE_DRUID_MAX_TRIES("hive.druid.maxTries", 5, "Maximum number of retries before giving up"), HIVE_DRUID_PASSIVE_WAIT_TIME("hive.druid.passiveWaitTimeMs", 30000L, "Wait time in ms default to 30 seconds." ), HIVE_DRUID_BITMAP_FACTORY_TYPE("hive.druid.bitmap.type", "roaring", new PatternSet("roaring", "concise"), "Coding algorithm use to encode the bitmaps"), // For HBase storage handler HIVE_HBASE_WAL_ENABLED("hive.hbase.wal.enabled", true, "Whether writes to HBase should be forced to the write-ahead log. \n" + "Disabling this improves HBase write performance at the risk of lost writes in case of a crash."), HIVE_HBASE_GENERATE_HFILES("hive.hbase.generatehfiles", false, "True when HBaseStorageHandler should generate hfiles instead of operate against the online table."), HIVE_HBASE_SNAPSHOT_NAME("hive.hbase.snapshot.name", null, "The HBase table snapshot name to use."), HIVE_HBASE_SNAPSHOT_RESTORE_DIR("hive.hbase.snapshot.restoredir", "/tmp", "The directory in which to " + "restore the HBase table snapshot."), // For har files HIVEARCHIVEENABLED("hive.archive.enabled", false, "Whether archiving operations are permitted"), HIVEFETCHTASKCONVERSION("hive.fetch.task.conversion", "more", new StringSet("none", "minimal", "more"), "Some select queries can be converted to single FETCH task minimizing latency.\n" + "Currently the query should be single sourced not having any subquery and should not have\n" + "any aggregations or distincts (which incurs RS), lateral views and joins.\n" + "0. none : disable hive.fetch.task.conversion\n" + "1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only\n" + "2. more : SELECT, FILTER, LIMIT only (support TABLESAMPLE and virtual columns)" ), HIVEFETCHTASKCONVERSIONTHRESHOLD("hive.fetch.task.conversion.threshold", 1073741824L, "Input threshold for applying hive.fetch.task.conversion. If target table is native, input length\n" + "is calculated by summation of file lengths. If it's not native, storage handler for the table\n" + "can optionally implement org.apache.hadoop.hive.ql.metadata.InputEstimator interface."), HIVEFETCHTASKAGGR("hive.fetch.task.aggr", false, "Aggregation queries with no group-by clause (for example, select count(*) from src) execute\n" + "final aggregations in single reduce task. If this is set true, Hive delegates final aggregation\n" + "stage to fetch task, possibly decreasing the query time."), HIVEOPTIMIZEMETADATAQUERIES("hive.compute.query.using.stats", true, "When set to true Hive will answer a few queries like count(1) purely using stats\n" + "stored in metastore. For basic stats collection turn on the config hive.stats.autogather to true.\n" + "For more advanced stats collection need to run analyze table queries."), // Serde for FetchTask HIVEFETCHOUTPUTSERDE("hive.fetch.output.serde", "org.apache.hadoop.hive.serde2.DelimitedJSONSerDe", "The SerDe used by FetchTask to serialize the fetch output."), HIVEEXPREVALUATIONCACHE("hive.cache.expr.evaluation", true, "If true, the evaluation result of a deterministic expression referenced twice or more\n" + "will be cached.\n" + "For example, in a filter condition like '.. where key + 10 = 100 or key + 10 = 0'\n" + "the expression 'key + 10' will be evaluated/cached once and reused for the following\n" + "expression ('key + 10 = 0'). Currently, this is applied only to expressions in select\n" + "or filter operators."), // Hive Variables HIVEVARIABLESUBSTITUTE("hive.variable.substitute", true, "This enables substitution using syntax like ${var} ${system:var} and ${env:var}."), HIVEVARIABLESUBSTITUTEDEPTH("hive.variable.substitute.depth", 40, "The maximum replacements the substitution engine will do."), HIVECONFVALIDATION("hive.conf.validation", true, "Enables type checking for registered Hive configurations"), SEMANTIC_ANALYZER_HOOK("hive.semantic.analyzer.hook", "", ""), HIVE_TEST_AUTHORIZATION_SQLSTD_HS2_MODE( "hive.test.authz.sstd.hs2.mode", false, "test hs2 mode from .q tests", true), HIVE_AUTHORIZATION_ENABLED("hive.security.authorization.enabled", false, "enable or disable the Hive client authorization"), HIVE_AUTHORIZATION_MANAGER("hive.security.authorization.manager", "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactory", "The Hive client authorization manager class name. The user defined authorization class should implement \n" + "interface org.apache.hadoop.hive.ql.security.authorization.HiveAuthorizationProvider."), HIVE_AUTHENTICATOR_MANAGER("hive.security.authenticator.manager", "org.apache.hadoop.hive.ql.security.HadoopDefaultAuthenticator", "hive client authenticator manager class name. The user defined authenticator should implement \n" + "interface org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider."), HIVE_METASTORE_AUTHORIZATION_MANAGER("hive.security.metastore.authorization.manager", "org.apache.hadoop.hive.ql.security.authorization.DefaultHiveMetastoreAuthorizationProvider", "Names of authorization manager classes (comma separated) to be used in the metastore\n" + "for authorization. The user defined authorization class should implement interface\n" + "org.apache.hadoop.hive.ql.security.authorization.HiveMetastoreAuthorizationProvider.\n" + "All authorization manager classes have to successfully authorize the metastore API\n" + "call for the command execution to be allowed."), HIVE_METASTORE_AUTHORIZATION_AUTH_READS("hive.security.metastore.authorization.auth.reads", true, "If this is true, metastore authorizer authorizes read actions on database, table"), HIVE_METASTORE_AUTHENTICATOR_MANAGER("hive.security.metastore.authenticator.manager", "org.apache.hadoop.hive.ql.security.HadoopDefaultMetastoreAuthenticator", "authenticator manager class name to be used in the metastore for authentication. \n" + "The user defined authenticator should implement interface org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider."), HIVE_AUTHORIZATION_TABLE_USER_GRANTS("hive.security.authorization.createtable.user.grants", "", "the privileges automatically granted to some users whenever a table gets created.\n" + "An example like \"userX,userY:select;userZ:create\" will grant select privilege to userX and userY,\n" + "and grant create privilege to userZ whenever a new table created."), HIVE_AUTHORIZATION_TABLE_GROUP_GRANTS("hive.security.authorization.createtable.group.grants", "", "the privileges automatically granted to some groups whenever a table gets created.\n" + "An example like \"groupX,groupY:select;groupZ:create\" will grant select privilege to groupX and groupY,\n" + "and grant create privilege to groupZ whenever a new table created."), HIVE_AUTHORIZATION_TABLE_ROLE_GRANTS("hive.security.authorization.createtable.role.grants", "", "the privileges automatically granted to some roles whenever a table gets created.\n" + "An example like \"roleX,roleY:select;roleZ:create\" will grant select privilege to roleX and roleY,\n" + "and grant create privilege to roleZ whenever a new table created."), HIVE_AUTHORIZATION_TABLE_OWNER_GRANTS("hive.security.authorization.createtable.owner.grants", "", "The privileges automatically granted to the owner whenever a table gets created.\n" + "An example like \"select,drop\" will grant select and drop privilege to the owner\n" + "of the table. Note that the default gives the creator of a table no access to the\n" + "table (but see HIVE-8067)."), HIVE_AUTHORIZATION_TASK_FACTORY("hive.security.authorization.task.factory", "org.apache.hadoop.hive.ql.parse.authorization.HiveAuthorizationTaskFactoryImpl", "Authorization DDL task factory implementation"), // if this is not set default value is set during config initialization // Default value can't be set in this constructor as it would refer names in other ConfVars // whose constructor would not have been called HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST( "hive.security.authorization.sqlstd.confwhitelist", "", "A Java regex. Configurations parameters that match this\n" + "regex can be modified by user when SQL standard authorization is enabled.\n" + "To get the default value, use the 'set <param>' command.\n" + "Note that the hive.conf.restricted.list checks are still enforced after the white list\n" + "check"), HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST_APPEND( "hive.security.authorization.sqlstd.confwhitelist.append", "", "2nd Java regex that it would match in addition to\n" + "hive.security.authorization.sqlstd.confwhitelist.\n" + "Do not include a starting \"|\" in the value. Using this regex instead\n" + "of updating the original regex means that you can append to the default\n" + "set by SQL standard authorization instead of replacing it entirely."), HIVE_CLI_PRINT_HEADER("hive.cli.print.header", false, "Whether to print the names of the columns in query output."), HIVE_CLI_PRINT_ESCAPE_CRLF("hive.cli.print.escape.crlf", false, "Whether to print carriage returns and line feeds in row output as escaped \\r and \\n"), HIVE_CLI_TEZ_SESSION_ASYNC("hive.cli.tez.session.async", true, "Whether to start Tez\n" + "session in background when running CLI with Tez, allowing CLI to be available earlier."), HIVE_DISABLE_UNSAFE_EXTERNALTABLE_OPERATIONS("hive.disable.unsafe.external.table.operations", true, "Whether to disable certain optimizations and operations on external tables," + " on the assumption that data changes by external applications may have negative effects" + " on these operations."), HIVE_ERROR_ON_EMPTY_PARTITION("hive.error.on.empty.partition", false, "Whether to throw an exception if dynamic partition insert generates empty results."), HIVE_EXIM_URI_SCHEME_WL("hive.exim.uri.scheme.whitelist", "hdfs,pfile,file,s3,s3a", "A comma separated list of acceptable URI schemes for import and export."), // temporary variable for testing. This is added just to turn off this feature in case of a bug in // deployment. It has not been documented in hive-default.xml intentionally, this should be removed // once the feature is stable HIVE_EXIM_RESTRICT_IMPORTS_INTO_REPLICATED_TABLES("hive.exim.strict.repl.tables",true, "Parameter that determines if 'regular' (non-replication) export dumps can be\n" + "imported on to tables that are the target of replication. If this parameter is\n" + "set, regular imports will check if the destination table(if it exists) has a " + "'repl.last.id' set on it. If so, it will fail."), HIVE_REPL_TASK_FACTORY("hive.repl.task.factory", "org.apache.hive.hcatalog.api.repl.exim.EximReplicationTaskFactory", "Parameter that can be used to override which ReplicationTaskFactory will be\n" + "used to instantiate ReplicationTask events. Override for third party repl plugins"), HIVE_MAPPER_CANNOT_SPAN_MULTIPLE_PARTITIONS("hive.mapper.cannot.span.multiple.partitions", false, ""), HIVE_REWORK_MAPREDWORK("hive.rework.mapredwork", false, "should rework the mapred work or not.\n" + "This is first introduced by SymlinkTextInputFormat to replace symlink files with real paths at compile time."), HIVE_IO_EXCEPTION_HANDLERS("hive.io.exception.handlers", "", "A list of io exception handler class names. This is used\n" + "to construct a list exception handlers to handle exceptions thrown\n" + "by record readers"), // logging configuration HIVE_LOG4J_FILE("hive.log4j.file", "", "Hive log4j configuration file.\n" + "If the property is not set, then logging will be initialized using hive-log4j2.properties found on the classpath.\n" + "If the property is set, the value must be a valid URI (java.net.URI, e.g. \"file:///tmp/my-logging.xml\"), \n" + "which you can then extract a URL from and pass to PropertyConfigurator.configure(URL)."), HIVE_EXEC_LOG4J_FILE("hive.exec.log4j.file", "", "Hive log4j configuration file for execution mode(sub command).\n" + "If the property is not set, then logging will be initialized using hive-exec-log4j2.properties found on the classpath.\n" + "If the property is set, the value must be a valid URI (java.net.URI, e.g. \"file:///tmp/my-logging.xml\"), \n" + "which you can then extract a URL from and pass to PropertyConfigurator.configure(URL)."), HIVE_ASYNC_LOG_ENABLED("hive.async.log.enabled", true, "Whether to enable Log4j2's asynchronous logging. Asynchronous logging can give\n" + " significant performance improvement as logging will be handled in separate thread\n" + " that uses LMAX disruptor queue for buffering log messages.\n" + " Refer https://logging.apache.org/log4j/2.x/manual/async.html for benefits and\n" + " drawbacks."), HIVE_LOG_EXPLAIN_OUTPUT("hive.log.explain.output", false, "Whether to log explain output for every query.\n" + "When enabled, will log EXPLAIN EXTENDED output for the query at INFO log4j log level\n" + "and in WebUI / Drilldown / Show Query."), HIVE_EXPLAIN_USER("hive.explain.user", true, "Whether to show explain result at user level.\n" + "When enabled, will log EXPLAIN output for the query at user level. Tez only."), HIVE_SPARK_EXPLAIN_USER("hive.spark.explain.user", false, "Whether to show explain result at user level.\n" + "When enabled, will log EXPLAIN output for the query at user level. Spark only."), // prefix used to auto generated column aliases (this should be started with '_') HIVE_AUTOGEN_COLUMNALIAS_PREFIX_LABEL("hive.autogen.columnalias.prefix.label", "_c", "String used as a prefix when auto generating column alias.\n" + "By default the prefix label will be appended with a column position number to form the column alias. \n" + "Auto generation would happen if an aggregate function is used in a select clause without an explicit alias."), HIVE_AUTOGEN_COLUMNALIAS_PREFIX_INCLUDEFUNCNAME( "hive.autogen.columnalias.prefix.includefuncname", false, "Whether to include function name in the column alias auto generated by Hive."), HIVE_METRICS_CLASS("hive.service.metrics.class", "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics", new StringSet( "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics", "org.apache.hadoop.hive.common.metrics.LegacyMetrics"), "Hive metrics subsystem implementation class."), HIVE_CODAHALE_METRICS_REPORTER_CLASSES("hive.service.metrics.codahale.reporter.classes", "org.apache.hadoop.hive.common.metrics.metrics2.JsonFileMetricsReporter, " + "org.apache.hadoop.hive.common.metrics.metrics2.JmxMetricsReporter", "Comma separated list of reporter implementation classes for metric class " + "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics. Overrides " + "HIVE_METRICS_REPORTER conf if present"), @Deprecated HIVE_METRICS_REPORTER("hive.service.metrics.reporter", "", "Reporter implementations for metric class " + "org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics;" + "Deprecated, use HIVE_CODAHALE_METRICS_REPORTER_CLASSES instead. This configuraiton will be" + " overridden by HIVE_CODAHALE_METRICS_REPORTER_CLASSES if present. " + "Comma separated list of JMX, CONSOLE, JSON_FILE, HADOOP2"), HIVE_METRICS_JSON_FILE_LOCATION("hive.service.metrics.file.location", "/tmp/report.json", "For metric class org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics JSON_FILE reporter, the location of local JSON metrics file. " + "This file will get overwritten at every interval."), HIVE_METRICS_JSON_FILE_INTERVAL("hive.service.metrics.file.frequency", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "For metric class org.apache.hadoop.hive.common.metrics.metrics2.JsonFileMetricsReporter, " + "the frequency of updating JSON metrics file."), HIVE_METRICS_HADOOP2_INTERVAL("hive.service.metrics.hadoop2.frequency", "30s", new TimeValidator(TimeUnit.SECONDS), "For metric class org.apache.hadoop.hive.common.metrics.metrics2.Metrics2Reporter, " + "the frequency of updating the HADOOP2 metrics system."), HIVE_METRICS_HADOOP2_COMPONENT_NAME("hive.service.metrics.hadoop2.component", "hive", "Component name to provide to Hadoop2 Metrics system. Ideally 'hivemetastore' for the MetaStore " + " and and 'hiveserver2' for HiveServer2." ), HIVE_PERF_LOGGER("hive.exec.perf.logger", "org.apache.hadoop.hive.ql.log.PerfLogger", "The class responsible for logging client side performance metrics. \n" + "Must be a subclass of org.apache.hadoop.hive.ql.log.PerfLogger"), HIVE_START_CLEANUP_SCRATCHDIR("hive.start.cleanup.scratchdir", false, "To cleanup the Hive scratchdir when starting the Hive Server"), HIVE_SCRATCH_DIR_LOCK("hive.scratchdir.lock", false, "To hold a lock file in scratchdir to prevent to be removed by cleardanglingscratchdir"), HIVE_INSERT_INTO_MULTILEVEL_DIRS("hive.insert.into.multilevel.dirs", false, "Where to insert into multilevel directories like\n" + "\"insert directory '/HIVEFT25686/chinna/' from table\""), HIVE_WAREHOUSE_SUBDIR_INHERIT_PERMS("hive.warehouse.subdir.inherit.perms", false, "Set this to false if the table directories should be created\n" + "with the permissions derived from dfs umask instead of\n" + "inheriting the permission of the warehouse or database directory."), HIVE_INSERT_INTO_EXTERNAL_TABLES("hive.insert.into.external.tables", true, "whether insert into external tables is allowed"), HIVE_TEMPORARY_TABLE_STORAGE( "hive.exec.temporary.table.storage", "default", new StringSet("memory", "ssd", "default"), "Define the storage policy for temporary tables." + "Choices between memory, ssd and default"), HIVE_QUERY_LIFETIME_HOOKS("hive.query.lifetime.hooks", "", "A comma separated list of hooks which implement QueryLifeTimeHook. These will be triggered" + " before/after query compilation and before/after query execution, in the order specified." + "Implementations of QueryLifeTimeHookWithParseHooks can also be specified in this list. If they are" + "specified then they will be invoked in the same places as QueryLifeTimeHooks and will be invoked during pre " + "and post query parsing"), HIVE_DRIVER_RUN_HOOKS("hive.exec.driver.run.hooks", "", "A comma separated list of hooks which implement HiveDriverRunHook. Will be run at the beginning " + "and end of Driver.run, these will be run in the order specified."), HIVE_DDL_OUTPUT_FORMAT("hive.ddl.output.format", null, "The data format to use for DDL output. One of \"text\" (for human\n" + "readable text) or \"json\" (for a json object)."), HIVE_ENTITY_SEPARATOR("hive.entity.separator", "@", "Separator used to construct names of tables and partitions. For example, dbname@tablename@partitionname"), HIVE_CAPTURE_TRANSFORM_ENTITY("hive.entity.capture.transform", false, "Compiler to capture transform URI referred in the query"), HIVE_DISPLAY_PARTITION_COLUMNS_SEPARATELY("hive.display.partition.cols.separately", true, "In older Hive version (0.10 and earlier) no distinction was made between\n" + "partition columns or non-partition columns while displaying columns in describe\n" + "table. From 0.12 onwards, they are displayed separately. This flag will let you\n" + "get old behavior, if desired. See, test-case in patch for HIVE-6689."), HIVE_HTTPS_SSL_PROTOCOL_BLACKLIST("hive.https.ssl.protocol.blacklist", "SSLv2,SSLv3", "SSL Versions to disable for all Hive Servers"), HIVE_PRIVILEGE_SYNCHRONIZER("hive.privilege.synchronizer", false, "Synchronize privileges from external authorizer such as ranger to Hive periodically in HS2"), HIVE_PRIVILEGE_SYNCHRONIZER_INTERVAL("hive.privilege.synchronizer.interval", "1800s", new TimeValidator(TimeUnit.SECONDS), "Interval to synchronize privileges from external authorizer periodically in HS2"), // HiveServer2 specific configs HIVE_SERVER2_CLEAR_DANGLING_SCRATCH_DIR("hive.server2.clear.dangling.scratchdir", false, "Clear dangling scratch dir periodically in HS2"), HIVE_SERVER2_CLEAR_DANGLING_SCRATCH_DIR_INTERVAL("hive.server2.clear.dangling.scratchdir.interval", "1800s", new TimeValidator(TimeUnit.SECONDS), "Interval to clear dangling scratch dir periodically in HS2"), HIVE_SERVER2_SLEEP_INTERVAL_BETWEEN_START_ATTEMPTS("hive.server2.sleep.interval.between.start.attempts", "60s", new TimeValidator(TimeUnit.MILLISECONDS, 0l, true, Long.MAX_VALUE, true), "Amount of time to sleep between HiveServer2 start attempts. Primarily meant for tests"), HIVE_SERVER2_MAX_START_ATTEMPTS("hive.server2.max.start.attempts", 30L, new RangeValidator(0L, null), "Number of times HiveServer2 will attempt to start before exiting. The sleep interval between retries" + " is determined by " + ConfVars.HIVE_SERVER2_SLEEP_INTERVAL_BETWEEN_START_ATTEMPTS.varname + "\n The default of 30 will keep trying for 30 minutes."), HIVE_SERVER2_SUPPORT_DYNAMIC_SERVICE_DISCOVERY("hive.server2.support.dynamic.service.discovery", false, "Whether HiveServer2 supports dynamic service discovery for its clients. " + "To support this, each instance of HiveServer2 currently uses ZooKeeper to register itself, " + "when it is brought up. JDBC/ODBC clients should use the ZooKeeper ensemble: " + "hive.zookeeper.quorum in their connection string."), HIVE_SERVER2_ZOOKEEPER_NAMESPACE("hive.server2.zookeeper.namespace", "hiveserver2", "The parent node in ZooKeeper used by HiveServer2 when supporting dynamic service discovery."), HIVE_SERVER2_ZOOKEEPER_PUBLISH_CONFIGS("hive.server2.zookeeper.publish.configs", true, "Whether we should publish HiveServer2's configs to ZooKeeper."), // HiveServer2 global init file location HIVE_SERVER2_GLOBAL_INIT_FILE_LOCATION("hive.server2.global.init.file.location", "${env:HIVE_CONF_DIR}", "Either the location of a HS2 global init file or a directory containing a .hiverc file. If the \n" + "property is set, the value must be a valid path to an init file or directory where the init file is located."), HIVE_SERVER2_TRANSPORT_MODE("hive.server2.transport.mode", "binary", new StringSet("binary", "http"), "Transport mode of HiveServer2."), HIVE_SERVER2_THRIFT_BIND_HOST("hive.server2.thrift.bind.host", "", "Bind host on which to run the HiveServer2 Thrift service."), HIVE_SERVER2_PARALLEL_COMPILATION("hive.driver.parallel.compilation", false, "Whether to\n" + "enable parallel compilation of the queries between sessions and within the same session on HiveServer2. The default is false."), HIVE_SERVER2_COMPILE_LOCK_TIMEOUT("hive.server2.compile.lock.timeout", "0s", new TimeValidator(TimeUnit.SECONDS), "Number of seconds a request will wait to acquire the compile lock before giving up. " + "Setting it to 0s disables the timeout."), HIVE_SERVER2_PARALLEL_OPS_IN_SESSION("hive.server2.parallel.ops.in.session", true, "Whether to allow several parallel operations (such as SQL statements) in one session."), HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL("hive.server2.materializedviews.registry.impl", "DEFAULT", new StringSet("DEFAULT", "DUMMY"), "The implementation that we should use for the materialized views registry. \n" + " DEFAULT: Default cache for materialized views\n" + " DUMMY: Do not cache materialized views and hence forward requests to metastore"), // HiveServer2 WebUI HIVE_SERVER2_WEBUI_BIND_HOST("hive.server2.webui.host", "0.0.0.0", "The host address the HiveServer2 WebUI will listen on"), HIVE_SERVER2_WEBUI_PORT("hive.server2.webui.port", 10002, "The port the HiveServer2 WebUI will listen on. This can be" + "set to 0 or a negative integer to disable the web UI"), HIVE_SERVER2_WEBUI_MAX_THREADS("hive.server2.webui.max.threads", 50, "The max HiveServer2 WebUI threads"), HIVE_SERVER2_WEBUI_USE_SSL("hive.server2.webui.use.ssl", false, "Set this to true for using SSL encryption for HiveServer2 WebUI."), HIVE_SERVER2_WEBUI_SSL_KEYSTORE_PATH("hive.server2.webui.keystore.path", "", "SSL certificate keystore location for HiveServer2 WebUI."), HIVE_SERVER2_WEBUI_SSL_KEYSTORE_PASSWORD("hive.server2.webui.keystore.password", "", "SSL certificate keystore password for HiveServer2 WebUI."), HIVE_SERVER2_WEBUI_USE_SPNEGO("hive.server2.webui.use.spnego", false, "If true, the HiveServer2 WebUI will be secured with SPNEGO. Clients must authenticate with Kerberos."), HIVE_SERVER2_WEBUI_SPNEGO_KEYTAB("hive.server2.webui.spnego.keytab", "", "The path to the Kerberos Keytab file containing the HiveServer2 WebUI SPNEGO service principal."), HIVE_SERVER2_WEBUI_SPNEGO_PRINCIPAL("hive.server2.webui.spnego.principal", "HTTP/[email protected]", "The HiveServer2 WebUI SPNEGO service principal.\n" + "The special string _HOST will be replaced automatically with \n" + "the value of hive.server2.webui.host or the correct host name."), HIVE_SERVER2_WEBUI_MAX_HISTORIC_QUERIES("hive.server2.webui.max.historic.queries", 25, "The maximum number of past queries to show in HiverSever2 WebUI."), HIVE_SERVER2_WEBUI_USE_PAM("hive.server2.webui.use.pam", false, "If true, the HiveServer2 WebUI will be secured with PAM."), HIVE_SERVER2_WEBUI_ENABLE_CORS("hive.server2.webui.enable.cors", false, "Whether to enable cross origin requests (CORS)\n"), HIVE_SERVER2_WEBUI_CORS_ALLOWED_ORIGINS("hive.server2.webui.cors.allowed.origins", "*", "Comma separated list of origins that are allowed when CORS is enabled.\n"), HIVE_SERVER2_WEBUI_CORS_ALLOWED_METHODS("hive.server2.webui.cors.allowed.methods", "GET,POST,DELETE,HEAD", "Comma separated list of http methods that are allowed when CORS is enabled.\n"), HIVE_SERVER2_WEBUI_CORS_ALLOWED_HEADERS("hive.server2.webui.cors.allowed.headers", "X-Requested-With,Content-Type,Accept,Origin", "Comma separated list of http headers that are allowed when CORS is enabled.\n"), // Tez session settings HIVE_SERVER2_ACTIVE_PASSIVE_HA_ENABLE("hive.server2.active.passive.ha.enable", false, "Whether HiveServer2 Active/Passive High Availability be enabled when Hive Interactive sessions are enabled." + "This will also require hive.server2.support.dynamic.service.discovery to be enabled."), HIVE_SERVER2_ACTIVE_PASSIVE_HA_REGISTRY_NAMESPACE("hive.server2.active.passive.ha.registry.namespace", "hs2ActivePassiveHA", "When HiveServer2 Active/Passive High Availability is enabled, uses this namespace for registering HS2\n" + "instances with zookeeper"), HIVE_SERVER2_TEZ_INTERACTIVE_QUEUE("hive.server2.tez.interactive.queue", "", "A single YARN queues to use for Hive Interactive sessions. When this is specified,\n" + "workload management is enabled and used for these sessions."), HIVE_SERVER2_WM_WORKER_THREADS("hive.server2.wm.worker.threads", 4, "Number of worker threads to use to perform the synchronous operations with Tez\n" + "sessions for workload management (e.g. opening, closing, etc.)"), HIVE_SERVER2_WM_ALLOW_ANY_POOL_VIA_JDBC("hive.server2.wm.allow.any.pool.via.jdbc", false, "Applies when a user specifies a target WM pool in the JDBC connection string. If\n" + "false, the user can only specify a pool he is mapped to (e.g. make a choice among\n" + "multiple group mappings); if true, the user can specify any existing pool."), HIVE_SERVER2_WM_POOL_METRICS("hive.server2.wm.pool.metrics", true, "Whether per-pool WM metrics should be enabled."), HIVE_SERVER2_TEZ_WM_AM_REGISTRY_TIMEOUT("hive.server2.tez.wm.am.registry.timeout", "30s", new TimeValidator(TimeUnit.SECONDS), "The timeout for AM registry registration, after which (on attempting to use the\n" + "session), we kill it and try to get another one."), HIVE_SERVER2_TEZ_DEFAULT_QUEUES("hive.server2.tez.default.queues", "", "A list of comma separated values corresponding to YARN queues of the same name.\n" + "When HiveServer2 is launched in Tez mode, this configuration needs to be set\n" + "for multiple Tez sessions to run in parallel on the cluster."), HIVE_SERVER2_TEZ_SESSIONS_PER_DEFAULT_QUEUE("hive.server2.tez.sessions.per.default.queue", 1, "A positive integer that determines the number of Tez sessions that should be\n" + "launched on each of the queues specified by \"hive.server2.tez.default.queues\".\n" + "Determines the parallelism on each queue."), HIVE_SERVER2_TEZ_INITIALIZE_DEFAULT_SESSIONS("hive.server2.tez.initialize.default.sessions", false, "This flag is used in HiveServer2 to enable a user to use HiveServer2 without\n" + "turning on Tez for HiveServer2. The user could potentially want to run queries\n" + "over Tez without the pool of sessions."), HIVE_SERVER2_TEZ_QUEUE_ACCESS_CHECK("hive.server2.tez.queue.access.check", false, "Whether to check user access to explicitly specified YARN queues. " + "yarn.resourcemanager.webapp.address must be configured to use this."), HIVE_SERVER2_TEZ_SESSION_LIFETIME("hive.server2.tez.session.lifetime", "162h", new TimeValidator(TimeUnit.HOURS), "The lifetime of the Tez sessions launched by HS2 when default sessions are enabled.\n" + "Set to 0 to disable session expiration."), HIVE_SERVER2_TEZ_SESSION_LIFETIME_JITTER("hive.server2.tez.session.lifetime.jitter", "3h", new TimeValidator(TimeUnit.HOURS), "The jitter for Tez session lifetime; prevents all the sessions from restarting at once."), HIVE_SERVER2_TEZ_SESSION_MAX_INIT_THREADS("hive.server2.tez.sessions.init.threads", 16, "If hive.server2.tez.initialize.default.sessions is enabled, the maximum number of\n" + "threads to use to initialize the default sessions."), HIVE_SERVER2_TEZ_SESSION_RESTRICTED_CONFIGS("hive.server2.tez.sessions.restricted.configs", "", "The configuration settings that cannot be set when submitting jobs to HiveServer2. If\n" + "any of these are set to values different from those in the server configuration, an\n" + "exception will be thrown."), HIVE_SERVER2_TEZ_SESSION_CUSTOM_QUEUE_ALLOWED("hive.server2.tez.sessions.custom.queue.allowed", "true", new StringSet("true", "false", "ignore"), "Whether Tez session pool should allow submitting queries to custom queues. The options\n" + "are true, false (error out), ignore (accept the query but ignore the queue setting)."), // Operation log configuration HIVE_SERVER2_LOGGING_OPERATION_ENABLED("hive.server2.logging.operation.enabled", true, "When true, HS2 will save operation logs and make them available for clients"), HIVE_SERVER2_LOGGING_OPERATION_LOG_LOCATION("hive.server2.logging.operation.log.location", "${system:java.io.tmpdir}" + File.separator + "${system:user.name}" + File.separator + "operation_logs", "Top level directory where operation logs are stored if logging functionality is enabled"), HIVE_SERVER2_LOGGING_OPERATION_LEVEL("hive.server2.logging.operation.level", "EXECUTION", new StringSet("NONE", "EXECUTION", "PERFORMANCE", "VERBOSE"), "HS2 operation logging mode available to clients to be set at session level.\n" + "For this to work, hive.server2.logging.operation.enabled should be set to true.\n" + " NONE: Ignore any logging\n" + " EXECUTION: Log completion of tasks\n" + " PERFORMANCE: Execution + Performance logs \n" + " VERBOSE: All logs" ), HIVE_SERVER2_OPERATION_LOG_CLEANUP_DELAY("hive.server2.operation.log.cleanup.delay", "300s", new TimeValidator(TimeUnit.SECONDS), "When a query is cancelled (via kill query, query timeout or triggers),\n" + " operation logs gets cleaned up after this delay"), // HS2 connections guard rails HIVE_SERVER2_LIMIT_CONNECTIONS_PER_USER("hive.server2.limit.connections.per.user", 0, "Maximum hive server2 connections per user. Any user exceeding this limit will not be allowed to connect. " + "Default=0 does not enforce limits."), HIVE_SERVER2_LIMIT_CONNECTIONS_PER_IPADDRESS("hive.server2.limit.connections.per.ipaddress", 0, "Maximum hive server2 connections per ipaddress. Any ipaddress exceeding this limit will not be allowed " + "to connect. Default=0 does not enforce limits."), HIVE_SERVER2_LIMIT_CONNECTIONS_PER_USER_IPADDRESS("hive.server2.limit.connections.per.user.ipaddress", 0, "Maximum hive server2 connections per user:ipaddress combination. Any user-ipaddress exceeding this limit will " + "not be allowed to connect. Default=0 does not enforce limits."), // Enable metric collection for HiveServer2 HIVE_SERVER2_METRICS_ENABLED("hive.server2.metrics.enabled", false, "Enable metrics on the HiveServer2."), // http (over thrift) transport settings HIVE_SERVER2_THRIFT_HTTP_PORT("hive.server2.thrift.http.port", 10001, "Port number of HiveServer2 Thrift interface when hive.server2.transport.mode is 'http'."), HIVE_SERVER2_THRIFT_HTTP_PATH("hive.server2.thrift.http.path", "cliservice", "Path component of URL endpoint when in HTTP mode."), HIVE_SERVER2_THRIFT_MAX_MESSAGE_SIZE("hive.server2.thrift.max.message.size", 100*1024*1024, "Maximum message size in bytes a HS2 server will accept."), HIVE_SERVER2_THRIFT_HTTP_MAX_IDLE_TIME("hive.server2.thrift.http.max.idle.time", "1800s", new TimeValidator(TimeUnit.MILLISECONDS), "Maximum idle time for a connection on the server when in HTTP mode."), HIVE_SERVER2_THRIFT_HTTP_WORKER_KEEPALIVE_TIME("hive.server2.thrift.http.worker.keepalive.time", "60s", new TimeValidator(TimeUnit.SECONDS), "Keepalive time for an idle http worker thread. When the number of workers exceeds min workers, " + "excessive threads are killed after this time interval."), HIVE_SERVER2_THRIFT_HTTP_REQUEST_HEADER_SIZE("hive.server2.thrift.http.request.header.size", 6*1024, "Request header size in bytes, when using HTTP transport mode. Jetty defaults used."), HIVE_SERVER2_THRIFT_HTTP_RESPONSE_HEADER_SIZE("hive.server2.thrift.http.response.header.size", 6*1024, "Response header size in bytes, when using HTTP transport mode. Jetty defaults used."), HIVE_SERVER2_THRIFT_HTTP_COMPRESSION_ENABLED("hive.server2.thrift.http.compression.enabled", true, "Enable thrift http compression via Jetty compression support"), // Cookie based authentication when using HTTP Transport HIVE_SERVER2_THRIFT_HTTP_COOKIE_AUTH_ENABLED("hive.server2.thrift.http.cookie.auth.enabled", true, "When true, HiveServer2 in HTTP transport mode, will use cookie based authentication mechanism."), HIVE_SERVER2_THRIFT_HTTP_COOKIE_MAX_AGE("hive.server2.thrift.http.cookie.max.age", "86400s", new TimeValidator(TimeUnit.SECONDS), "Maximum age in seconds for server side cookie used by HS2 in HTTP mode."), HIVE_SERVER2_THRIFT_HTTP_COOKIE_DOMAIN("hive.server2.thrift.http.cookie.domain", null, "Domain for the HS2 generated cookies"), HIVE_SERVER2_THRIFT_HTTP_COOKIE_PATH("hive.server2.thrift.http.cookie.path", null, "Path for the HS2 generated cookies"), @Deprecated HIVE_SERVER2_THRIFT_HTTP_COOKIE_IS_SECURE("hive.server2.thrift.http.cookie.is.secure", true, "Deprecated: Secure attribute of the HS2 generated cookie (this is automatically enabled for SSL enabled HiveServer2)."), HIVE_SERVER2_THRIFT_HTTP_COOKIE_IS_HTTPONLY("hive.server2.thrift.http.cookie.is.httponly", true, "HttpOnly attribute of the HS2 generated cookie."), // binary transport settings HIVE_SERVER2_THRIFT_PORT("hive.server2.thrift.port", 10000, "Port number of HiveServer2 Thrift interface when hive.server2.transport.mode is 'binary'."), HIVE_SERVER2_THRIFT_PORT_2WSSL("hive.server2.thrift.port.ssl", 9999, "Port number of HiveServer2 Thrift interface when hive.server2.transport.mode is 'binary' and SSL two way."), HIVE_LOAD_SSL_SERVER("hive.load.ssl-server", false, "True to load the ssl-server.xml from the classpath"), HIVE_SERVER2_THRIFT_SASL_QOP("hive.server2.thrift.sasl.qop", "auth", new StringSet("auth", "auth-int", "auth-conf"), "Sasl QOP value; set it to one of following values to enable higher levels of\n" + "protection for HiveServer2 communication with clients.\n" + "Setting hadoop.rpc.protection to a higher level than HiveServer2 does not\n" + "make sense in most situations. HiveServer2 ignores hadoop.rpc.protection in favor\n" + "of hive.server2.thrift.sasl.qop.\n" + " \"auth\" - authentication only (default)\n" + " \"auth-int\" - authentication plus integrity protection\n" + " \"auth-conf\" - authentication plus integrity and confidentiality protection\n" + "This is applicable only if HiveServer2 is configured to use Kerberos authentication."), HIVE_SERVER2_THRIFT_MIN_WORKER_THREADS("hive.server2.thrift.min.worker.threads", 5, "Minimum number of Thrift worker threads"), HIVE_SERVER2_THRIFT_MAX_WORKER_THREADS("hive.server2.thrift.max.worker.threads", 500, "Maximum number of Thrift worker threads"), HIVE_SERVER2_THRIFT_LOGIN_BEBACKOFF_SLOT_LENGTH( "hive.server2.thrift.exponential.backoff.slot.length", "100ms", new TimeValidator(TimeUnit.MILLISECONDS), "Binary exponential backoff slot time for Thrift clients during login to HiveServer2,\n" + "for retries until hitting Thrift client timeout"), HIVE_SERVER2_THRIFT_LOGIN_TIMEOUT("hive.server2.thrift.login.timeout", "20s", new TimeValidator(TimeUnit.SECONDS), "Timeout for Thrift clients during login to HiveServer2"), HIVE_SERVER2_THRIFT_WORKER_KEEPALIVE_TIME("hive.server2.thrift.worker.keepalive.time", "60s", new TimeValidator(TimeUnit.SECONDS), "Keepalive time (in seconds) for an idle worker thread. When the number of workers exceeds min workers, " + "excessive threads are killed after this time interval."), // Configuration for async thread pool in SessionManager HIVE_SERVER2_ASYNC_EXEC_THREADS("hive.server2.async.exec.threads", 100, "Number of threads in the async thread pool for HiveServer2"), HIVE_SERVER2_ASYNC_EXEC_SHUTDOWN_TIMEOUT("hive.server2.async.exec.shutdown.timeout", "10s", new TimeValidator(TimeUnit.SECONDS), "How long HiveServer2 shutdown will wait for async threads to terminate."), HIVE_SERVER2_ASYNC_EXEC_WAIT_QUEUE_SIZE("hive.server2.async.exec.wait.queue.size", 100, "Size of the wait queue for async thread pool in HiveServer2.\n" + "After hitting this limit, the async thread pool will reject new requests."), HIVE_SERVER2_ASYNC_EXEC_KEEPALIVE_TIME("hive.server2.async.exec.keepalive.time", "10s", new TimeValidator(TimeUnit.SECONDS), "Time that an idle HiveServer2 async thread (from the thread pool) will wait for a new task\n" + "to arrive before terminating"), HIVE_SERVER2_ASYNC_EXEC_ASYNC_COMPILE("hive.server2.async.exec.async.compile", false, "Whether to enable compiling async query asynchronously. If enabled, it is unknown if the query will have any resultset before compilation completed."), HIVE_SERVER2_LONG_POLLING_TIMEOUT("hive.server2.long.polling.timeout", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Time that HiveServer2 will wait before responding to asynchronous calls that use long polling"), HIVE_SESSION_IMPL_CLASSNAME("hive.session.impl.classname", null, "Classname for custom implementation of hive session"), HIVE_SESSION_IMPL_WITH_UGI_CLASSNAME("hive.session.impl.withugi.classname", null, "Classname for custom implementation of hive session with UGI"), // HiveServer2 auth configuration HIVE_SERVER2_AUTHENTICATION("hive.server2.authentication", "NONE", new StringSet("NOSASL", "NONE", "LDAP", "KERBEROS", "PAM", "CERTIFICATES", "HOPS", "EXTERNAL", "CUSTOM"), "Client authentication types.\n" + " NONE: no authentication check\n" + " LDAP: LDAP/AD based authentication\n" + " KERBEROS: Kerberos/GSSAPI authentication\n" + " CUSTOM: Custom authentication provider\n" + " (Use with property hive.server2.custom.authentication.class)\n" + " PAM: Pluggable authentication module\n" + " CERTIFICATES: Authenticate using the CN of the client X.509 certificate\n" + " HOPS: Certificate + Password authentication\n" + " EXTERNAL: Hops external users password authentication\n" + " NOSASL: Raw transport"), HIVE_SERVER2_ALLOW_USER_SUBSTITUTION("hive.server2.allow.user.substitution", true, "Allow alternate user to be specified as part of HiveServer2 open connection request."), HIVE_SERVER2_KERBEROS_KEYTAB("hive.server2.authentication.kerberos.keytab", "", "Kerberos keytab file for server principal"), HIVE_SERVER2_KERBEROS_PRINCIPAL("hive.server2.authentication.kerberos.principal", "", "Kerberos server principal"), HIVE_SERVER2_CLIENT_KERBEROS_PRINCIPAL("hive.server2.authentication.client.kerberos.principal", "", "Kerberos principal used by the HA hive_server2s."), HIVE_SERVER2_SPNEGO_KEYTAB("hive.server2.authentication.spnego.keytab", "", "keytab file for SPNego principal, optional,\n" + "typical value would look like /etc/security/keytabs/spnego.service.keytab,\n" + "This keytab would be used by HiveServer2 when Kerberos security is enabled and \n" + "HTTP transport mode is used.\n" + "This needs to be set only if SPNEGO is to be used in authentication.\n" + "SPNego authentication would be honored only if valid\n" + " hive.server2.authentication.spnego.principal\n" + "and\n" + " hive.server2.authentication.spnego.keytab\n" + "are specified."), HIVE_SERVER2_SPNEGO_PRINCIPAL("hive.server2.authentication.spnego.principal", "", "SPNego service principal, optional,\n" + "typical value would look like HTTP/[email protected]\n" + "SPNego service principal would be used by HiveServer2 when Kerberos security is enabled\n" + "and HTTP transport mode is used.\n" + "This needs to be set only if SPNEGO is to be used in authentication."), HIVE_SERVER2_PLAIN_LDAP_URL("hive.server2.authentication.ldap.url", null, "LDAP connection URL(s),\n" + "this value could contain URLs to multiple LDAP servers instances for HA,\n" + "each LDAP URL is separated by a SPACE character. URLs are used in the \n" + " order specified until a connection is successful."), HIVE_SERVER2_PLAIN_LDAP_BASEDN("hive.server2.authentication.ldap.baseDN", null, "LDAP base DN"), HIVE_SERVER2_PLAIN_LDAP_DOMAIN("hive.server2.authentication.ldap.Domain", null, ""), HIVE_SERVER2_PLAIN_LDAP_GROUPDNPATTERN("hive.server2.authentication.ldap.groupDNPattern", null, "COLON-separated list of patterns to use to find DNs for group entities in this directory.\n" + "Use %s where the actual group name is to be substituted for.\n" + "For example: CN=%s,CN=Groups,DC=subdomain,DC=domain,DC=com."), HIVE_SERVER2_PLAIN_LDAP_GROUPFILTER("hive.server2.authentication.ldap.groupFilter", null, "COMMA-separated list of LDAP Group names (short name not full DNs).\n" + "For example: HiveAdmins,HadoopAdmins,Administrators"), HIVE_SERVER2_PLAIN_LDAP_USERDNPATTERN("hive.server2.authentication.ldap.userDNPattern", null, "COLON-separated list of patterns to use to find DNs for users in this directory.\n" + "Use %s where the actual group name is to be substituted for.\n" + "For example: CN=%s,CN=Users,DC=subdomain,DC=domain,DC=com."), HIVE_SERVER2_PLAIN_LDAP_USERFILTER("hive.server2.authentication.ldap.userFilter", null, "COMMA-separated list of LDAP usernames (just short names, not full DNs).\n" + "For example: hiveuser,impalauser,hiveadmin,hadoopadmin"), HIVE_SERVER2_PLAIN_LDAP_GUIDKEY("hive.server2.authentication.ldap.guidKey", "uid", "LDAP attribute name whose values are unique in this LDAP server.\n" + "For example: uid or CN."), HIVE_SERVER2_PLAIN_LDAP_GROUPMEMBERSHIP_KEY("hive.server2.authentication.ldap.groupMembershipKey", "member", "LDAP attribute name on the group object that contains the list of distinguished names\n" + "for the user, group, and contact objects that are members of the group.\n" + "For example: member, uniqueMember or memberUid"), HIVE_SERVER2_PLAIN_LDAP_USERMEMBERSHIP_KEY(HIVE_SERVER2_AUTHENTICATION_LDAP_USERMEMBERSHIPKEY_NAME, null, "LDAP attribute name on the user object that contains groups of which the user is\n" + "a direct member, except for the primary group, which is represented by the\n" + "primaryGroupId.\n" + "For example: memberOf"), HIVE_SERVER2_PLAIN_LDAP_GROUPCLASS_KEY("hive.server2.authentication.ldap.groupClassKey", "groupOfNames", "LDAP attribute name on the group entry that is to be used in LDAP group searches.\n" + "For example: group, groupOfNames or groupOfUniqueNames."), HIVE_SERVER2_PLAIN_LDAP_CUSTOMLDAPQUERY("hive.server2.authentication.ldap.customLDAPQuery", null, "A full LDAP query that LDAP Atn provider uses to execute against LDAP Server.\n" + "If this query returns a null resultset, the LDAP Provider fails the Authentication\n" + "request, succeeds if the user is part of the resultset." + "For example: (&(objectClass=group)(objectClass=top)(instanceType=4)(cn=Domain*)) \n" + "(&(objectClass=person)(|(sAMAccountName=admin)(|(memberOf=CN=Domain Admins,CN=Users,DC=domain,DC=com)" + "(memberOf=CN=Administrators,CN=Builtin,DC=domain,DC=com))))"), HIVE_SERVER2_CUSTOM_AUTHENTICATION_CLASS("hive.server2.custom.authentication.class", "org.apache.hive.service.auth.HopsAuthenticationProviderImpl", "Custom authentication class. Used when property\n" + "'hive.server2.authentication' is set to 'CUSTOM'. Provided class\n" + "must be a proper implementation of the interface\n" + "org.apache.hive.service.auth.PasswdAuthenticationProvider. HiveServer2\n" + "will call its Authenticate(user, passed) method to authenticate requests.\n" + "The implementation may optionally implement Hadoop's\n" + "org.apache.hadoop.conf.Configurable class to grab Hive's Configuration object."), HOPSWORKS_ENDPOINT("hopsworks.endpoint", "0.0.0.0", "Hopsworks endpoint to use for authentication"), HIVE_SERVER2_PAM_SERVICES("hive.server2.authentication.pam.services", null, "List of the underlying pam services that should be used when auth type is PAM\n" + "A file with the same name must exist in /etc/pam.d"), HIVE_SERVER2_ENABLE_DOAS("hive.server2.enable.doAs", true, "Setting this property to true will have HiveServer2 execute\n" + "Hive operations as the user making the calls to it."), HIVE_DISTCP_DOAS_USER("hive.distcp.privileged.doAs","hive", "This property allows privileged distcp executions done by hive\n" + "to run as this user."), HIVE_SERVER2_TABLE_TYPE_MAPPING("hive.server2.table.type.mapping", "CLASSIC", new StringSet("CLASSIC", "HIVE"), "This setting reflects how HiveServer2 will report the table types for JDBC and other\n" + "client implementations that retrieve the available tables and supported table types\n" + " HIVE : Exposes Hive's native table types like MANAGED_TABLE, EXTERNAL_TABLE, VIRTUAL_VIEW\n" + " CLASSIC : More generic types like TABLE and VIEW"), HIVE_SERVER2_SESSION_HOOK("hive.server2.session.hook", "", ""), // SSL settings HIVE_SUPER_USER("hive.superuser", "hive", "The user to use to create databases"), HIVE_SUPERUSER_ALLOWED_IMPERSONATION("hive.superuser.impersonation-users", "", "User that are allowed to impersonate the Hive superuser"), HIVE_SERVER2_MAP_FAIR_SCHEDULER_QUEUE("hive.server2.map.fair.scheduler.queue", true, "If the YARN fair scheduler is configured and HiveServer2 is running in non-impersonation mode,\n" + "this setting determines the user for fair scheduler queue mapping.\n" + "If set to true (default), the logged-in user determines the fair scheduler queue\n" + "for submitted jobs, so that map reduce resource usage can be tracked by user.\n" + "If set to false, all Hive jobs go to the 'hive' user's queue."), HIVE_SERVER2_BUILTIN_UDF_WHITELIST("hive.server2.builtin.udf.whitelist", "", "Comma separated list of builtin udf names allowed in queries.\n" + "An empty whitelist allows all builtin udfs to be executed. " + " The udf black list takes precedence over udf white list"), HIVE_SERVER2_BUILTIN_UDF_BLACKLIST("hive.server2.builtin.udf.blacklist", "", "Comma separated list of udfs names. These udfs will not be allowed in queries." + " The udf black list takes precedence over udf white list"), HIVE_ALLOW_UDF_LOAD_ON_DEMAND("hive.allow.udf.load.on.demand", false, "Whether enable loading UDFs from metastore on demand; this is mostly relevant for\n" + "HS2 and was the default behavior before Hive 1.2. Off by default."), HIVE_SERVER2_SESSION_CHECK_INTERVAL("hive.server2.session.check.interval", "6h", new TimeValidator(TimeUnit.MILLISECONDS, 3000l, true, null, false), "The check interval for session/operation timeout, which can be disabled by setting to zero or negative value."), HIVE_SERVER2_CLOSE_SESSION_ON_DISCONNECT("hive.server2.close.session.on.disconnect", true, "Session will be closed when connection is closed. Set this to false to have session outlive its parent connection."), HIVE_SERVER2_IDLE_SESSION_TIMEOUT("hive.server2.idle.session.timeout", "7d", new TimeValidator(TimeUnit.MILLISECONDS), "Session will be closed when it's not accessed for this duration, which can be disabled by setting to zero or negative value."), HIVE_SERVER2_IDLE_OPERATION_TIMEOUT("hive.server2.idle.operation.timeout", "5d", new TimeValidator(TimeUnit.MILLISECONDS), "Operation will be closed when it's not accessed for this duration of time, which can be disabled by setting to zero value.\n" + " With positive value, it's checked for operations in terminal state only (FINISHED, CANCELED, CLOSED, ERROR).\n" + " With negative value, it's checked for all of the operations regardless of state."), HIVE_SERVER2_IDLE_SESSION_CHECK_OPERATION("hive.server2.idle.session.check.operation", true, "Session will be considered to be idle only if there is no activity, and there is no pending operation.\n" + " This setting takes effect only if session idle timeout (hive.server2.idle.session.timeout) and checking\n" + "(hive.server2.session.check.interval) are enabled."), HIVE_SERVER2_THRIFT_CLIENT_RETRY_LIMIT("hive.server2.thrift.client.retry.limit", 1,"Number of retries upon " + "failure of Thrift HiveServer2 calls"), HIVE_SERVER2_THRIFT_CLIENT_CONNECTION_RETRY_LIMIT("hive.server2.thrift.client.connect.retry.limit", 1,"Number of " + "retries while opening a connection to HiveServe2"), HIVE_SERVER2_THRIFT_CLIENT_RETRY_DELAY_SECONDS("hive.server2.thrift.client.retry.delay.seconds", "1s", new TimeValidator(TimeUnit.SECONDS), "Number of seconds for the HiveServer2 thrift client to wait between " + "consecutive connection attempts. Also specifies the time to wait between retrying thrift calls upon failures"), HIVE_SERVER2_THRIFT_CLIENT_USER("hive.server2.thrift.client.user", "anonymous","Username to use against thrift" + " client"), HIVE_SERVER2_THRIFT_CLIENT_PASSWORD("hive.server2.thrift.client.password", "anonymous","Password to use against " + "thrift client"), // ResultSet serialization settings HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS("hive.server2.thrift.resultset.serialize.in.tasks", false, "Whether we should serialize the Thrift structures used in JDBC ResultSet RPC in task nodes.\n " + "We use SequenceFile and ThriftJDBCBinarySerDe to read and write the final results if this is true."), // TODO: Make use of this config to configure fetch size HIVE_SERVER2_THRIFT_RESULTSET_MAX_FETCH_SIZE("hive.server2.thrift.resultset.max.fetch.size", 10000, "Max number of rows sent in one Fetch RPC call by the server to the client."), HIVE_SERVER2_THRIFT_RESULTSET_DEFAULT_FETCH_SIZE("hive.server2.thrift.resultset.default.fetch.size", 1000, "The number of rows sent in one Fetch RPC call by the server to the client, if not\n" + "specified by the client."), HIVE_SERVER2_XSRF_FILTER_ENABLED("hive.server2.xsrf.filter.enabled",false, "If enabled, HiveServer2 will block any requests made to it over http " + "if an X-XSRF-HEADER header is not present"), HIVE_SECURITY_COMMAND_WHITELIST("hive.security.command.whitelist", "set,reset,dfs,add,list,delete,reload,compile,llap", "Comma separated list of non-SQL Hive commands users are authorized to execute"), HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH("hive.server2.job.credential.provider.path", "", "If set, this configuration property should provide a comma-separated list of URLs that indicates the type and " + "location of providers to be used by hadoop credential provider API. It provides HiveServer2 the ability to provide job-specific " + "credential providers for jobs run using MR and Spark execution engines. This functionality has not been tested against Tez."), HIVE_MOVE_FILES_THREAD_COUNT("hive.mv.files.thread", 15, new SizeValidator(0L, true, 1024L, true), "Number of threads" + " used to move files in move task. Set it to 0 to disable multi-threaded file moves. This parameter is also used by" + " MSCK to check tables."), HIVE_LOAD_DYNAMIC_PARTITIONS_THREAD_COUNT("hive.load.dynamic.partitions.thread", 15, new SizeValidator(1L, true, 1024L, true), "Number of threads used to load dynamic partitions."), // If this is set all move tasks at the end of a multi-insert query will only begin once all // outputs are ready HIVE_MULTI_INSERT_MOVE_TASKS_SHARE_DEPENDENCIES( "hive.multi.insert.move.tasks.share.dependencies", false, "If this is set all move tasks for tables/partitions (not directories) at the end of a\n" + "multi-insert query will only begin once the dependencies for all these move tasks have been\n" + "met.\n" + "Advantages: If concurrency is enabled, the locks will only be released once the query has\n" + " finished, so with this config enabled, the time when the table/partition is\n" + " generated will be much closer to when the lock on it is released.\n" + "Disadvantages: If concurrency is not enabled, with this disabled, the tables/partitions which\n" + " are produced by this query and finish earlier will be available for querying\n" + " much earlier. Since the locks are only released once the query finishes, this\n" + " does not apply if concurrency is enabled."), HIVE_INFER_BUCKET_SORT("hive.exec.infer.bucket.sort", false, "If this is set, when writing partitions, the metadata will include the bucketing/sorting\n" + "properties with which the data was written if any (this will not overwrite the metadata\n" + "inherited from the table if the table is bucketed/sorted)"), HIVE_INFER_BUCKET_SORT_NUM_BUCKETS_POWER_TWO( "hive.exec.infer.bucket.sort.num.buckets.power.two", false, "If this is set, when setting the number of reducers for the map reduce task which writes the\n" + "final output files, it will choose a number which is a power of two, unless the user specifies\n" + "the number of reducers to use using mapred.reduce.tasks. The number of reducers\n" + "may be set to a power of two, only to be followed by a merge task meaning preventing\n" + "anything from being inferred.\n" + "With hive.exec.infer.bucket.sort set to true:\n" + "Advantages: If this is not set, the number of buckets for partitions will seem arbitrary,\n" + " which means that the number of mappers used for optimized joins, for example, will\n" + " be very low. With this set, since the number of buckets used for any partition is\n" + " a power of two, the number of mappers used for optimized joins will be the least\n" + " number of buckets used by any partition being joined.\n" + "Disadvantages: This may mean a much larger or much smaller number of reducers being used in the\n" + " final map reduce job, e.g. if a job was originally going to take 257 reducers,\n" + " it will now take 512 reducers, similarly if the max number of reducers is 511,\n" + " and a job was going to use this many, it will now use 256 reducers."), HIVEOPTLISTBUCKETING("hive.optimize.listbucketing", false, "Enable list bucketing optimizer. Default value is false so that we disable it by default."), // Allow TCP Keep alive socket option for for HiveServer or a maximum timeout for the socket. SERVER_READ_SOCKET_TIMEOUT("hive.server.read.socket.timeout", "10s", new TimeValidator(TimeUnit.SECONDS), "Timeout for the HiveServer to close the connection if no response from the client. By default, 10 seconds."), SERVER_TCP_KEEP_ALIVE("hive.server.tcp.keepalive", true, "Whether to enable TCP keepalive for the Hive Server. Keepalive will prevent accumulation of half-open connections."), HIVE_DECODE_PARTITION_NAME("hive.decode.partition.name", false, "Whether to show the unquoted partition names in query results."), HIVE_EXECUTION_ENGINE("hive.execution.engine", "mr", new StringSet(true, "mr", "tez", "spark"), "Chooses execution engine. Options are: mr (Map reduce, default), tez, spark. While MR\n" + "remains the default engine for historical reasons, it is itself a historical engine\n" + "and is deprecated in Hive 2 line. It may be removed without further warning."), HIVE_EXECUTION_MODE("hive.execution.mode", "container", new StringSet("container", "llap"), "Chooses whether query fragments will run in container or in llap"), HIVE_JAR_DIRECTORY("hive.jar.directory", null, "This is the location hive in tez mode will look for to find a site wide \n" + "installed hive instance."), HIVE_USER_INSTALL_DIR("hive.user.install.directory", "/user/", "If hive (in tez mode only) cannot find a usable hive jar in \"hive.jar.directory\", \n" + "it will upload the hive jar to \"hive.user.install.directory/user.name\"\n" + "and use it to run queries."), // Vectorization enabled HIVE_VECTORIZATION_ENABLED("hive.vectorized.execution.enabled", true, "This flag should be set to true to enable vectorized mode of query execution.\n" + "The default value is true to reflect that our most expected Hive deployment will be using vectorization."), HIVE_VECTORIZATION_REDUCE_ENABLED("hive.vectorized.execution.reduce.enabled", true, "This flag should be set to true to enable vectorized mode of the reduce-side of query execution.\n" + "The default value is true."), HIVE_VECTORIZATION_REDUCE_GROUPBY_ENABLED("hive.vectorized.execution.reduce.groupby.enabled", true, "This flag should be set to true to enable vectorized mode of the reduce-side GROUP BY query execution.\n" + "The default value is true."), HIVE_VECTORIZATION_MAPJOIN_NATIVE_ENABLED("hive.vectorized.execution.mapjoin.native.enabled", true, "This flag should be set to true to enable native (i.e. non-pass through) vectorization\n" + "of queries using MapJoin.\n" + "The default value is true."), HIVE_VECTORIZATION_MAPJOIN_NATIVE_MULTIKEY_ONLY_ENABLED("hive.vectorized.execution.mapjoin.native.multikey.only.enabled", false, "This flag should be set to true to restrict use of native vector map join hash tables to\n" + "the MultiKey in queries using MapJoin.\n" + "The default value is false."), HIVE_VECTORIZATION_MAPJOIN_NATIVE_MINMAX_ENABLED("hive.vectorized.execution.mapjoin.minmax.enabled", false, "This flag should be set to true to enable vector map join hash tables to\n" + "use max / max filtering for integer join queries using MapJoin.\n" + "The default value is false."), HIVE_VECTORIZATION_MAPJOIN_NATIVE_OVERFLOW_REPEATED_THRESHOLD("hive.vectorized.execution.mapjoin.overflow.repeated.threshold", -1, "The number of small table rows for a match in vector map join hash tables\n" + "where we use the repeated field optimization in overflow vectorized row batch for join queries using MapJoin.\n" + "A value of -1 means do use the join result optimization. Otherwise, threshold value can be 0 to maximum integer."), HIVE_VECTORIZATION_MAPJOIN_NATIVE_FAST_HASHTABLE_ENABLED("hive.vectorized.execution.mapjoin.native.fast.hashtable.enabled", false, "This flag should be set to true to enable use of native fast vector map join hash tables in\n" + "queries using MapJoin.\n" + "The default value is false."), HIVE_VECTORIZATION_GROUPBY_CHECKINTERVAL("hive.vectorized.groupby.checkinterval", 100000, "Number of entries added to the group by aggregation hash before a recomputation of average entry size is performed."), HIVE_VECTORIZATION_GROUPBY_MAXENTRIES("hive.vectorized.groupby.maxentries", 1000000, "Max number of entries in the vector group by aggregation hashtables. \n" + "Exceeding this will trigger a flush irrelevant of memory pressure condition."), HIVE_VECTORIZATION_GROUPBY_FLUSH_PERCENT("hive.vectorized.groupby.flush.percent", (float) 0.1, "Percent of entries in the group by aggregation hash flushed when the memory threshold is exceeded."), HIVE_VECTORIZATION_REDUCESINK_NEW_ENABLED("hive.vectorized.execution.reducesink.new.enabled", true, "This flag should be set to true to enable the new vectorization\n" + "of queries using ReduceSink.\ni" + "The default value is true."), HIVE_VECTORIZATION_USE_VECTORIZED_INPUT_FILE_FORMAT("hive.vectorized.use.vectorized.input.format", true, "This flag should be set to true to enable vectorizing with vectorized input file format capable SerDe.\n" + "The default value is true."), HIVE_VECTORIZATION_VECTORIZED_INPUT_FILE_FORMAT_EXCLUDES("hive.vectorized.input.format.excludes","", "This configuration should be set to fully described input format class names for which \n" + " vectorized input format should not be used for vectorized execution."), HIVE_VECTORIZATION_USE_VECTOR_DESERIALIZE("hive.vectorized.use.vector.serde.deserialize", true, "This flag should be set to true to enable vectorizing rows using vector deserialize.\n" + "The default value is true."), HIVE_VECTORIZATION_USE_ROW_DESERIALIZE("hive.vectorized.use.row.serde.deserialize", true, "This flag should be set to true to enable vectorizing using row deserialize.\n" + "The default value is false."), HIVE_VECTORIZATION_ROW_DESERIALIZE_INPUTFORMAT_EXCLUDES( "hive.vectorized.row.serde.inputformat.excludes", "org.apache.parquet.hadoop.ParquetInputFormat,org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat,org.apache.hive.storage.jdbc.JdbcInputFormat", "The input formats not supported by row deserialize vectorization."), HIVE_VECTOR_ADAPTOR_USAGE_MODE("hive.vectorized.adaptor.usage.mode", "all", new StringSet("none", "chosen", "all"), "Specifies the extent to which the VectorUDFAdaptor will be used for UDFs that do not have a corresponding vectorized class.\n" + "0. none : disable any usage of VectorUDFAdaptor\n" + "1. chosen : use VectorUDFAdaptor for a small set of UDFs that were chosen for good performance\n" + "2. all : use VectorUDFAdaptor for all UDFs" ), HIVE_TEST_VECTOR_ADAPTOR_OVERRIDE("hive.test.vectorized.adaptor.override", false, "internal use only, used to force always using the VectorUDFAdaptor.\n" + "The default is false, of course", true), HIVE_VECTORIZATION_PTF_ENABLED("hive.vectorized.execution.ptf.enabled", true, "This flag should be set to true to enable vectorized mode of the PTF of query execution.\n" + "The default value is true."), HIVE_VECTORIZATION_PTF_MAX_MEMORY_BUFFERING_BATCH_COUNT("hive.vectorized.ptf.max.memory.buffering.batch.count", 25, "Maximum number of vectorized row batches to buffer in memory for PTF\n" + "The default value is 25"), HIVE_VECTORIZATION_TESTING_REDUCER_BATCH_SIZE("hive.vectorized.testing.reducer.batch.size", -1, "internal use only, used for creating small group key vectorized row batches to exercise more logic\n" + "The default value is -1 which means don't restrict for testing", true), HIVE_VECTORIZATION_TESTING_REUSE_SCRATCH_COLUMNS("hive.vectorized.reuse.scratch.columns", true, "internal use only. Disable this to debug scratch column state issues", true), HIVE_VECTORIZATION_COMPLEX_TYPES_ENABLED("hive.vectorized.complex.types.enabled", true, "This flag should be set to true to enable vectorization\n" + "of expressions with complex types.\n" + "The default value is true."), HIVE_VECTORIZATION_GROUPBY_COMPLEX_TYPES_ENABLED("hive.vectorized.groupby.complex.types.enabled", true, "This flag should be set to true to enable group by vectorization\n" + "of aggregations that use complex types.\n", "For example, AVG uses a complex type (STRUCT) for partial aggregation results" + "The default value is true."), HIVE_VECTORIZATION_ROW_IDENTIFIER_ENABLED("hive.vectorized.row.identifier.enabled", true, "This flag should be set to true to enable vectorization of ROW__ID."), HIVE_VECTORIZATION_USE_CHECKED_EXPRESSIONS("hive.vectorized.use.checked.expressions", false, "This flag should be set to true to use overflow checked vector expressions when available.\n" + "For example, arithmetic expressions which can overflow the output data type can be evaluated using\n" + " checked vector expressions so that they produce same result as non-vectorized evaluation."), HIVE_VECTORIZED_ADAPTOR_SUPPRESS_EVALUATE_EXCEPTIONS( "hive.vectorized.adaptor.suppress.evaluate.exceptions", false, "This flag should be set to true to suppress HiveException from the generic UDF function\n" + "evaluate call and turn them into NULLs. Assume, by default, this is not needed"), HIVE_VECTORIZED_INPUT_FORMAT_SUPPORTS_ENABLED( "hive.vectorized.input.format.supports.enabled", "decimal_64", "Which vectorized input format support features are enabled for vectorization.\n" + "That is, if a VectorizedInputFormat input format does support \"decimal_64\" for example\n" + "this variable must enable that to be used in vectorization"), HIVE_VECTORIZED_IF_EXPR_MODE("hive.vectorized.if.expr.mode", "better", new StringSet("adaptor", "good", "better"), "Specifies the extent to which SQL IF statements will be vectorized.\n" + "0. adaptor: only use the VectorUDFAdaptor to vectorize IF statements\n" + "1. good : use regular vectorized IF expression classes that get good performance\n" + "2. better : use vectorized IF expression classes that conditionally execute THEN/ELSE\n" + " expressions for better performance.\n"), HIVE_TEST_VECTORIZATION_ENABLED_OVERRIDE("hive.test.vectorized.execution.enabled.override", "none", new StringSet("none", "enable", "disable"), "internal use only, used to override the hive.vectorized.execution.enabled setting and\n" + "turn off vectorization. The default is false, of course", true), HIVE_TEST_VECTORIZATION_SUPPRESS_EXPLAIN_EXECUTION_MODE( "hive.test.vectorization.suppress.explain.execution.mode", false, "internal use only, used to suppress \"Execution mode: vectorized\" EXPLAIN display.\n" + "The default is false, of course", true), HIVE_TEST_VECTORIZER_SUPPRESS_FATAL_EXCEPTIONS( "hive.test.vectorizer.suppress.fatal.exceptions", true, "internal use only. When false, don't suppress fatal exceptions like\n" + "NullPointerException, etc so the query will fail and assure it will be noticed", true), HIVE_TYPE_CHECK_ON_INSERT("hive.typecheck.on.insert", true, "This property has been extended to control " + "whether to check, convert, and normalize partition value to conform to its column type in " + "partition operations including but not limited to insert, such as alter, describe etc."), HIVE_HADOOP_CLASSPATH("hive.hadoop.classpath", null, "For Windows OS, we need to pass HIVE_HADOOP_CLASSPATH Java parameter while starting HiveServer2 \n" + "using \"-hiveconf hive.hadoop.classpath=%HIVE_LIB%\"."), HIVE_RPC_QUERY_PLAN("hive.rpc.query.plan", false, "Whether to send the query plan via local resource or RPC"), HIVE_AM_SPLIT_GENERATION("hive.compute.splits.in.am", true, "Whether to generate the splits locally or in the AM (tez only)"), HIVE_TEZ_GENERATE_CONSISTENT_SPLITS("hive.tez.input.generate.consistent.splits", true, "Whether to generate consistent split locations when generating splits in the AM"), HIVE_PREWARM_ENABLED("hive.prewarm.enabled", false, "Enables container prewarm for Tez/Spark (Hadoop 2 only)"), HIVE_PREWARM_NUM_CONTAINERS("hive.prewarm.numcontainers", 10, "Controls the number of containers to prewarm for Tez/Spark (Hadoop 2 only)"), HIVE_PREWARM_SPARK_TIMEOUT("hive.prewarm.spark.timeout", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Time to wait to finish prewarming spark executors"), HIVESTAGEIDREARRANGE("hive.stageid.rearrange", "none", new StringSet("none", "idonly", "traverse", "execution"), ""), HIVEEXPLAINDEPENDENCYAPPENDTASKTYPES("hive.explain.dependency.append.tasktype", false, ""), HIVECOUNTERGROUP("hive.counters.group.name", "HIVE", "The name of counter group for internal Hive variables (CREATED_FILE, FATAL_ERROR, etc.)"), HIVE_QUOTEDID_SUPPORT("hive.support.quoted.identifiers", "column", new StringSet("none", "column"), "Whether to use quoted identifier. 'none' or 'column' can be used. \n" + " none: default(past) behavior. Implies only alphaNumeric and underscore are valid characters in identifiers.\n" + " column: implies column names can contain any character." ), /** * @deprecated Use MetastoreConf.SUPPORT_SPECIAL_CHARACTERS_IN_TABLE_NAMES */ @Deprecated HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES("hive.support.special.characters.tablename", true, "This flag should be set to true to enable support for special characters in table names.\n" + "When it is set to false, only [a-zA-Z_0-9]+ are supported.\n" + "The only supported special character right now is '/'. This flag applies only to quoted table names.\n" + "The default value is true."), HIVE_CREATE_TABLES_AS_INSERT_ONLY("hive.create.as.insert.only", false, "Whether the eligible tables should be created as ACID insert-only by default. Does \n" + "not apply to external tables, the ones using storage handlers, etc."), // role names are case-insensitive USERS_IN_ADMIN_ROLE("hive.users.in.admin.role", "", false, "Comma separated list of users who are in admin role for bootstrapping.\n" + "More users can be added in ADMIN role later."), HIVE_COMPAT("hive.compat", HiveCompat.DEFAULT_COMPAT_LEVEL, "Enable (configurable) deprecated behaviors by setting desired level of backward compatibility.\n" + "Setting to 0.12:\n" + " Maintains division behavior: int / int = double"), HIVE_CONVERT_JOIN_BUCKET_MAPJOIN_TEZ("hive.convert.join.bucket.mapjoin.tez", true, "Whether joins can be automatically converted to bucket map joins in hive \n" + "when tez is used as the execution engine."), HIVE_TEZ_BMJ_USE_SUBCACHE("hive.tez.bmj.use.subcache", true, "Use subcache to reuse hashtable across multiple tasks"), HIVE_CHECK_CROSS_PRODUCT("hive.exec.check.crossproducts", true, "Check if a plan contains a Cross Product. If there is one, output a warning to the Session's console."), HIVE_LOCALIZE_RESOURCE_WAIT_INTERVAL("hive.localize.resource.wait.interval", "5000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Time to wait for another thread to localize the same resource for hive-tez."), HIVE_LOCALIZE_RESOURCE_NUM_WAIT_ATTEMPTS("hive.localize.resource.num.wait.attempts", 5, "The number of attempts waiting for localizing a resource in hive-tez."), TEZ_AUTO_REDUCER_PARALLELISM("hive.tez.auto.reducer.parallelism", false, "Turn on Tez' auto reducer parallelism feature. When enabled, Hive will still estimate data sizes\n" + "and set parallelism estimates. Tez will sample source vertices' output sizes and adjust the estimates at runtime as\n" + "necessary."), TEZ_LLAP_MIN_REDUCER_PER_EXECUTOR("hive.tez.llap.min.reducer.per.executor", 0.95f, "If above 0, the min number of reducers for auto-parallelism for LLAP scheduling will\n" + "be set to this fraction of the number of executors."), TEZ_MAX_PARTITION_FACTOR("hive.tez.max.partition.factor", 2f, "When auto reducer parallelism is enabled this factor will be used to over-partition data in shuffle edges."), TEZ_MIN_PARTITION_FACTOR("hive.tez.min.partition.factor", 0.25f, "When auto reducer parallelism is enabled this factor will be used to put a lower limit to the number\n" + "of reducers that tez specifies."), TEZ_OPTIMIZE_BUCKET_PRUNING( "hive.tez.bucket.pruning", false, "When pruning is enabled, filters on bucket columns will be processed by \n" + "filtering the splits against a bitset of included buckets. This needs predicates \n"+ "produced by hive.optimize.ppd and hive.optimize.index.filters."), TEZ_OPTIMIZE_BUCKET_PRUNING_COMPAT( "hive.tez.bucket.pruning.compat", true, "When pruning is enabled, handle possibly broken inserts due to negative hashcodes.\n" + "This occasionally doubles the data scan cost, but is default enabled for safety"), TEZ_DYNAMIC_PARTITION_PRUNING( "hive.tez.dynamic.partition.pruning", true, "When dynamic pruning is enabled, joins on partition keys will be processed by sending\n" + "events from the processing vertices to the Tez application master. These events will be\n" + "used to prune unnecessary partitions."), TEZ_DYNAMIC_PARTITION_PRUNING_MAX_EVENT_SIZE("hive.tez.dynamic.partition.pruning.max.event.size", 1*1024*1024L, "Maximum size of events sent by processors in dynamic pruning. If this size is crossed no pruning will take place."), TEZ_DYNAMIC_PARTITION_PRUNING_MAX_DATA_SIZE("hive.tez.dynamic.partition.pruning.max.data.size", 100*1024*1024L, "Maximum total data size of events in dynamic pruning."), TEZ_DYNAMIC_SEMIJOIN_REDUCTION("hive.tez.dynamic.semijoin.reduction", true, "When dynamic semijoin is enabled, shuffle joins will perform a leaky semijoin before shuffle. This " + "requires hive.tez.dynamic.partition.pruning to be enabled."), TEZ_MIN_BLOOM_FILTER_ENTRIES("hive.tez.min.bloom.filter.entries", 1000000L, "Bloom filter should be of at min certain size to be effective"), TEZ_MAX_BLOOM_FILTER_ENTRIES("hive.tez.max.bloom.filter.entries", 100000000L, "Bloom filter should be of at max certain size to be effective"), TEZ_BLOOM_FILTER_FACTOR("hive.tez.bloom.filter.factor", (float) 1.0, "Bloom filter should be a multiple of this factor with nDV"), TEZ_BIGTABLE_MIN_SIZE_SEMIJOIN_REDUCTION("hive.tez.bigtable.minsize.semijoin.reduction", 100000000L, "Big table for runtime filteting should be of atleast this size"), TEZ_DYNAMIC_SEMIJOIN_REDUCTION_THRESHOLD("hive.tez.dynamic.semijoin.reduction.threshold", (float) 0.50, "Only perform semijoin optimization if the estimated benefit at or above this fraction of the target table"), TEZ_DYNAMIC_SEMIJOIN_REDUCTION_FOR_MAPJOIN("hive.tez.dynamic.semijoin.reduction.for.mapjoin", false, "Use a semi-join branch for map-joins. This may not make it faster, but is helpful in certain join patterns."), TEZ_DYNAMIC_SEMIJOIN_REDUCTION_FOR_DPP_FACTOR("hive.tez.dynamic.semijoin.reduction.for.dpp.factor", (float) 1.0, "The factor to decide if semijoin branch feeds into a TableScan\n" + "which has an outgoing Dynamic Partition Pruning (DPP) branch based on number of distinct values."), TEZ_SMB_NUMBER_WAVES( "hive.tez.smb.number.waves", (float) 0.5, "The number of waves in which to run the SMB join. Account for cluster being occupied. Ideally should be 1 wave."), TEZ_EXEC_SUMMARY( "hive.tez.exec.print.summary", false, "Display breakdown of execution steps, for every query executed by the shell."), TEZ_SESSION_EVENTS_SUMMARY( "hive.tez.session.events.print.summary", "none", new StringSet("none", "text", "json"), "Display summary of all tez sessions related events in text or json format"), TEZ_EXEC_INPLACE_PROGRESS( "hive.tez.exec.inplace.progress", true, "Updates tez job execution progress in-place in the terminal when hive-cli is used."), HIVE_SERVER2_INPLACE_PROGRESS( "hive.server2.in.place.progress", true, "Allows hive server 2 to send progress bar update information. This is currently available" + " only if the execution engine is tez."), TEZ_DAG_STATUS_CHECK_INTERVAL("hive.tez.dag.status.check.interval", "500ms", new TimeValidator(TimeUnit.MILLISECONDS), "Interval between subsequent DAG status invocation."), SPARK_EXEC_INPLACE_PROGRESS("hive.spark.exec.inplace.progress", true, "Updates spark job execution progress in-place in the terminal."), TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION("hive.tez.container.max.java.heap.fraction", 0.8f, "This is to override the tez setting with the same name"), TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION_MIN("hive.tez.task.scale.memory.reserve-fraction.min", 0.3f, "This is to override the tez setting tez.task.scale.memory.reserve-fraction"), TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION_MAX("hive.tez.task.scale.memory.reserve.fraction.max", 0.5f, "The maximum fraction of JVM memory which Tez will reserve for the processor"), TEZ_TASK_SCALE_MEMORY_RESERVE_FRACTION("hive.tez.task.scale.memory.reserve.fraction", -1f, "The customized fraction of JVM memory which Tez will reserve for the processor"), TEZ_CARTESIAN_PRODUCT_EDGE_ENABLED("hive.tez.cartesian-product.enabled", false, "Use Tez cartesian product edge to speed up cross product"), // The default is different on the client and server, so it's null here. LLAP_IO_ENABLED("hive.llap.io.enabled", null, "Whether the LLAP IO layer is enabled."), LLAP_IO_ROW_WRAPPER_ENABLED("hive.llap.io.row.wrapper.enabled", true, "Whether the LLAP IO row wrapper is enabled for non-vectorized queries."), LLAP_IO_ACID_ENABLED("hive.llap.io.acid", true, "Whether the LLAP IO layer is enabled for ACID."), LLAP_IO_TRACE_SIZE("hive.llap.io.trace.size", "2Mb", new SizeValidator(0L, true, (long)Integer.MAX_VALUE, false), "The buffer size for a per-fragment LLAP debug trace. 0 to disable."), LLAP_IO_TRACE_ALWAYS_DUMP("hive.llap.io.trace.always.dump", false, "Whether to always dump the LLAP IO trace (if enabled); the default is on error."), LLAP_IO_NONVECTOR_WRAPPER_ENABLED("hive.llap.io.nonvector.wrapper.enabled", true, "Whether the LLAP IO layer is enabled for non-vectorized queries that read inputs\n" + "that can be vectorized"), LLAP_IO_MEMORY_MODE("hive.llap.io.memory.mode", "cache", new StringSet("cache", "none"), "LLAP IO memory usage; 'cache' (the default) uses data and metadata cache with a\n" + "custom off-heap allocator, 'none' doesn't use either (this mode may result in\n" + "significant performance degradation)"), LLAP_ALLOCATOR_MIN_ALLOC("hive.llap.io.allocator.alloc.min", "16Kb", new SizeValidator(), "Minimum allocation possible from LLAP buddy allocator. Allocations below that are\n" + "padded to minimum allocation. For ORC, should generally be the same as the expected\n" + "compression buffer size, or next lowest power of 2. Must be a power of 2."), LLAP_ALLOCATOR_MAX_ALLOC("hive.llap.io.allocator.alloc.max", "16Mb", new SizeValidator(), "Maximum allocation possible from LLAP buddy allocator. For ORC, should be as large as\n" + "the largest expected ORC compression buffer size. Must be a power of 2."), LLAP_ALLOCATOR_ARENA_COUNT("hive.llap.io.allocator.arena.count", 8, "Arena count for LLAP low-level cache; cache will be allocated in the steps of\n" + "(size/arena_count) bytes. This size must be <= 1Gb and >= max allocation; if it is\n" + "not the case, an adjusted size will be used. Using powers of 2 is recommended."), LLAP_IO_MEMORY_MAX_SIZE("hive.llap.io.memory.size", "1Gb", new SizeValidator(), "Maximum size for IO allocator or ORC low-level cache.", "hive.llap.io.cache.orc.size"), LLAP_ALLOCATOR_DIRECT("hive.llap.io.allocator.direct", true, "Whether ORC low-level cache should use direct allocation."), LLAP_ALLOCATOR_MAPPED("hive.llap.io.allocator.mmap", false, "Whether ORC low-level cache should use memory mapped allocation (direct I/O). \n" + "This is recommended to be used along-side NVDIMM (DAX) or NVMe flash storage."), LLAP_ALLOCATOR_MAPPED_PATH("hive.llap.io.allocator.mmap.path", "/tmp", new WritableDirectoryValidator(), "The directory location for mapping NVDIMM/NVMe flash storage into the ORC low-level cache."), LLAP_ALLOCATOR_DISCARD_METHOD("hive.llap.io.allocator.discard.method", "both", new StringSet("freelist", "brute", "both"), "Which method to use to force-evict blocks to deal with fragmentation:\n" + "freelist - use half-size free list (discards less, but also less reliable); brute -\n" + "brute force, discard whatever we can; both - first try free list, then brute force."), LLAP_ALLOCATOR_DEFRAG_HEADROOM("hive.llap.io.allocator.defrag.headroom", "1Mb", "How much of a headroom to leave to allow allocator more flexibility to defragment.\n" + "The allocator would further cap it to a fraction of total memory."), LLAP_TRACK_CACHE_USAGE("hive.llap.io.track.cache.usage", true, "Whether to tag LLAP cache contents, mapping them to Hive entities (paths for\n" + "partitions and tables) for reporting."), LLAP_USE_LRFU("hive.llap.io.use.lrfu", true, "Whether ORC low-level cache should use LRFU cache policy instead of default (FIFO)."), LLAP_LRFU_LAMBDA("hive.llap.io.lrfu.lambda", 0.000001f, "Lambda for ORC low-level cache LRFU cache policy. Must be in [0, 1]. 0 makes LRFU\n" + "behave like LFU, 1 makes it behave like LRU, values in between balance accordingly.\n" + "The meaning of this parameter is the inverse of the number of time ticks (cache\n" + " operations, currently) that cause the combined recency-frequency of a block in cache\n" + " to be halved."), LLAP_CACHE_ALLOW_SYNTHETIC_FILEID("hive.llap.cache.allow.synthetic.fileid", true, "Whether LLAP cache should use synthetic file ID if real one is not available. Systems\n" + "like HDFS, Isilon, etc. provide a unique file/inode ID. On other FSes (e.g. local\n" + "FS), the cache would not work by default because LLAP is unable to uniquely track the\n" + "files; enabling this setting allows LLAP to generate file ID from the path, size and\n" + "modification time, which is almost certain to identify file uniquely. However, if you\n" + "use a FS without file IDs and rewrite files a lot (or are paranoid), you might want\n" + "to avoid this setting."), LLAP_CACHE_DEFAULT_FS_FILE_ID("hive.llap.cache.defaultfs.only.native.fileid", true, "Whether LLAP cache should use native file IDs from the default FS only. This is to\n" + "avoid file ID collisions when several different DFS instances are in use at the same\n" + "time. Disable this check to allow native file IDs from non-default DFS."), LLAP_CACHE_ENABLE_ORC_GAP_CACHE("hive.llap.orc.gap.cache", true, "Whether LLAP cache for ORC should remember gaps in ORC compression buffer read\n" + "estimates, to avoid re-reading the data that was read once and discarded because it\n" + "is unneeded. This is only necessary for ORC files written before HIVE-9660."), LLAP_IO_USE_FILEID_PATH("hive.llap.io.use.fileid.path", true, "Whether LLAP should use fileId (inode)-based path to ensure better consistency for the\n" + "cases of file overwrites. This is supported on HDFS."), // Restricted to text for now as this is a new feature; only text files can be sliced. LLAP_IO_ENCODE_ENABLED("hive.llap.io.encode.enabled", true, "Whether LLAP should try to re-encode and cache data for non-ORC formats. This is used\n" + "on LLAP Server side to determine if the infrastructure for that is initialized."), LLAP_IO_ENCODE_FORMATS("hive.llap.io.encode.formats", "org.apache.hadoop.mapred.TextInputFormat,", "The table input formats for which LLAP IO should re-encode and cache data.\n" + "Comma-separated list."), LLAP_IO_ENCODE_ALLOC_SIZE("hive.llap.io.encode.alloc.size", "256Kb", new SizeValidator(), "Allocation size for the buffers used to cache encoded data from non-ORC files. Must\n" + "be a power of two between " + LLAP_ALLOCATOR_MIN_ALLOC + " and\n" + LLAP_ALLOCATOR_MAX_ALLOC + "."), LLAP_IO_ENCODE_VECTOR_SERDE_ENABLED("hive.llap.io.encode.vector.serde.enabled", true, "Whether LLAP should use vectorized SerDe reader to read text data when re-encoding."), LLAP_IO_ENCODE_VECTOR_SERDE_ASYNC_ENABLED("hive.llap.io.encode.vector.serde.async.enabled", true, "Whether LLAP should use async mode in vectorized SerDe reader to read text data."), LLAP_IO_ENCODE_SLICE_ROW_COUNT("hive.llap.io.encode.slice.row.count", 100000, "Row count to use to separate cache slices when reading encoded data from row-based\n" + "inputs into LLAP cache, if this feature is enabled."), LLAP_IO_ENCODE_SLICE_LRR("hive.llap.io.encode.slice.lrr", true, "Whether to separate cache slices when reading encoded data from text inputs via MR\n" + "MR LineRecordRedader into LLAP cache, if this feature is enabled. Safety flag."), LLAP_ORC_ENABLE_TIME_COUNTERS("hive.llap.io.orc.time.counters", true, "Whether to enable time counters for LLAP IO layer (time spent in HDFS, etc.)"), LLAP_IO_VRB_QUEUE_LIMIT_BASE("hive.llap.io.vrb.queue.limit.base", 50000, "The default queue size for VRBs produced by a LLAP IO thread when the processing is\n" + "slower than the IO. The actual queue size is set per fragment, and is adjusted down\n" + "from the base, depending on the schema."), LLAP_IO_VRB_QUEUE_LIMIT_MIN("hive.llap.io.vrb.queue.limit.min", 10, "The minimum queue size for VRBs produced by a LLAP IO thread when the processing is\n" + "slower than the IO (used when determining the size from base size)."), LLAP_IO_SHARE_OBJECT_POOLS("hive.llap.io.share.object.pools", false, "Whether to used shared object pools in LLAP IO. A safety flag."), LLAP_AUTO_ALLOW_UBER("hive.llap.auto.allow.uber", false, "Whether or not to allow the planner to run vertices in the AM."), LLAP_AUTO_ENFORCE_TREE("hive.llap.auto.enforce.tree", true, "Enforce that all parents are in llap, before considering vertex"), LLAP_AUTO_ENFORCE_VECTORIZED("hive.llap.auto.enforce.vectorized", true, "Enforce that inputs are vectorized, before considering vertex"), LLAP_AUTO_ENFORCE_STATS("hive.llap.auto.enforce.stats", true, "Enforce that col stats are available, before considering vertex"), LLAP_AUTO_MAX_INPUT("hive.llap.auto.max.input.size", 10*1024*1024*1024L, "Check input size, before considering vertex (-1 disables check)"), LLAP_AUTO_MAX_OUTPUT("hive.llap.auto.max.output.size", 1*1024*1024*1024L, "Check output size, before considering vertex (-1 disables check)"), LLAP_SKIP_COMPILE_UDF_CHECK("hive.llap.skip.compile.udf.check", false, "Whether to skip the compile-time check for non-built-in UDFs when deciding whether to\n" + "execute tasks in LLAP. Skipping the check allows executing UDFs from pre-localized\n" + "jars in LLAP; if the jars are not pre-localized, the UDFs will simply fail to load."), LLAP_ALLOW_PERMANENT_FNS("hive.llap.allow.permanent.fns", true, "Whether LLAP decider should allow permanent UDFs."), LLAP_EXECUTION_MODE("hive.llap.execution.mode", "none", new StringSet("auto", "none", "all", "map", "only"), "Chooses whether query fragments will run in container or in llap"), LLAP_OBJECT_CACHE_ENABLED("hive.llap.object.cache.enabled", true, "Cache objects (plans, hashtables, etc) in llap"), LLAP_IO_DECODING_METRICS_PERCENTILE_INTERVALS("hive.llap.io.decoding.metrics.percentiles.intervals", "30", "Comma-delimited set of integers denoting the desired rollover intervals (in seconds)\n" + "for percentile latency metrics on the LLAP daemon IO decoding time.\n" + "hive.llap.queue.metrics.percentiles.intervals"), LLAP_IO_THREADPOOL_SIZE("hive.llap.io.threadpool.size", 10, "Specify the number of threads to use for low-level IO thread pool."), LLAP_KERBEROS_PRINCIPAL(HIVE_LLAP_DAEMON_SERVICE_PRINCIPAL_NAME, "", "The name of the LLAP daemon's service principal."), LLAP_KERBEROS_KEYTAB_FILE("hive.llap.daemon.keytab.file", "", "The path to the Kerberos Keytab file containing the LLAP daemon's service principal."), LLAP_WEBUI_SPNEGO_KEYTAB_FILE("hive.llap.webui.spnego.keytab", "", "The path to the Kerberos Keytab file containing the LLAP WebUI SPNEGO principal.\n" + "Typical value would look like /etc/security/keytabs/spnego.service.keytab."), LLAP_WEBUI_SPNEGO_PRINCIPAL("hive.llap.webui.spnego.principal", "", "The LLAP WebUI SPNEGO service principal. Configured similarly to\n" + "hive.server2.webui.spnego.principal"), LLAP_FS_KERBEROS_PRINCIPAL("hive.llap.task.principal", "", "The name of the principal to use to run tasks. By default, the clients are required\n" + "to provide tokens to access HDFS/etc."), LLAP_FS_KERBEROS_KEYTAB_FILE("hive.llap.task.keytab.file", "", "The path to the Kerberos Keytab file containing the principal to use to run tasks.\n" + "By default, the clients are required to provide tokens to access HDFS/etc."), LLAP_ZKSM_ZK_CONNECTION_STRING("hive.llap.zk.sm.connectionString", "", "ZooKeeper connection string for ZooKeeper SecretManager."), LLAP_ZKSM_ZK_SESSION_TIMEOUT("hive.llap.zk.sm.session.timeout", "40s", new TimeValidator( TimeUnit.MILLISECONDS), "ZooKeeper session timeout for ZK SecretManager."), LLAP_ZK_REGISTRY_USER("hive.llap.zk.registry.user", "", "In the LLAP ZooKeeper-based registry, specifies the username in the Zookeeper path.\n" + "This should be the hive user or whichever user is running the LLAP daemon."), LLAP_ZK_REGISTRY_NAMESPACE("hive.llap.zk.registry.namespace", null, "In the LLAP ZooKeeper-based registry, overrides the ZK path namespace. Note that\n" + "using this makes the path management (e.g. setting correct ACLs) your responsibility."), // Note: do not rename to ..service.acl; Hadoop generates .hosts setting name from this, // resulting in a collision with existing hive.llap.daemon.service.hosts and bizarre errors. // These are read by Hadoop IPC, so you should check the usage and naming conventions (e.g. // ".blocked" is a string hardcoded by Hadoop, and defaults are enforced elsewhere in Hive) // before making changes or copy-pasting these. LLAP_SECURITY_ACL("hive.llap.daemon.acl", "*", "The ACL for LLAP daemon."), LLAP_SECURITY_ACL_DENY("hive.llap.daemon.acl.blocked", "", "The deny ACL for LLAP daemon."), LLAP_MANAGEMENT_ACL("hive.llap.management.acl", "*", "The ACL for LLAP daemon management."), LLAP_MANAGEMENT_ACL_DENY("hive.llap.management.acl.blocked", "", "The deny ACL for LLAP daemon management."), LLAP_PLUGIN_ACL("hive.llap.plugin.acl", "*", "The ACL for LLAP plugin AM endpoint."), LLAP_PLUGIN_ACL_DENY("hive.llap.plugin.acl.blocked", "", "The deny ACL for LLAP plugin AM endpoint."), LLAP_REMOTE_TOKEN_REQUIRES_SIGNING("hive.llap.remote.token.requires.signing", "true", new StringSet("false", "except_llap_owner", "true"), "Whether the token returned from LLAP management API should require fragment signing.\n" + "True by default; can be disabled to allow CLI to get tokens from LLAP in a secure\n" + "cluster by setting it to true or 'except_llap_owner' (the latter returns such tokens\n" + "to everyone except the user LLAP cluster is authenticating under)."), // Hadoop DelegationTokenManager default is 1 week. LLAP_DELEGATION_TOKEN_LIFETIME("hive.llap.daemon.delegation.token.lifetime", "14d", new TimeValidator(TimeUnit.SECONDS), "LLAP delegation token lifetime, in seconds if specified without a unit."), LLAP_MANAGEMENT_RPC_PORT("hive.llap.management.rpc.port", 15004, "RPC port for LLAP daemon management service."), LLAP_WEB_AUTO_AUTH("hive.llap.auto.auth", false, "Whether or not to set Hadoop configs to enable auth in LLAP web app."), LLAP_DAEMON_RPC_NUM_HANDLERS("hive.llap.daemon.rpc.num.handlers", 5, "Number of RPC handlers for LLAP daemon.", "llap.daemon.rpc.num.handlers"), LLAP_PLUGIN_RPC_NUM_HANDLERS("hive.llap.plugin.rpc.num.handlers", 1, "Number of RPC handlers for AM LLAP plugin endpoint."), LLAP_DAEMON_WORK_DIRS("hive.llap.daemon.work.dirs", "", "Working directories for the daemon. This should not be set if running as a YARN\n" + "application via Slider. It must be set when not running via Slider on YARN. If the value\n" + "is set when running as a Slider YARN application, the specified value will be used.", "llap.daemon.work.dirs"), LLAP_DAEMON_YARN_SHUFFLE_PORT("hive.llap.daemon.yarn.shuffle.port", 15551, "YARN shuffle port for LLAP-daemon-hosted shuffle.", "llap.daemon.yarn.shuffle.port"), LLAP_DAEMON_YARN_CONTAINER_MB("hive.llap.daemon.yarn.container.mb", -1, "llap server yarn container size in MB. Used in LlapServiceDriver and package.py", "llap.daemon.yarn.container.mb"), LLAP_DAEMON_QUEUE_NAME("hive.llap.daemon.queue.name", null, "Queue name within which the llap slider application will run." + " Used in LlapServiceDriver and package.py"), // TODO Move the following 2 properties out of Configuration to a constant. LLAP_DAEMON_CONTAINER_ID("hive.llap.daemon.container.id", null, "ContainerId of a running LlapDaemon. Used to publish to the registry"), LLAP_DAEMON_NM_ADDRESS("hive.llap.daemon.nm.address", null, "NM Address host:rpcPort for the NodeManager on which the instance of the daemon is running.\n" + "Published to the llap registry. Should never be set by users"), LLAP_DAEMON_SHUFFLE_DIR_WATCHER_ENABLED("hive.llap.daemon.shuffle.dir.watcher.enabled", false, "TODO doc", "llap.daemon.shuffle.dir-watcher.enabled"), LLAP_DAEMON_AM_LIVENESS_HEARTBEAT_INTERVAL_MS( "hive.llap.daemon.am.liveness.heartbeat.interval.ms", "10000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Tez AM-LLAP heartbeat interval (milliseconds). This needs to be below the task timeout\n" + "interval, but otherwise as high as possible to avoid unnecessary traffic.", "llap.daemon.am.liveness.heartbeat.interval-ms"), LLAP_DAEMON_AM_LIVENESS_CONNECTION_TIMEOUT_MS( "hive.llap.am.liveness.connection.timeout.ms", "10000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Amount of time to wait on connection failures to the AM from an LLAP daemon before\n" + "considering the AM to be dead.", "llap.am.liveness.connection.timeout-millis"), LLAP_DAEMON_AM_USE_FQDN("hive.llap.am.use.fqdn", true, "Whether to use FQDN of the AM machine when submitting work to LLAP."), // Not used yet - since the Writable RPC engine does not support this policy. LLAP_DAEMON_AM_LIVENESS_CONNECTION_SLEEP_BETWEEN_RETRIES_MS( "hive.llap.am.liveness.connection.sleep.between.retries.ms", "2000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Sleep duration while waiting to retry connection failures to the AM from the daemon for\n" + "the general keep-alive thread (milliseconds).", "llap.am.liveness.connection.sleep-between-retries-millis"), LLAP_DAEMON_TASK_SCHEDULER_TIMEOUT_SECONDS( "hive.llap.task.scheduler.timeout.seconds", "60s", new TimeValidator(TimeUnit.SECONDS), "Amount of time to wait before failing the query when there are no llap daemons running\n" + "(alive) in the cluster.", "llap.daemon.scheduler.timeout.seconds"), LLAP_DAEMON_NUM_EXECUTORS("hive.llap.daemon.num.executors", 4, "Number of executors to use in LLAP daemon; essentially, the number of tasks that can be\n" + "executed in parallel.", "llap.daemon.num.executors"), LLAP_MAPJOIN_MEMORY_OVERSUBSCRIBE_FACTOR("hive.llap.mapjoin.memory.oversubscribe.factor", 0.2f, "Fraction of memory from hive.auto.convert.join.noconditionaltask.size that can be over subscribed\n" + "by queries running in LLAP mode. This factor has to be from 0.0 to 1.0. Default is 20% over subscription.\n"), LLAP_MEMORY_OVERSUBSCRIPTION_MAX_EXECUTORS_PER_QUERY("hive.llap.memory.oversubscription.max.executors.per.query", 3, "Used along with hive.llap.mapjoin.memory.oversubscribe.factor to limit the number of executors from\n" + "which memory for mapjoin can be borrowed. Default 3 (from 3 other executors\n" + "hive.llap.mapjoin.memory.oversubscribe.factor amount of memory can be borrowed based on which mapjoin\n" + "conversion decision will be made). This is only an upper bound. Lower bound is determined by number of\n" + "executors and configured max concurrency."), LLAP_MAPJOIN_MEMORY_MONITOR_CHECK_INTERVAL("hive.llap.mapjoin.memory.monitor.check.interval", 100000L, "Check memory usage of mapjoin hash tables after every interval of this many rows. If map join hash table\n" + "memory usage exceeds (hive.auto.convert.join.noconditionaltask.size * hive.hash.table.inflation.factor)\n" + "when running in LLAP, tasks will get killed and not retried. Set the value to 0 to disable this feature."), LLAP_DAEMON_AM_REPORTER_MAX_THREADS("hive.llap.daemon.am-reporter.max.threads", 4, "Maximum number of threads to be used for AM reporter. If this is lower than number of\n" + "executors in llap daemon, it would be set to number of executors at runtime.", "llap.daemon.am-reporter.max.threads"), LLAP_DAEMON_RPC_PORT("hive.llap.daemon.rpc.port", 0, "The LLAP daemon RPC port.", "llap.daemon.rpc.port. A value of 0 indicates a dynamic port"), LLAP_DAEMON_MEMORY_PER_INSTANCE_MB("hive.llap.daemon.memory.per.instance.mb", 4096, "The total amount of memory to use for the executors inside LLAP (in megabytes).", "llap.daemon.memory.per.instance.mb"), LLAP_DAEMON_XMX_HEADROOM("hive.llap.daemon.xmx.headroom", "5%", "The total amount of heap memory set aside by LLAP and not used by the executors. Can\n" + "be specified as size (e.g. '512Mb'), or percentage (e.g. '5%'). Note that the latter is\n" + "derived from the total daemon XMX, which can be different from the total executor\n" + "memory if the cache is on-heap; although that's not the default configuration."), LLAP_DAEMON_VCPUS_PER_INSTANCE("hive.llap.daemon.vcpus.per.instance", 4, "The total number of vcpus to use for the executors inside LLAP.", "llap.daemon.vcpus.per.instance"), LLAP_DAEMON_NUM_FILE_CLEANER_THREADS("hive.llap.daemon.num.file.cleaner.threads", 1, "Number of file cleaner threads in LLAP.", "llap.daemon.num.file.cleaner.threads"), LLAP_FILE_CLEANUP_DELAY_SECONDS("hive.llap.file.cleanup.delay.seconds", "300s", new TimeValidator(TimeUnit.SECONDS), "How long to delay before cleaning up query files in LLAP (in seconds, for debugging).", "llap.file.cleanup.delay-seconds"), LLAP_DAEMON_SERVICE_HOSTS("hive.llap.daemon.service.hosts", null, "Explicitly specified hosts to use for LLAP scheduling. Useful for testing. By default,\n" + "YARN registry is used.", "llap.daemon.service.hosts"), LLAP_DAEMON_SERVICE_REFRESH_INTERVAL("hive.llap.daemon.service.refresh.interval.sec", "60s", new TimeValidator(TimeUnit.SECONDS), "LLAP YARN registry service list refresh delay, in seconds.", "llap.daemon.service.refresh.interval"), LLAP_DAEMON_COMMUNICATOR_NUM_THREADS("hive.llap.daemon.communicator.num.threads", 10, "Number of threads to use in LLAP task communicator in Tez AM.", "llap.daemon.communicator.num.threads"), LLAP_PLUGIN_CLIENT_NUM_THREADS("hive.llap.plugin.client.num.threads", 10, "Number of threads to use in LLAP task plugin client."), LLAP_DAEMON_DOWNLOAD_PERMANENT_FNS("hive.llap.daemon.download.permanent.fns", false, "Whether LLAP daemon should localize the resources for permanent UDFs."), LLAP_TASK_SCHEDULER_AM_REGISTRY_NAME("hive.llap.task.scheduler.am.registry", "llap", "AM registry name for LLAP task scheduler plugin to register with."), LLAP_TASK_SCHEDULER_AM_REGISTRY_PRINCIPAL("hive.llap.task.scheduler.am.registry.principal", "", "The name of the principal used to access ZK AM registry securely."), LLAP_TASK_SCHEDULER_AM_REGISTRY_KEYTAB_FILE("hive.llap.task.scheduler.am.registry.keytab.file", "", "The path to the Kerberos keytab file used to access ZK AM registry securely."), LLAP_TASK_SCHEDULER_NODE_REENABLE_MIN_TIMEOUT_MS( "hive.llap.task.scheduler.node.reenable.min.timeout.ms", "200ms", new TimeValidator(TimeUnit.MILLISECONDS), "Minimum time after which a previously disabled node will be re-enabled for scheduling,\n" + "in milliseconds. This may be modified by an exponential back-off if failures persist.", "llap.task.scheduler.node.re-enable.min.timeout.ms"), LLAP_TASK_SCHEDULER_NODE_REENABLE_MAX_TIMEOUT_MS( "hive.llap.task.scheduler.node.reenable.max.timeout.ms", "10000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Maximum time after which a previously disabled node will be re-enabled for scheduling,\n" + "in milliseconds. This may be modified by an exponential back-off if failures persist.", "llap.task.scheduler.node.re-enable.max.timeout.ms"), LLAP_TASK_SCHEDULER_NODE_DISABLE_BACK_OFF_FACTOR( "hive.llap.task.scheduler.node.disable.backoff.factor", 1.5f, "Backoff factor on successive blacklists of a node due to some failures. Blacklist times\n" + "start at the min timeout and go up to the max timeout based on this backoff factor.", "llap.task.scheduler.node.disable.backoff.factor"), LLAP_TASK_SCHEDULER_PREEMPT_INDEPENDENT("hive.llap.task.scheduler.preempt.independent", false, "Whether the AM LLAP scheduler should preempt a lower priority task for a higher pri one\n" + "even if the former doesn't depend on the latter (e.g. for two parallel sides of a union)."), LLAP_TASK_SCHEDULER_NUM_SCHEDULABLE_TASKS_PER_NODE( "hive.llap.task.scheduler.num.schedulable.tasks.per.node", 0, "The number of tasks the AM TaskScheduler will try allocating per node. 0 indicates that\n" + "this should be picked up from the Registry. -1 indicates unlimited capacity; positive\n" + "values indicate a specific bound.", "llap.task.scheduler.num.schedulable.tasks.per.node"), LLAP_TASK_SCHEDULER_LOCALITY_DELAY( "hive.llap.task.scheduler.locality.delay", "0ms", new TimeValidator(TimeUnit.MILLISECONDS, -1l, true, Long.MAX_VALUE, true), "Amount of time to wait before allocating a request which contains location information," + " to a location other than the ones requested. Set to -1 for an infinite delay, 0" + "for no delay." ), LLAP_DAEMON_TASK_PREEMPTION_METRICS_INTERVALS( "hive.llap.daemon.task.preemption.metrics.intervals", "30,60,300", "Comma-delimited set of integers denoting the desired rollover intervals (in seconds)\n" + " for percentile latency metrics. Used by LLAP daemon task scheduler metrics for\n" + " time taken to kill task (due to pre-emption) and useful time wasted by the task that\n" + " is about to be preempted." ), LLAP_DAEMON_TASK_SCHEDULER_WAIT_QUEUE_SIZE("hive.llap.daemon.task.scheduler.wait.queue.size", 10, "LLAP scheduler maximum queue size.", "llap.daemon.task.scheduler.wait.queue.size"), LLAP_DAEMON_WAIT_QUEUE_COMPARATOR_CLASS_NAME( "hive.llap.daemon.wait.queue.comparator.class.name", "org.apache.hadoop.hive.llap.daemon.impl.comparator.ShortestJobFirstComparator", "The priority comparator to use for LLAP scheduler priority queue. The built-in options\n" + "are org.apache.hadoop.hive.llap.daemon.impl.comparator.ShortestJobFirstComparator and\n" + ".....FirstInFirstOutComparator", "llap.daemon.wait.queue.comparator.class.name"), LLAP_DAEMON_TASK_SCHEDULER_ENABLE_PREEMPTION( "hive.llap.daemon.task.scheduler.enable.preemption", true, "Whether non-finishable running tasks (e.g. a reducer waiting for inputs) should be\n" + "preempted by finishable tasks inside LLAP scheduler.", "llap.daemon.task.scheduler.enable.preemption"), LLAP_TASK_COMMUNICATOR_CONNECTION_TIMEOUT_MS( "hive.llap.task.communicator.connection.timeout.ms", "16000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Connection timeout (in milliseconds) before a failure to an LLAP daemon from Tez AM.", "llap.task.communicator.connection.timeout-millis"), LLAP_TASK_COMMUNICATOR_LISTENER_THREAD_COUNT( "hive.llap.task.communicator.listener.thread-count", 30, "The number of task communicator listener threads."), LLAP_TASK_COMMUNICATOR_CONNECTION_SLEEP_BETWEEN_RETRIES_MS( "hive.llap.task.communicator.connection.sleep.between.retries.ms", "2000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Sleep duration (in milliseconds) to wait before retrying on error when obtaining a\n" + "connection to LLAP daemon from Tez AM.", "llap.task.communicator.connection.sleep-between-retries-millis"), LLAP_DAEMON_WEB_PORT("hive.llap.daemon.web.port", 15002, "LLAP daemon web UI port.", "llap.daemon.service.port"), LLAP_DAEMON_WEB_SSL("hive.llap.daemon.web.ssl", false, "Whether LLAP daemon web UI should use SSL.", "llap.daemon.service.ssl"), LLAP_CLIENT_CONSISTENT_SPLITS("hive.llap.client.consistent.splits", true, "Whether to setup split locations to match nodes on which llap daemons are running, " + "instead of using the locations provided by the split itself. If there is no llap daemon " + "running, fall back to locations provided by the split. This is effective only if " + "hive.execution.mode is llap"), LLAP_VALIDATE_ACLS("hive.llap.validate.acls", true, "Whether LLAP should reject permissive ACLs in some cases (e.g. its own management\n" + "protocol or ZK paths), similar to how ssh refuses a key with bad access permissions."), LLAP_DAEMON_OUTPUT_SERVICE_PORT("hive.llap.daemon.output.service.port", 15003, "LLAP daemon output service port"), LLAP_DAEMON_OUTPUT_STREAM_TIMEOUT("hive.llap.daemon.output.stream.timeout", "120s", new TimeValidator(TimeUnit.SECONDS), "The timeout for the client to connect to LLAP output service and start the fragment\n" + "output after sending the fragment. The fragment will fail if its output is not claimed."), LLAP_DAEMON_OUTPUT_SERVICE_SEND_BUFFER_SIZE("hive.llap.daemon.output.service.send.buffer.size", 128 * 1024, "Send buffer size to be used by LLAP daemon output service"), LLAP_DAEMON_OUTPUT_SERVICE_MAX_PENDING_WRITES("hive.llap.daemon.output.service.max.pending.writes", 8, "Maximum number of queued writes allowed per connection when sending data\n" + " via the LLAP output service to external clients."), LLAP_ENABLE_GRACE_JOIN_IN_LLAP("hive.llap.enable.grace.join.in.llap", false, "Override if grace join should be allowed to run in llap."), LLAP_HS2_ENABLE_COORDINATOR("hive.llap.hs2.coordinator.enabled", true, "Whether to create the LLAP coordinator; since execution engine and container vs llap\n" + "settings are both coming from job configs, we don't know at start whether this should\n" + "be created. Default true."), LLAP_DAEMON_LOGGER("hive.llap.daemon.logger", Constants.LLAP_LOGGER_NAME_QUERY_ROUTING, new StringSet(Constants.LLAP_LOGGER_NAME_QUERY_ROUTING, Constants.LLAP_LOGGER_NAME_RFA, Constants.LLAP_LOGGER_NAME_CONSOLE), "logger used for llap-daemons."), HIVE_TRIGGER_VALIDATION_INTERVAL("hive.trigger.validation.interval", "500ms", new TimeValidator(TimeUnit.MILLISECONDS), "Interval for validating triggers during execution of a query. Triggers defined in resource plan will get\n" + "validated for all SQL operations after every defined interval (default: 500ms) and corresponding action\n" + "defined in the trigger will be taken"), SPARK_USE_OP_STATS("hive.spark.use.op.stats", true, "Whether to use operator stats to determine reducer parallelism for Hive on Spark.\n" + "If this is false, Hive will use source table stats to determine reducer\n" + "parallelism for all first level reduce tasks, and the maximum reducer parallelism\n" + "from all parents for all the rest (second level and onward) reducer tasks."), SPARK_USE_TS_STATS_FOR_MAPJOIN("hive.spark.use.ts.stats.for.mapjoin", false, "If this is set to true, mapjoin optimization in Hive/Spark will use statistics from\n" + "TableScan operators at the root of operator tree, instead of parent ReduceSink\n" + "operators of the Join operator."), SPARK_OPTIMIZE_SHUFFLE_SERDE("hive.spark.optimize.shuffle.serde", false, "If this is set to true, Hive on Spark will register custom serializers for data types\n" + "in shuffle. This should result in less shuffled data."), SPARK_CLIENT_FUTURE_TIMEOUT("hive.spark.client.future.timeout", "60s", new TimeValidator(TimeUnit.SECONDS), "Timeout for requests from Hive client to remote Spark driver."), SPARK_JOB_MONITOR_TIMEOUT("hive.spark.job.monitor.timeout", "60s", new TimeValidator(TimeUnit.SECONDS), "Timeout for job monitor to get Spark job state."), SPARK_RPC_CLIENT_CONNECT_TIMEOUT("hive.spark.client.connect.timeout", "1000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Timeout for remote Spark driver in connecting back to Hive client."), SPARK_RPC_CLIENT_HANDSHAKE_TIMEOUT("hive.spark.client.server.connect.timeout", "90000ms", new TimeValidator(TimeUnit.MILLISECONDS), "Timeout for handshake between Hive client and remote Spark driver. Checked by both processes."), SPARK_RPC_SECRET_RANDOM_BITS("hive.spark.client.secret.bits", "256", "Number of bits of randomness in the generated secret for communication between Hive client and remote Spark driver. " + "Rounded down to the nearest multiple of 8."), SPARK_RPC_MAX_THREADS("hive.spark.client.rpc.threads", 8, "Maximum number of threads for remote Spark driver's RPC event loop."), SPARK_RPC_MAX_MESSAGE_SIZE("hive.spark.client.rpc.max.size", 50 * 1024 * 1024, "Maximum message size in bytes for communication between Hive client and remote Spark driver. Default is 50MB."), SPARK_RPC_CHANNEL_LOG_LEVEL("hive.spark.client.channel.log.level", null, "Channel logging level for remote Spark driver. One of {DEBUG, ERROR, INFO, TRACE, WARN}."), SPARK_RPC_SASL_MECHANISM("hive.spark.client.rpc.sasl.mechanisms", "DIGEST-MD5", "Name of the SASL mechanism to use for authentication."), SPARK_RPC_SERVER_ADDRESS("hive.spark.client.rpc.server.address", "", "The server address of HiverServer2 host to be used for communication between Hive client and remote Spark driver. " + "Default is empty, which means the address will be determined in the same way as for hive.server2.thrift.bind.host." + "This is only necessary if the host has multiple network addresses and if a different network address other than " + "hive.server2.thrift.bind.host is to be used."), SPARK_RPC_SERVER_PORT("hive.spark.client.rpc.server.port", "", "A list of port ranges which can be used by RPC server " + "with the format of 49152-49222,49228 and a random one is selected from the list. Default is empty, which randomly " + "selects one port from all available ones."), SPARK_DYNAMIC_PARTITION_PRUNING( "hive.spark.dynamic.partition.pruning", false, "When dynamic pruning is enabled, joins on partition keys will be processed by writing\n" + "to a temporary HDFS file, and read later for removing unnecessary partitions."), SPARK_DYNAMIC_PARTITION_PRUNING_MAX_DATA_SIZE( "hive.spark.dynamic.partition.pruning.max.data.size", 100*1024*1024L, "Maximum total data size in dynamic pruning."), SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY( "hive.spark.dynamic.partition.pruning.map.join.only", false, "Turn on dynamic partition pruning only for map joins.\n" + "If hive.spark.dynamic.partition.pruning is set to true, this parameter value is ignored."), SPARK_USE_GROUPBY_SHUFFLE( "hive.spark.use.groupby.shuffle", true, "Spark groupByKey transformation has better performance but uses unbounded memory." + "Turn this off when there is a memory issue."), SPARK_JOB_MAX_TASKS("hive.spark.job.max.tasks", -1, "The maximum number of tasks a Spark job may have.\n" + "If a Spark job contains more tasks than the maximum, it will be cancelled. A value of -1 means no limit."), SPARK_STAGE_MAX_TASKS("hive.spark.stage.max.tasks", -1, "The maximum number of tasks a stage in a Spark job may have.\n" + "If a Spark job stage contains more tasks than the maximum, the job will be cancelled. A value of -1 means no limit."), NWAYJOINREORDER("hive.reorder.nway.joins", true, "Runs reordering of tables within single n-way join (i.e.: picks streamtable)"), HIVE_MERGE_NWAY_JOINS("hive.merge.nway.joins", true, "Merge adjacent joins into a single n-way join"), HIVE_LOG_N_RECORDS("hive.log.every.n.records", 0L, new RangeValidator(0L, null), "If value is greater than 0 logs in fixed intervals of size n rather than exponentially."), HIVE_MSCK_PATH_VALIDATION("hive.msck.path.validation", "throw", new StringSet("throw", "skip", "ignore"), "The approach msck should take with HDFS " + "directories that are partition-like but contain unsupported characters. 'throw' (an " + "exception) is the default; 'skip' will skip the invalid directories and still repair the" + " others; 'ignore' will skip the validation (legacy behavior, causes bugs in many cases)"), HIVE_MSCK_REPAIR_BATCH_SIZE( "hive.msck.repair.batch.size", 3000, "Batch size for the msck repair command. If the value is greater than zero,\n " + "it will execute batch wise with the configured batch size. In case of errors while\n" + "adding unknown partitions the batch size is automatically reduced by half in the subsequent\n" + "retry attempt. The default value is 3000 which means it will execute in the batches of 3000."), HIVE_MSCK_REPAIR_BATCH_MAX_RETRIES("hive.msck.repair.batch.max.retries", 4, "Maximum number of retries for the msck repair command when adding unknown partitions.\n " + "If the value is greater than zero it will retry adding unknown partitions until the maximum\n" + "number of attempts is reached or batch size is reduced to 0, whichever is earlier.\n" + "In each retry attempt it will reduce the batch size by a factor of 2 until it reaches zero.\n" + "If the value is set to zero it will retry until the batch size becomes zero as described above."), HIVE_SERVER2_LLAP_CONCURRENT_QUERIES("hive.server2.llap.concurrent.queries", -1, "The number of queries allowed in parallel via llap. Negative number implies 'infinite'."), HIVE_TEZ_ENABLE_MEMORY_MANAGER("hive.tez.enable.memory.manager", true, "Enable memory manager for tez"), HIVE_HASH_TABLE_INFLATION_FACTOR("hive.hash.table.inflation.factor", (float) 2.0, "Expected inflation factor between disk/in memory representation of hash tables"), HIVE_LOG_TRACE_ID("hive.log.trace.id", "", "Log tracing id that can be used by upstream clients for tracking respective logs. " + "Truncated to " + LOG_PREFIX_LENGTH + " characters. Defaults to use auto-generated session id."), HIVE_METASTORE_MM_THREAD_SCAN_INTERVAL("hive.metastore.mm.thread.scan.interval", "900s", new TimeValidator(TimeUnit.SECONDS), "MM table housekeeping thread interval in this metastore instance. 0 to disable."), HIVE_METASTORE_MM_HEARTBEAT_TIMEOUT("hive.metastore.mm.heartbeat.timeout", "1800s", new TimeValidator(TimeUnit.SECONDS), "MM write ID times out after this long if a heartbeat is not send. Currently disabled."), HIVE_METASTORE_MM_ABSOLUTE_TIMEOUT("hive.metastore.mm.absolute.timeout", "7d", new TimeValidator(TimeUnit.SECONDS), "MM write ID cannot be outstanding for more than this long."), HIVE_METASTORE_MM_ABORTED_GRACE_PERIOD("hive.metastore.mm.aborted.grace.period", "1d", new TimeValidator(TimeUnit.SECONDS), "MM write ID will not be removed up for that long after it has been aborted;\n" + "this is to work around potential races e.g. with FS visibility, when deleting files."), HIVE_MM_AVOID_GLOBSTATUS_ON_S3("hive.mm.avoid.s3.globstatus", true, "Whether to use listFiles (optimized on S3) instead of globStatus when on S3."), // If a parameter is added to the restricted list, add a test in TestRestrictedList.Java HIVE_CONF_RESTRICTED_LIST("hive.conf.restricted.list", "hive.security.authenticator.manager,hive.security.authorization.manager," + "hive.security.metastore.authorization.manager,hive.security.metastore.authenticator.manager," + "hive.users.in.admin.role,hive.server2.xsrf.filter.enabled,hive.security.authorization.enabled," + "hive.distcp.privileged.doAs," + "hive.server2.authentication.ldap.baseDN," + "hive.server2.authentication.ldap.url," + "hive.server2.authentication.ldap.Domain," + "hive.server2.authentication.ldap.groupDNPattern," + "hive.server2.authentication.ldap.groupFilter," + "hive.server2.authentication.ldap.userDNPattern," + "hive.server2.authentication.ldap.userFilter," + "hive.server2.authentication.ldap.groupMembershipKey," + "hive.server2.authentication.ldap.userMembershipKey," + "hive.server2.authentication.ldap.groupClassKey," + "hive.server2.authentication.ldap.customLDAPQuery," + "hive.privilege.synchronizer," + "hive.privilege.synchronizer.interval," + "hive.spark.client.connect.timeout," + "hive.spark.client.server.connect.timeout," + "hive.spark.client.channel.log.level," + "hive.spark.client.rpc.max.size," + "hive.spark.client.rpc.threads," + "hive.spark.client.secret.bits," + "hive.spark.client.rpc.server.address," + "hive.spark.client.rpc.server.port," + "hive.spark.client.rpc.sasl.mechanisms," + "bonecp.,"+ "hive.druid.broker.address.default,"+ "hive.druid.coordinator.address.default,"+ "hikari.,"+ "hadoop.bin.path,"+ "yarn.bin.path,"+ "spark.home", "Comma separated list of configuration options which are immutable at runtime"), HIVE_CONF_HIDDEN_LIST("hive.conf.hidden.list", METASTOREPWD.varname + "," + HIVE_SUPER_USER.varname + "," + HIVE_SUPERUSER_ALLOWED_IMPERSONATION.varname // Add ssl-server.xml conf properties + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_KEYSTORE_LOCATION_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_KEYSTORE_PASSWORD_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_KEYSTORE_KEYPASSWORD_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_KEYSTORE_TYPE_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_RELOAD_INTERVAL_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_TYPE_TPL_KEY) + "," + FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_EXCLUDE_CIPHER_LIST) // these properties should not be used by Hive, that's why there is no enum. However they are in the ssl-server.xml // which is available to the daemons. As such we should avoid to print them when a user requests a property dump or // value for a specific field. + ",hops.jwt-manager.master-token" + ",hops.jwt-manager.renew-token-0" + ",hops.jwt-manager.renew-token-1" + ",hops.jwt-manager.renew-token-2" + ",hops.jwt-manager.renew-token-3" + ",hops.jwt-manager.renew-token-4" // Adding the S3 credentials from Hadoop config to be hidden + ",fs.s3.awsAccessKeyId" + ",fs.s3.awsSecretAccessKey" + ",fs.s3n.awsAccessKeyId" + ",fs.s3n.awsSecretAccessKey" + ",fs.s3a.access.key" + ",fs.s3a.secret.key" + ",fs.s3a.proxy.password" // HopsTLS config + ",dfs.adls.oauth2.credential" + ",fs.adl.oauth2.credential", "Comma separated list of configuration options which should not be read by normal user like passwords"), HIVE_CONF_INTERNAL_VARIABLE_LIST("hive.conf.internal.variable.list", "hive.added.files.path,hive.added.jars.path,hive.added.archives.path", "Comma separated list of variables which are used internally and should not be configurable."), HIVE_SPARK_RSC_CONF_LIST("hive.spark.rsc.conf.list", SPARK_OPTIMIZE_SHUFFLE_SERDE.varname + "," + SPARK_CLIENT_FUTURE_TIMEOUT.varname, "Comma separated list of variables which are related to remote spark context.\n" + "Changing these variables will result in re-creating the spark session."), HIVE_QUERY_TIMEOUT_SECONDS("hive.query.timeout.seconds", "0s", new TimeValidator(TimeUnit.SECONDS), "Timeout for Running Query in seconds. A nonpositive value means infinite. " + "If the query timeout is also set by thrift API call, the smaller one will be taken."), HIVE_EXEC_INPUT_LISTING_MAX_THREADS("hive.exec.input.listing.max.threads", 0, new SizeValidator(0L, true, 1024L, true), "Maximum number of threads that Hive uses to list file information from file systems (recommended > 1 for blobstore)."), HIVE_QUERY_REEXECUTION_ENABLED("hive.query.reexecution.enabled", true, "Enable query reexecutions"), HIVE_QUERY_REEXECUTION_STRATEGIES("hive.query.reexecution.strategies", "overlay,reoptimize", "comma separated list of plugin can be used:\n" + " overlay: hiveconf subtree 'reexec.overlay' is used as an overlay in case of an execution errors out\n" + " reoptimize: collects operator statistics during execution and recompile the query after a failure"), HIVE_QUERY_REEXECUTION_STATS_PERSISTENCE("hive.query.reexecution.stats.persist.scope", "query", new StringSet("query", "hiveserver", "metastore"), "Sets the persistence scope of runtime statistics\n" + " query: runtime statistics are only used during re-execution\n" + " hiveserver: runtime statistics are persisted in the hiveserver - all sessions share it\n" + " metastore: runtime statistics are persisted in the metastore as well"), HIVE_QUERY_MAX_REEXECUTION_COUNT("hive.query.reexecution.max.count", 1, "Maximum number of re-executions for a single query."), HIVE_QUERY_REEXECUTION_ALWAYS_COLLECT_OPERATOR_STATS("hive.query.reexecution.always.collect.operator.stats", false, "If sessionstats are enabled; this option can be used to collect statistics all the time"), HIVE_QUERY_REEXECUTION_STATS_CACHE_BATCH_SIZE("hive.query.reexecution.stats.cache.batch.size", -1, "If runtime stats are stored in metastore; the maximal batch size per round during load."), HIVE_QUERY_REEXECUTION_STATS_CACHE_SIZE("hive.query.reexecution.stats.cache.size", 100_000, "Size of the runtime statistics cache. Unit is: OperatorStat entry; a query plan consist ~100."), HIVE_QUERY_RESULTS_CACHE_ENABLED("hive.query.results.cache.enabled", true, "If the query results cache is enabled. This will keep results of previously executed queries " + "to be reused if the same query is executed again."), HIVE_QUERY_RESULTS_CACHE_NONTRANSACTIONAL_TABLES_ENABLED("hive.query.results.cache.nontransactional.tables.enabled", false, "If the query results cache is enabled for queries involving non-transactional tables." + "Users who enable this setting should be willing to tolerate some amount of stale results in the cache."), HIVE_QUERY_RESULTS_CACHE_WAIT_FOR_PENDING_RESULTS("hive.query.results.cache.wait.for.pending.results", true, "Should a query wait for the pending results of an already running query, " + "in order to use the cached result when it becomes ready"), HIVE_QUERY_RESULTS_CACHE_DIRECTORY("hive.query.results.cache.directory", "/tmp/hive/_resultscache_", "Location of the query results cache directory. Temporary results from queries " + "will be moved to this location."), HIVE_QUERY_RESULTS_CACHE_MAX_ENTRY_LIFETIME("hive.query.results.cache.max.entry.lifetime", "3600s", new TimeValidator(TimeUnit.SECONDS), "Maximum lifetime in seconds for an entry in the query results cache. A nonpositive value means infinite."), HIVE_QUERY_RESULTS_CACHE_MAX_SIZE("hive.query.results.cache.max.size", (long) 2 * 1024 * 1024 * 1024, "Maximum total size in bytes that the query results cache directory is allowed to use on the filesystem."), HIVE_QUERY_RESULTS_CACHE_MAX_ENTRY_SIZE("hive.query.results.cache.max.entry.size", (long) 10 * 1024 * 1024, "Maximum size in bytes that a single query result is allowed to use in the results cache directory"), HIVE_NOTFICATION_EVENT_POLL_INTERVAL("hive.notification.event.poll.interval", "60s", new TimeValidator(TimeUnit.SECONDS), "How often the notification log is polled for new NotificationEvents from the metastore." + "A nonpositive value means the notification log is never polled."), HIVE_NOTFICATION_EVENT_CONSUMERS("hive.notification.event.consumers", "org.apache.hadoop.hive.ql.cache.results.QueryResultsCache$InvalidationEventConsumer", "Comma-separated list of class names extending EventConsumer," + "to handle the NotificationEvents retreived by the notification event poll."), /* BLOBSTORE section */ HIVE_BLOBSTORE_SUPPORTED_SCHEMES("hive.blobstore.supported.schemes", "s3,s3a,s3n", "Comma-separated list of supported blobstore schemes."), HIVE_BLOBSTORE_USE_BLOBSTORE_AS_SCRATCHDIR("hive.blobstore.use.blobstore.as.scratchdir", false, "Enable the use of scratch directories directly on blob storage systems (it may cause performance penalties)."), HIVE_BLOBSTORE_OPTIMIZATIONS_ENABLED("hive.blobstore.optimizations.enabled", true, "This parameter enables a number of optimizations when running on blobstores:\n" + "(1) If hive.blobstore.use.blobstore.as.scratchdir is false, force the last Hive job to write to the blobstore.\n" + "This is a performance optimization that forces the final FileSinkOperator to write to the blobstore.\n" + "See HIVE-15121 for details."); public final String varname; public final String altName; private final String defaultExpr; public final String defaultStrVal; public final int defaultIntVal; public final long defaultLongVal; public final float defaultFloatVal; public final boolean defaultBoolVal; private final Class<?> valClass; private final VarType valType; private final Validator validator; private final String description; private final boolean excluded; private final boolean caseSensitive; ConfVars(String varname, Object defaultVal, String description) { this(varname, defaultVal, null, description, true, false, null); } ConfVars(String varname, Object defaultVal, String description, String altName) { this(varname, defaultVal, null, description, true, false, altName); } ConfVars(String varname, Object defaultVal, Validator validator, String description, String altName) { this(varname, defaultVal, validator, description, true, false, altName); } ConfVars(String varname, Object defaultVal, String description, boolean excluded) { this(varname, defaultVal, null, description, true, excluded, null); } ConfVars(String varname, String defaultVal, boolean caseSensitive, String description) { this(varname, defaultVal, null, description, caseSensitive, false, null); } ConfVars(String varname, Object defaultVal, Validator validator, String description) { this(varname, defaultVal, validator, description, true, false, null); } ConfVars(String varname, Object defaultVal, Validator validator, String description, boolean excluded) { this(varname, defaultVal, validator, description, true, excluded, null); } ConfVars(String varname, Object defaultVal, Validator validator, String description, boolean caseSensitive, boolean excluded, String altName) { this.varname = varname; this.validator = validator; this.description = description; this.defaultExpr = defaultVal == null ? null : String.valueOf(defaultVal); this.excluded = excluded; this.caseSensitive = caseSensitive; this.altName = altName; if (defaultVal == null || defaultVal instanceof String) { this.valClass = String.class; this.valType = VarType.STRING; this.defaultStrVal = SystemVariables.substitute((String)defaultVal); this.defaultIntVal = -1; this.defaultLongVal = -1; this.defaultFloatVal = -1; this.defaultBoolVal = false; } else if (defaultVal instanceof Integer) { this.valClass = Integer.class; this.valType = VarType.INT; this.defaultStrVal = null; this.defaultIntVal = (Integer)defaultVal; this.defaultLongVal = -1; this.defaultFloatVal = -1; this.defaultBoolVal = false; } else if (defaultVal instanceof Long) { this.valClass = Long.class; this.valType = VarType.LONG; this.defaultStrVal = null; this.defaultIntVal = -1; this.defaultLongVal = (Long)defaultVal; this.defaultFloatVal = -1; this.defaultBoolVal = false; } else if (defaultVal instanceof Float) { this.valClass = Float.class; this.valType = VarType.FLOAT; this.defaultStrVal = null; this.defaultIntVal = -1; this.defaultLongVal = -1; this.defaultFloatVal = (Float)defaultVal; this.defaultBoolVal = false; } else if (defaultVal instanceof Boolean) { this.valClass = Boolean.class; this.valType = VarType.BOOLEAN; this.defaultStrVal = null; this.defaultIntVal = -1; this.defaultLongVal = -1; this.defaultFloatVal = -1; this.defaultBoolVal = (Boolean)defaultVal; } else { throw new IllegalArgumentException("Not supported type value " + defaultVal.getClass() + " for name " + varname); } } public boolean isType(String value) { return valType.isType(value); } public Validator getValidator() { return validator; } public String validate(String value) { return validator == null ? null : validator.validate(value); } public String validatorDescription() { return validator == null ? null : validator.toDescription(); } public String typeString() { String type = valType.typeString(); if (valType == VarType.STRING && validator != null) { if (validator instanceof TimeValidator) { type += "(TIME)"; } } return type; } public String getRawDescription() { return description; } public String getDescription() { String validator = validatorDescription(); if (validator != null) { return validator + ".\n" + description; } return description; } public boolean isExcluded() { return excluded; } public boolean isCaseSensitive() { return caseSensitive; } @Override public String toString() { return varname; } private static String findHadoopBinary() { String val = findHadoopHome(); // if can't find hadoop home we can at least try /usr/bin/hadoop val = (val == null ? File.separator + "usr" : val) + File.separator + "bin" + File.separator + "hadoop"; // Launch hadoop command file on windows. return val; } private static String findYarnBinary() { String val = findHadoopHome(); val = (val == null ? "yarn" : val + File.separator + "bin" + File.separator + "yarn"); return val; } private static String findMapRedBinary() { String val = findHadoopHome(); val = (val == null ? "mapred" : val + File.separator + "bin" + File.separator + "mapred"); return val; } private static String findHadoopHome() { String val = System.getenv("HADOOP_HOME"); // In Hadoop 1.X and Hadoop 2.X HADOOP_HOME is gone and replaced with HADOOP_PREFIX if (val == null) { val = System.getenv("HADOOP_PREFIX"); } return val; } public String getDefaultValue() { return valType.defaultValueString(this); } public String getDefaultExpr() { return defaultExpr; } private Set<String> getValidStringValues() { if (validator == null || !(validator instanceof StringSet)) { throw new RuntimeException(varname + " does not specify a list of valid values"); } return ((StringSet)validator).getExpected(); } enum VarType { STRING { @Override void checkType(String value) throws Exception { } @Override String defaultValueString(ConfVars confVar) { return confVar.defaultStrVal; } }, INT { @Override void checkType(String value) throws Exception { Integer.valueOf(value); } }, LONG { @Override void checkType(String value) throws Exception { Long.valueOf(value); } }, FLOAT { @Override void checkType(String value) throws Exception { Float.valueOf(value); } }, BOOLEAN { @Override void checkType(String value) throws Exception { Boolean.valueOf(value); } }; boolean isType(String value) { try { checkType(value); } catch (Exception e) { return false; } return true; } String typeString() { return name().toUpperCase();} String defaultValueString(ConfVars confVar) { return confVar.defaultExpr; } abstract void checkType(String value) throws Exception; } } /** * Writes the default ConfVars out to a byte array and returns an input * stream wrapping that byte array. * * We need this in order to initialize the ConfVar properties * in the underling Configuration object using the addResource(InputStream) * method. * * It is important to use a LoopingByteArrayInputStream because it turns out * addResource(InputStream) is broken since Configuration tries to read the * entire contents of the same InputStream repeatedly without resetting it. * LoopingByteArrayInputStream has special logic to handle this. */ private static synchronized InputStream getConfVarInputStream() { if (confVarByteArray == null) { try { // Create a Hadoop configuration without inheriting default settings. Configuration conf = new Configuration(false); applyDefaultNonNullConfVars(conf); ByteArrayOutputStream confVarBaos = new ByteArrayOutputStream(); conf.writeXml(confVarBaos); confVarByteArray = confVarBaos.toByteArray(); } catch (Exception e) { // We're pretty screwed if we can't load the default conf vars throw new RuntimeException("Failed to initialize default Hive configuration variables!", e); } } return new LoopingByteArrayInputStream(confVarByteArray); } public void verifyAndSet(String name, String value) throws IllegalArgumentException { if (modWhiteListPattern != null) { Matcher wlMatcher = modWhiteListPattern.matcher(name); if (!wlMatcher.matches()) { throw new IllegalArgumentException("Cannot modify " + name + " at runtime. " + "It is not in list of params that are allowed to be modified at runtime"); } } if (Iterables.any(restrictList, restrictedVar -> name != null && name.startsWith(restrictedVar))) { throw new IllegalArgumentException("Cannot modify " + name + " at runtime. It is in the list" + " of parameters that can't be modified at runtime or is prefixed by a restricted variable"); } String oldValue = name != null ? get(name) : null; if (name == null || value == null || !value.equals(oldValue)) { // When either name or value is null, the set method below will fail, // and throw IllegalArgumentException set(name, value); if (isSparkRelatedConfig(name)) { isSparkConfigUpdated = true; } } } public boolean isHiddenConfig(String name) { return Iterables.any(hiddenSet, hiddenVar -> name.startsWith(hiddenVar)); } public static boolean isEncodedPar(String name) { for (ConfVars confVar : HiveConf.ENCODED_CONF) { ConfVars confVar1 = confVar; if (confVar1.varname.equals(name)) { return true; } } return false; } /** * check whether spark related property is updated, which includes spark configurations, * RSC configurations and yarn configuration in Spark on YARN mode. * @param name * @return */ private boolean isSparkRelatedConfig(String name) { boolean result = false; if (name.startsWith("spark")) { // Spark property. // for now we don't support changing spark app name on the fly result = !name.equals("spark.app.name"); } else if (name.startsWith("yarn")) { // YARN property in Spark on YARN mode. String sparkMaster = get("spark.master"); if (sparkMaster != null && sparkMaster.startsWith("yarn")) { result = true; } } else if (rscList.stream().anyMatch(rscVar -> rscVar.equals(name))) { // Remote Spark Context property. result = true; } else if (name.equals("mapreduce.job.queuename")) { // a special property starting with mapreduce that we would also like to effect if it changes result = true; } return result; } public static int getIntVar(Configuration conf, ConfVars var) { assert (var.valClass == Integer.class) : var.varname; if (var.altName != null) { return conf.getInt(var.varname, conf.getInt(var.altName, var.defaultIntVal)); } return conf.getInt(var.varname, var.defaultIntVal); } public static void setIntVar(Configuration conf, ConfVars var, int val) { assert (var.valClass == Integer.class) : var.varname; conf.setInt(var.varname, val); } public int getIntVar(ConfVars var) { return getIntVar(this, var); } public void setIntVar(ConfVars var, int val) { setIntVar(this, var, val); } public static long getTimeVar(Configuration conf, ConfVars var, TimeUnit outUnit) { return toTime(getVar(conf, var), getDefaultTimeUnit(var), outUnit); } public static void setTimeVar(Configuration conf, ConfVars var, long time, TimeUnit timeunit) { assert (var.valClass == String.class) : var.varname; conf.set(var.varname, time + stringFor(timeunit)); } public long getTimeVar(ConfVars var, TimeUnit outUnit) { return getTimeVar(this, var, outUnit); } public void setTimeVar(ConfVars var, long time, TimeUnit outUnit) { setTimeVar(this, var, time, outUnit); } public static long getSizeVar(Configuration conf, ConfVars var) { return toSizeBytes(getVar(conf, var)); } public long getSizeVar(ConfVars var) { return getSizeVar(this, var); } public static TimeUnit getDefaultTimeUnit(ConfVars var) { TimeUnit inputUnit = null; if (var.validator instanceof TimeValidator) { inputUnit = ((TimeValidator)var.validator).getTimeUnit(); } return inputUnit; } public static long toTime(String value, TimeUnit inputUnit, TimeUnit outUnit) { String[] parsed = parseNumberFollowedByUnit(value.trim()); return outUnit.convert(Long.parseLong(parsed[0].trim()), unitFor(parsed[1].trim(), inputUnit)); } public static long toSizeBytes(String value) { String[] parsed = parseNumberFollowedByUnit(value.trim()); return Long.parseLong(parsed[0].trim()) * multiplierFor(parsed[1].trim()); } private static String[] parseNumberFollowedByUnit(String value) { char[] chars = value.toCharArray(); int i = 0; for (; i < chars.length && (chars[i] == '-' || Character.isDigit(chars[i])); i++) { } return new String[] {value.substring(0, i), value.substring(i)}; } private static Set<String> daysSet = ImmutableSet.of("d", "D", "day", "DAY", "days", "DAYS"); private static Set<String> hoursSet = ImmutableSet.of("h", "H", "hour", "HOUR", "hours", "HOURS"); private static Set<String> minutesSet = ImmutableSet.of("m", "M", "min", "MIN", "mins", "MINS", "minute", "MINUTE", "minutes", "MINUTES"); private static Set<String> secondsSet = ImmutableSet.of("s", "S", "sec", "SEC", "secs", "SECS", "second", "SECOND", "seconds", "SECONDS"); private static Set<String> millisSet = ImmutableSet.of("ms", "MS", "msec", "MSEC", "msecs", "MSECS", "millisecond", "MILLISECOND", "milliseconds", "MILLISECONDS"); private static Set<String> microsSet = ImmutableSet.of("us", "US", "usec", "USEC", "usecs", "USECS", "microsecond", "MICROSECOND", "microseconds", "MICROSECONDS"); private static Set<String> nanosSet = ImmutableSet.of("ns", "NS", "nsec", "NSEC", "nsecs", "NSECS", "nanosecond", "NANOSECOND", "nanoseconds", "NANOSECONDS"); public static TimeUnit unitFor(String unit, TimeUnit defaultUnit) { unit = unit.trim().toLowerCase(); if (unit.isEmpty() || unit.equals("l")) { if (defaultUnit == null) { throw new IllegalArgumentException("Time unit is not specified"); } return defaultUnit; } else if (daysSet.contains(unit)) { return TimeUnit.DAYS; } else if (hoursSet.contains(unit)) { return TimeUnit.HOURS; } else if (minutesSet.contains(unit)) { return TimeUnit.MINUTES; } else if (secondsSet.contains(unit)) { return TimeUnit.SECONDS; } else if (millisSet.contains(unit)) { return TimeUnit.MILLISECONDS; } else if (microsSet.contains(unit)) { return TimeUnit.MICROSECONDS; } else if (nanosSet.contains(unit)) { return TimeUnit.NANOSECONDS; } throw new IllegalArgumentException("Invalid time unit " + unit); } public static long multiplierFor(String unit) { unit = unit.trim().toLowerCase(); if (unit.isEmpty() || unit.equals("b") || unit.equals("bytes")) { return 1; } else if (unit.equals("kb")) { return 1024; } else if (unit.equals("mb")) { return 1024*1024; } else if (unit.equals("gb")) { return 1024*1024*1024; } else if (unit.equals("tb")) { return 1024L*1024*1024*1024; } else if (unit.equals("pb")) { return 1024L*1024*1024*1024*1024; } throw new IllegalArgumentException("Invalid size unit " + unit); } public static String stringFor(TimeUnit timeunit) { switch (timeunit) { case DAYS: return "day"; case HOURS: return "hour"; case MINUTES: return "min"; case SECONDS: return "sec"; case MILLISECONDS: return "msec"; case MICROSECONDS: return "usec"; case NANOSECONDS: return "nsec"; } throw new IllegalArgumentException("Invalid timeunit " + timeunit); } public static long getLongVar(Configuration conf, ConfVars var) { assert (var.valClass == Long.class) : var.varname; if (var.altName != null) { return conf.getLong(var.varname, conf.getLong(var.altName, var.defaultLongVal)); } return conf.getLong(var.varname, var.defaultLongVal); } public static long getLongVar(Configuration conf, ConfVars var, long defaultVal) { if (var.altName != null) { return conf.getLong(var.varname, conf.getLong(var.altName, defaultVal)); } return conf.getLong(var.varname, defaultVal); } public static void setLongVar(Configuration conf, ConfVars var, long val) { assert (var.valClass == Long.class) : var.varname; conf.setLong(var.varname, val); } public long getLongVar(ConfVars var) { return getLongVar(this, var); } public void setLongVar(ConfVars var, long val) { setLongVar(this, var, val); } public static float getFloatVar(Configuration conf, ConfVars var) { assert (var.valClass == Float.class) : var.varname; if (var.altName != null) { return conf.getFloat(var.varname, conf.getFloat(var.altName, var.defaultFloatVal)); } return conf.getFloat(var.varname, var.defaultFloatVal); } public static float getFloatVar(Configuration conf, ConfVars var, float defaultVal) { if (var.altName != null) { return conf.getFloat(var.varname, conf.getFloat(var.altName, defaultVal)); } return conf.getFloat(var.varname, defaultVal); } public static void setFloatVar(Configuration conf, ConfVars var, float val) { assert (var.valClass == Float.class) : var.varname; conf.setFloat(var.varname, val); } public float getFloatVar(ConfVars var) { return getFloatVar(this, var); } public void setFloatVar(ConfVars var, float val) { setFloatVar(this, var, val); } public static boolean getBoolVar(Configuration conf, ConfVars var) { assert (var.valClass == Boolean.class) : var.varname; if (var.altName != null) { return conf.getBoolean(var.varname, conf.getBoolean(var.altName, var.defaultBoolVal)); } return conf.getBoolean(var.varname, var.defaultBoolVal); } public static boolean getBoolVar(Configuration conf, ConfVars var, boolean defaultVal) { if (var.altName != null) { return conf.getBoolean(var.varname, conf.getBoolean(var.altName, defaultVal)); } return conf.getBoolean(var.varname, defaultVal); } public static void setBoolVar(Configuration conf, ConfVars var, boolean val) { assert (var.valClass == Boolean.class) : var.varname; conf.setBoolean(var.varname, val); } /* Dynamic partition pruning is enabled in some or all cases if either * hive.spark.dynamic.partition.pruning is true or * hive.spark.dynamic.partition.pruning.map.join.only is true */ public static boolean isSparkDPPAny(Configuration conf) { return (conf.getBoolean(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING.varname, ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING.defaultBoolVal) || conf.getBoolean(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY.varname, ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY.defaultBoolVal)); } public boolean getBoolVar(ConfVars var) { return getBoolVar(this, var); } public void setBoolVar(ConfVars var, boolean val) { setBoolVar(this, var, val); } public static String getVar(Configuration conf, ConfVars var) { assert (var.valClass == String.class) : var.varname; return var.altName != null ? conf.get(var.varname, conf.get(var.altName, var.defaultStrVal)) : conf.get(var.varname, var.defaultStrVal); } public static String getVarWithoutType(Configuration conf, ConfVars var) { return var.altName != null ? conf.get(var.varname, conf.get(var.altName, var.defaultExpr)) : conf.get(var.varname, var.defaultExpr); } public static String getTrimmedVar(Configuration conf, ConfVars var) { assert (var.valClass == String.class) : var.varname; if (var.altName != null) { return conf.getTrimmed(var.varname, conf.getTrimmed(var.altName, var.defaultStrVal)); } return conf.getTrimmed(var.varname, var.defaultStrVal); } public static String[] getTrimmedStringsVar(Configuration conf, ConfVars var) { assert (var.valClass == String.class) : var.varname; String[] result = conf.getTrimmedStrings(var.varname, (String[])null); if (result != null) { return result; } if (var.altName != null) { result = conf.getTrimmedStrings(var.altName, (String[])null); if (result != null) { return result; } } return org.apache.hadoop.util.StringUtils.getTrimmedStrings(var.defaultStrVal); } public static String getVar(Configuration conf, ConfVars var, String defaultVal) { String ret = var.altName != null ? conf.get(var.varname, conf.get(var.altName, defaultVal)) : conf.get(var.varname, defaultVal); return ret; } public static String getVar(Configuration conf, ConfVars var, EncoderDecoder<String, String> encoderDecoder) { return encoderDecoder.decode(getVar(conf, var)); } public String getLogIdVar(String defaultValue) { String retval = getVar(ConfVars.HIVE_LOG_TRACE_ID); if (StringUtils.EMPTY.equals(retval)) { LOG.info("Using the default value passed in for log id: {}", defaultValue); retval = defaultValue; } if (retval.length() > LOG_PREFIX_LENGTH) { LOG.warn("The original log id prefix is {} has been truncated to {}", retval, retval.substring(0, LOG_PREFIX_LENGTH - 1)); retval = retval.substring(0, LOG_PREFIX_LENGTH - 1); } return retval; } public static void setVar(Configuration conf, ConfVars var, String val) { assert (var.valClass == String.class) : var.varname; conf.set(var.varname, val); } public static void setVar(Configuration conf, ConfVars var, String val, EncoderDecoder<String, String> encoderDecoder) { setVar(conf, var, encoderDecoder.encode(val)); } public static ConfVars getConfVars(String name) { return vars.get(name); } public static ConfVars getMetaConf(String name) { return metaConfs.get(name); } public String getVar(ConfVars var) { return getVar(this, var); } public void setVar(ConfVars var, String val) { setVar(this, var, val); } public String getQueryString() { return getQueryString(this); } public static String getQueryString(Configuration conf) { return getVar(conf, ConfVars.HIVEQUERYSTRING, EncoderDecoderFactory.URL_ENCODER_DECODER); } public void setQueryString(String query) { setQueryString(this, query); } public static void setQueryString(Configuration conf, String query) { setVar(conf, ConfVars.HIVEQUERYSTRING, query, EncoderDecoderFactory.URL_ENCODER_DECODER); } public void logVars(PrintStream ps) { for (ConfVars one : ConfVars.values()) { ps.println(one.varname + "=" + ((get(one.varname) != null) ? get(one.varname) : "")); } } public HiveConf() { super(); initialize(this.getClass()); } public HiveConf(Class<?> cls) { super(); initialize(cls); } public HiveConf(Configuration other, Class<?> cls) { super(other); initialize(cls); } /** * Copy constructor */ public HiveConf(HiveConf other) { super(other); hiveJar = other.hiveJar; auxJars = other.auxJars; isSparkConfigUpdated = other.isSparkConfigUpdated; origProp = (Properties)other.origProp.clone(); restrictList.addAll(other.restrictList); hiddenSet.addAll(other.hiddenSet); modWhiteListPattern = other.modWhiteListPattern; } public Properties getAllProperties() { return getProperties(this); } public static Properties getProperties(Configuration conf) { Iterator<Map.Entry<String, String>> iter = conf.iterator(); Properties p = new Properties(); while (iter.hasNext()) { Map.Entry<String, String> e = iter.next(); p.setProperty(e.getKey(), e.getValue()); } return p; } private void initialize(Class<?> cls) { hiveJar = (new JobConf(cls)).getJar(); // preserve the original configuration origProp = getAllProperties(); // Overlay the ConfVars. Note that this ignores ConfVars with null values addResource(getConfVarInputStream()); // Overlay hive-site.xml if it exists if (hiveSiteURL != null) { addResource(hiveSiteURL); } // if embedded metastore is to be used as per config so far // then this is considered like the metastore server case String msUri = this.getVar(HiveConf.ConfVars.METASTOREURIS); // This is hackery, but having hive-common depend on standalone-metastore is really bad // because it will pull all of the metastore code into every module. We need to check that // we aren't using the standalone metastore. If we are, we should treat it the same as a // remote metastore situation. if (msUri == null || msUri.isEmpty()) { msUri = this.get("metastore.thrift.uris"); } LOG.debug("Found metastore URI of " + msUri); if(HiveConfUtil.isEmbeddedMetaStore(msUri)){ setLoadMetastoreConfig(true); } // load hivemetastore-site.xml if this is metastore and file exists if (isLoadMetastoreConfig() && hivemetastoreSiteUrl != null) { addResource(hivemetastoreSiteUrl); } // load hiveserver2-site.xml if this is hiveserver2 and file exists // metastore can be embedded within hiveserver2, in such cases // the conf params in hiveserver2-site.xml will override whats defined // in hivemetastore-site.xml if (isLoadHiveServer2Config() && hiveServer2SiteUrl != null) { addResource(hiveServer2SiteUrl); } // Load ssl-server.xml (in HADOOP_CONF_DIR) if we are not in the context of a client if (this.getBoolVar(ConfVars.HIVE_LOAD_SSL_SERVER)) { String resource = get(SSLFactory.SSL_SERVER_CONF_KEY, "ssl-server.xml"); URL resourceURL = ClassLoader.getSystemResource(resource); if (resourceURL != null && (new File(resourceURL.getPath()).canRead())) { addResource(resource); } else { LOG.warn("Could not load ssl-server, this is probably a client so it is fine. Continuing."); } } // Overlay the values of any system properties whose names appear in the list of ConfVars applySystemProperties(); if ((this.get("hive.metastore.ds.retry.attempts") != null) || this.get("hive.metastore.ds.retry.interval") != null) { LOG.warn("DEPRECATED: hive.metastore.ds.retry.* no longer has any effect. " + "Use hive.hmshandler.retry.* instead"); } // if the running class was loaded directly (through eclipse) rather than through a // jar then this would be needed if (hiveJar == null) { hiveJar = this.get(ConfVars.HIVEJAR.varname); } if (auxJars == null) { auxJars = StringUtils.join(FileUtils.getJarFilesByPath(this.get(ConfVars.HIVEAUXJARS.varname), this), ','); } if (getBoolVar(HiveConf.ConfVars.HIVECONFVALIDATION)) { List<String> trimmed = new ArrayList<String>(); for (Map.Entry<String,String> entry : this) { String key = entry.getKey(); if (key == null || !key.startsWith("hive.")) { continue; } ConfVars var = HiveConf.getConfVars(key); if (var == null) { var = HiveConf.getConfVars(key.trim()); if (var != null) { trimmed.add(key); } } if (var == null) { LOG.warn("HiveConf of name {} does not exist", key); } else if (!var.isType(entry.getValue())) { LOG.warn("HiveConf {} expects {} type value", var.varname, var.typeString()); } } for (String key : trimmed) { set(key.trim(), getRaw(key)); unset(key); } } setupSQLStdAuthWhiteList(); // setup list of conf vars that are not allowed to change runtime setupRestrictList(); hiddenSet.clear(); hiddenSet.addAll(HiveConfUtil.getHiddenSet(this)); setupRSCList(); } /** * If the config whitelist param for sql standard authorization is not set, set it up here. */ private void setupSQLStdAuthWhiteList() { String whiteListParamsStr = getVar(ConfVars.HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST); if (whiteListParamsStr == null || whiteListParamsStr.trim().isEmpty()) { // set the default configs in whitelist whiteListParamsStr = getSQLStdAuthDefaultWhiteListPattern(); } setVar(ConfVars.HIVE_AUTHORIZATION_SQL_STD_AUTH_CONFIG_WHITELIST, whiteListParamsStr); } private static String getSQLStdAuthDefaultWhiteListPattern() { // create the default white list from list of safe config params // and regex list String confVarPatternStr = Joiner.on("|").join(convertVarsToRegex(sqlStdAuthSafeVarNames)); String regexPatternStr = Joiner.on("|").join(sqlStdAuthSafeVarNameRegexes); return regexPatternStr + "|" + confVarPatternStr; } /** * Obtains the local time-zone ID. */ public ZoneId getLocalTimeZone() { String timeZoneStr = getVar(ConfVars.HIVE_LOCAL_TIME_ZONE); return TimestampTZUtil.parseTimeZone(timeZoneStr); } /** * @param paramList list of parameter strings * @return list of parameter strings with "." replaced by "\." */ private static String[] convertVarsToRegex(String[] paramList) { String[] regexes = new String[paramList.length]; for(int i=0; i<paramList.length; i++) { regexes[i] = paramList[i].replace(".", "\\." ); } return regexes; } /** * Default list of modifiable config parameters for sql standard authorization * For internal use only. */ private static final String [] sqlStdAuthSafeVarNames = new String [] { ConfVars.AGGR_JOIN_TRANSPOSE.varname, ConfVars.BYTESPERREDUCER.varname, ConfVars.CLIENT_STATS_COUNTERS.varname, ConfVars.DEFAULTPARTITIONNAME.varname, ConfVars.DROPIGNORESNONEXISTENT.varname, ConfVars.HIVECOUNTERGROUP.varname, ConfVars.HIVEDEFAULTMANAGEDFILEFORMAT.varname, ConfVars.HIVEENFORCEBUCKETMAPJOIN.varname, ConfVars.HIVEENFORCESORTMERGEBUCKETMAPJOIN.varname, ConfVars.HIVEEXPREVALUATIONCACHE.varname, ConfVars.HIVEQUERYRESULTFILEFORMAT.varname, ConfVars.HIVEHASHTABLELOADFACTOR.varname, ConfVars.HIVEHASHTABLETHRESHOLD.varname, ConfVars.HIVEIGNOREMAPJOINHINT.varname, ConfVars.HIVELIMITMAXROWSIZE.varname, ConfVars.HIVEMAPREDMODE.varname, ConfVars.HIVEMAPSIDEAGGREGATE.varname, ConfVars.HIVEOPTIMIZEMETADATAQUERIES.varname, ConfVars.HIVEROWOFFSET.varname, ConfVars.HIVEVARIABLESUBSTITUTE.varname, ConfVars.HIVEVARIABLESUBSTITUTEDEPTH.varname, ConfVars.HIVE_AUTOGEN_COLUMNALIAS_PREFIX_INCLUDEFUNCNAME.varname, ConfVars.HIVE_AUTOGEN_COLUMNALIAS_PREFIX_LABEL.varname, ConfVars.HIVE_CHECK_CROSS_PRODUCT.varname, ConfVars.HIVE_CLI_TEZ_SESSION_ASYNC.varname, ConfVars.HIVE_COMPAT.varname, ConfVars.HIVE_DISPLAY_PARTITION_COLUMNS_SEPARATELY.varname, ConfVars.HIVE_ERROR_ON_EMPTY_PARTITION.varname, ConfVars.HIVE_EXECUTION_ENGINE.varname, ConfVars.HIVE_EXEC_COPYFILE_MAXSIZE.varname, ConfVars.HIVE_EXIM_URI_SCHEME_WL.varname, ConfVars.HIVE_FILE_MAX_FOOTER.varname, ConfVars.HIVE_INSERT_INTO_MULTILEVEL_DIRS.varname, ConfVars.HIVE_LOCALIZE_RESOURCE_NUM_WAIT_ATTEMPTS.varname, ConfVars.HIVE_MULTI_INSERT_MOVE_TASKS_SHARE_DEPENDENCIES.varname, ConfVars.HIVE_QUERY_RESULTS_CACHE_ENABLED.varname, ConfVars.HIVE_QUERY_RESULTS_CACHE_WAIT_FOR_PENDING_RESULTS.varname, ConfVars.HIVE_QUOTEDID_SUPPORT.varname, ConfVars.HIVE_RESULTSET_USE_UNIQUE_COLUMN_NAMES.varname, ConfVars.HIVE_STATS_COLLECT_PART_LEVEL_STATS.varname, ConfVars.HIVE_SCHEMA_EVOLUTION.varname, ConfVars.HIVE_SERVER2_LOGGING_OPERATION_LEVEL.varname, ConfVars.HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS.varname, ConfVars.HIVE_SUPPORT_SPECICAL_CHARACTERS_IN_TABLE_NAMES.varname, ConfVars.JOB_DEBUG_CAPTURE_STACKTRACES.varname, ConfVars.JOB_DEBUG_TIMEOUT.varname, ConfVars.LLAP_IO_ENABLED.varname, ConfVars.LLAP_IO_USE_FILEID_PATH.varname, ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname, ConfVars.LLAP_EXECUTION_MODE.varname, ConfVars.LLAP_AUTO_ALLOW_UBER.varname, ConfVars.LLAP_AUTO_ENFORCE_TREE.varname, ConfVars.LLAP_AUTO_ENFORCE_VECTORIZED.varname, ConfVars.LLAP_AUTO_ENFORCE_STATS.varname, ConfVars.LLAP_AUTO_MAX_INPUT.varname, ConfVars.LLAP_AUTO_MAX_OUTPUT.varname, ConfVars.LLAP_SKIP_COMPILE_UDF_CHECK.varname, ConfVars.LLAP_CLIENT_CONSISTENT_SPLITS.varname, ConfVars.LLAP_ENABLE_GRACE_JOIN_IN_LLAP.varname, ConfVars.LLAP_ALLOW_PERMANENT_FNS.varname, ConfVars.MAXCREATEDFILES.varname, ConfVars.MAXREDUCERS.varname, ConfVars.NWAYJOINREORDER.varname, ConfVars.OUTPUT_FILE_EXTENSION.varname, ConfVars.SHOW_JOB_FAIL_DEBUG_INFO.varname, ConfVars.TASKLOG_DEBUG_TIMEOUT.varname, ConfVars.HIVEQUERYID.varname, }; /** * Default list of regexes for config parameters that are modifiable with * sql standard authorization enabled */ static final String [] sqlStdAuthSafeVarNameRegexes = new String [] { "hive\\.auto\\..*", "hive\\.cbo\\..*", "hive\\.convert\\..*", "hive\\.druid\\..*", "hive\\.exec\\.dynamic\\.partition.*", "hive\\.exec\\.max\\.dynamic\\.partitions.*", "hive\\.exec\\.compress\\..*", "hive\\.exec\\.infer\\..*", "hive\\.exec\\.mode.local\\..*", "hive\\.exec\\.orc\\..*", "hive\\.exec\\.parallel.*", "hive\\.explain\\..*", "hive\\.fetch.task\\..*", "hive\\.groupby\\..*", "hive\\.hbase\\..*", "hive\\.index\\..*", "hive\\.index\\..*", "hive\\.intermediate\\..*", "hive\\.join\\..*", "hive\\.limit\\..*", "hive\\.log\\..*", "hive\\.mapjoin\\..*", "hive\\.merge\\..*", "hive\\.optimize\\..*", "hive\\.orc\\..*", "hive\\.outerjoin\\..*", "hive\\.parquet\\..*", "hive\\.ppd\\..*", "hive\\.prewarm\\..*", "hive\\.server2\\.thrift\\.resultset\\.default\\.fetch\\.size", "hive\\.server2\\.proxy\\.user", "hive\\.skewjoin\\..*", "hive\\.smbjoin\\..*", "hive\\.stats\\..*", "hive\\.strict\\..*", "hive\\.tez\\..*", "hive\\.vectorized\\..*", "fs\\.defaultFS", "ssl\\.client\\.truststore\\.location", "distcp\\.atomic", "distcp\\.ignore\\.failures", "distcp\\.preserve\\.status", "distcp\\.preserve\\.rawxattrs", "distcp\\.sync\\.folders", "distcp\\.delete\\.missing\\.source", "distcp\\.keystore\\.resource", "distcp\\.liststatus\\.threads", "distcp\\.max\\.maps", "distcp\\.copy\\.strategy", "distcp\\.skip\\.crc", "distcp\\.copy\\.overwrite", "distcp\\.copy\\.append", "distcp\\.map\\.bandwidth\\.mb", "distcp\\.dynamic\\..*", "distcp\\.meta\\.folder", "distcp\\.copy\\.listing\\.class", "distcp\\.filters\\.class", "distcp\\.options\\.skipcrccheck", "distcp\\.options\\.m", "distcp\\.options\\.numListstatusThreads", "distcp\\.options\\.mapredSslConf", "distcp\\.options\\.bandwidth", "distcp\\.options\\.overwrite", "distcp\\.options\\.strategy", "distcp\\.options\\.i", "distcp\\.options\\.p.*", "distcp\\.options\\.update", "distcp\\.options\\.delete", "mapred\\.map\\..*", "mapred\\.reduce\\..*", "mapred\\.output\\.compression\\.codec", "mapred\\.job\\.queue\\.name", "mapred\\.output\\.compression\\.type", "mapred\\.min\\.split\\.size", "mapreduce\\.job\\.reduce\\.slowstart\\.completedmaps", "mapreduce\\.job\\.queuename", "mapreduce\\.job\\.tags", "mapreduce\\.input\\.fileinputformat\\.split\\.minsize", "mapreduce\\.map\\..*", "mapreduce\\.reduce\\..*", "mapreduce\\.output\\.fileoutputformat\\.compress\\.codec", "mapreduce\\.output\\.fileoutputformat\\.compress\\.type", "oozie\\..*", "tez\\.am\\..*", "tez\\.task\\..*", "tez\\.runtime\\..*", "tez\\.queue\\.name", }; /** * Apply system properties to this object if the property name is defined in ConfVars * and the value is non-null and not an empty string. */ private void applySystemProperties() { Map<String, String> systemProperties = getConfSystemProperties(); for (Entry<String, String> systemProperty : systemProperties.entrySet()) { this.set(systemProperty.getKey(), systemProperty.getValue()); } } /** * This method returns a mapping from config variable name to its value for all config variables * which have been set using System properties */ public static Map<String, String> getConfSystemProperties() { Map<String, String> systemProperties = new HashMap<String, String>(); for (ConfVars oneVar : ConfVars.values()) { if (System.getProperty(oneVar.varname) != null) { if (System.getProperty(oneVar.varname).length() > 0) { systemProperties.put(oneVar.varname, System.getProperty(oneVar.varname)); } } } return systemProperties; } /** * Overlays ConfVar properties with non-null values */ private static void applyDefaultNonNullConfVars(Configuration conf) { for (ConfVars var : ConfVars.values()) { String defaultValue = var.getDefaultValue(); if (defaultValue == null) { // Don't override ConfVars with null values continue; } conf.set(var.varname, defaultValue); } } public Properties getChangedProperties() { Properties ret = new Properties(); Properties newProp = getAllProperties(); for (Object one : newProp.keySet()) { String oneProp = (String) one; String oldValue = origProp.getProperty(oneProp); if (!StringUtils.equals(oldValue, newProp.getProperty(oneProp))) { ret.setProperty(oneProp, newProp.getProperty(oneProp)); } } return (ret); } public String getJar() { return hiveJar; } /** * @return the auxJars */ public String getAuxJars() { return auxJars; } /** * Set the auxiliary jars. Used for unit tests only. * @param auxJars the auxJars to set. */ public void setAuxJars(String auxJars) { this.auxJars = auxJars; setVar(this, ConfVars.HIVEAUXJARS, auxJars); } public URL getHiveDefaultLocation() { return hiveDefaultURL; } public static void setHiveSiteLocation(URL location) { hiveSiteURL = location; } public static void setHivemetastoreSiteUrl(URL location) { hivemetastoreSiteUrl = location; } public static URL getHiveSiteLocation() { return hiveSiteURL; } public static URL getMetastoreSiteLocation() { return hivemetastoreSiteUrl; } public static URL getHiveServer2SiteLocation() { return hiveServer2SiteUrl; } /** * @return the user name set in hadoop.job.ugi param or the current user from System * @throws IOException */ public String getUser() throws IOException { try { UserGroupInformation ugi = Utils.getUGI(); return ugi.getUserName(); } catch (LoginException le) { throw new IOException(le); } } public static String getColumnInternalName(int pos) { return "_col" + pos; } public static int getPositionFromInternalName(String internalName) { Pattern internalPattern = Pattern.compile("_col([0-9]+)"); Matcher m = internalPattern.matcher(internalName); if (!m.matches()){ return -1; } else { return Integer.parseInt(m.group(1)); } } /** * Append comma separated list of config vars to the restrict List * @param restrictListStr */ public void addToRestrictList(String restrictListStr) { if (restrictListStr == null) { return; } String oldList = this.getVar(ConfVars.HIVE_CONF_RESTRICTED_LIST); if (oldList == null || oldList.isEmpty()) { this.setVar(ConfVars.HIVE_CONF_RESTRICTED_LIST, restrictListStr); } else { this.setVar(ConfVars.HIVE_CONF_RESTRICTED_LIST, oldList + "," + restrictListStr); } setupRestrictList(); } /** * Set white list of parameters that are allowed to be modified * * @param paramNameRegex */ @LimitedPrivate(value = { "Currently only for use by HiveAuthorizer" }) public void setModifiableWhiteListRegex(String paramNameRegex) { if (paramNameRegex == null) { return; } modWhiteListPattern = Pattern.compile(paramNameRegex); } /** * Add the HIVE_CONF_RESTRICTED_LIST values to restrictList, * including HIVE_CONF_RESTRICTED_LIST itself */ private void setupRestrictList() { String restrictListStr = this.getVar(ConfVars.HIVE_CONF_RESTRICTED_LIST); restrictList.clear(); if (restrictListStr != null) { for (String entry : restrictListStr.split(",")) { restrictList.add(entry.trim()); } } String internalVariableListStr = this.getVar(ConfVars.HIVE_CONF_INTERNAL_VARIABLE_LIST); if (internalVariableListStr != null) { for (String entry : internalVariableListStr.split(",")) { restrictList.add(entry.trim()); } } restrictList.add(ConfVars.HIVE_IN_TEST.varname); restrictList.add(ConfVars.HIVE_CONF_RESTRICTED_LIST.varname); restrictList.add(ConfVars.HIVE_CONF_HIDDEN_LIST.varname); restrictList.add(ConfVars.HIVE_CONF_INTERNAL_VARIABLE_LIST.varname); restrictList.add(ConfVars.HIVE_SPARK_RSC_CONF_LIST.varname); } private void setupRSCList() { rscList.clear(); String vars = this.getVar(ConfVars.HIVE_SPARK_RSC_CONF_LIST); if (vars != null) { for (String var : vars.split(",")) { rscList.add(var.trim()); } } } /** * Strips hidden config entries from configuration */ public void stripHiddenConfigurations(Configuration conf) { HiveConfUtil.stripConfigurations(conf, hiddenSet); } /** * @return true if HS2 webui is enabled */ public boolean isWebUiEnabled() { return this.getIntVar(ConfVars.HIVE_SERVER2_WEBUI_PORT) != 0; } /** * @return true if HS2 webui query-info cache is enabled */ public boolean isWebUiQueryInfoCacheEnabled() { return isWebUiEnabled() && this.getIntVar(ConfVars.HIVE_SERVER2_WEBUI_MAX_HISTORIC_QUERIES) > 0; } /* Dynamic partition pruning is enabled in some or all cases */ public boolean isSparkDPPAny() { return isSparkDPPAny(this); } /* Dynamic partition pruning is enabled only for map join * hive.spark.dynamic.partition.pruning is false and * hive.spark.dynamic.partition.pruning.map.join.only is true */ public boolean isSparkDPPOnlyMapjoin() { return (!this.getBoolVar(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING) && this.getBoolVar(ConfVars.SPARK_DYNAMIC_PARTITION_PRUNING_MAP_JOIN_ONLY)); } public static boolean isLoadMetastoreConfig() { return loadMetastoreConfig; } public static void setLoadMetastoreConfig(boolean loadMetastoreConfig) { HiveConf.loadMetastoreConfig = loadMetastoreConfig; } public static boolean isLoadHiveServer2Config() { return loadHiveServer2Config; } public static void setLoadHiveServer2Config(boolean loadHiveServer2Config) { HiveConf.loadHiveServer2Config = loadHiveServer2Config; } public static class StrictChecks { private static final String NO_LIMIT_MSG = makeMessage( "Order by-s without limit", ConfVars.HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT); public static final String NO_PARTITIONLESS_MSG = makeMessage( "Queries against partitioned tables without a partition filter", ConfVars.HIVE_STRICT_CHECKS_NO_PARTITION_FILTER); private static final String NO_COMPARES_MSG = makeMessage( "Unsafe compares between different types", ConfVars.HIVE_STRICT_CHECKS_TYPE_SAFETY); private static final String NO_CARTESIAN_MSG = makeMessage( "Cartesian products", ConfVars.HIVE_STRICT_CHECKS_CARTESIAN); private static final String NO_BUCKETING_MSG = makeMessage( "Load into bucketed tables", ConfVars.HIVE_STRICT_CHECKS_BUCKETING); private static String makeMessage(String what, ConfVars setting) { return what + " are disabled for safety reasons. If you know what you are doing, please set " + setting.varname + " to false and make sure that " + ConfVars.HIVEMAPREDMODE.varname + " is not set to 'strict' to proceed. Note that you may get errors or incorrect " + "results if you make a mistake while using some of the unsafe features."; } public static String checkNoLimit(Configuration conf) { return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_ORDERBY_NO_LIMIT) ? null : NO_LIMIT_MSG; } public static String checkNoPartitionFilter(Configuration conf) { return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_NO_PARTITION_FILTER) ? null : NO_PARTITIONLESS_MSG; } public static String checkTypeSafety(Configuration conf) { return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_TYPE_SAFETY) ? null : NO_COMPARES_MSG; } public static String checkCartesian(Configuration conf) { return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_CARTESIAN) ? null : NO_CARTESIAN_MSG; } public static String checkBucketing(Configuration conf) { return isAllowed(conf, ConfVars.HIVE_STRICT_CHECKS_BUCKETING) ? null : NO_BUCKETING_MSG; } private static boolean isAllowed(Configuration conf, ConfVars setting) { String mode = HiveConf.getVar(conf, ConfVars.HIVEMAPREDMODE, (String)null); return (mode != null) ? !"strict".equals(mode) : !HiveConf.getBoolVar(conf, setting); } } public static String getNonMrEngines() { String result = StringUtils.EMPTY; for (String s : ConfVars.HIVE_EXECUTION_ENGINE.getValidStringValues()) { if ("mr".equals(s)) { continue; } if (!result.isEmpty()) { result += ", "; } result += s; } return result; } public static String generateMrDeprecationWarning() { return "Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. " + "Consider using a different execution engine (i.e. " + HiveConf.getNonMrEngines() + ") or using Hive 1.X releases."; } private static final Object reverseMapLock = new Object(); private static HashMap<String, ConfVars> reverseMap = null; public static HashMap<String, ConfVars> getOrCreateReverseMap() { // This should be called rarely enough; for now it's ok to just lock every time. synchronized (reverseMapLock) { if (reverseMap != null) { return reverseMap; } } HashMap<String, ConfVars> vars = new HashMap<>(); for (ConfVars val : ConfVars.values()) { vars.put(val.varname.toLowerCase(), val); if (val.altName != null && !val.altName.isEmpty()) { vars.put(val.altName.toLowerCase(), val); } } synchronized (reverseMapLock) { if (reverseMap != null) { return reverseMap; } reverseMap = vars; return reverseMap; } } public void verifyAndSetAll(Map<String, String> overlay) { for (Entry<String, String> entry : overlay.entrySet()) { verifyAndSet(entry.getKey(), entry.getValue()); } } public Map<String, String> subtree(String string) { Map<String, String> ret = new HashMap<>(); for (Entry<Object, Object> entry : getProps().entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key.startsWith(string)) { ret.put(key.substring(string.length() + 1), value); } } return ret; } }
[ "\"HIVE_CONF_DIR\"", "\"HIVE_HOME\"", "\"HADOOP_HOME\"", "\"HADOOP_PREFIX\"" ]
[]
[ "HADOOP_PREFIX", "HADOOP_HOME", "HIVE_CONF_DIR", "HIVE_HOME" ]
[]
["HADOOP_PREFIX", "HADOOP_HOME", "HIVE_CONF_DIR", "HIVE_HOME"]
java
4
0
internal/pipe/snapcraft/snapcraft_test.go
package snapcraft import ( "fmt" "io/ioutil" "os" "path/filepath" "testing" "github.com/goreleaser/goreleaser/internal/artifact" "github.com/goreleaser/goreleaser/internal/pipe" "github.com/goreleaser/goreleaser/pkg/config" "github.com/goreleaser/goreleaser/pkg/context" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" yaml "gopkg.in/yaml.v2" ) func TestDescription(t *testing.T) { assert.NotEmpty(t, Pipe{}.String()) } func TestRunPipeMissingInfo(t *testing.T) { for eerr, snap := range map[error]config.Snapcraft{ ErrNoSummary: { Description: "dummy desc", }, ErrNoDescription: { Summary: "dummy summary", }, pipe.Skip("no summary nor description were provided"): {}, } { t.Run(fmt.Sprintf("testing if %v happens", eerr), func(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Snapcrafts: []config.Snapcraft{ snap, }, }, } assert.Equal(t, eerr, Pipe{}.Run(ctx)) }) } } func TestRunPipe(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "mybin", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Summary: "test summary", Description: "test description", Publish: true, Builds: []string{"foo"}, }, { NameTemplate: "foo_and_bar_{{.Arch}}", Summary: "test summary", Description: "test description", Publish: true, Builds: []string{"foo", "bar"}, }, { NameTemplate: "bar_{{.Arch}}", Summary: "test summary", Description: "test description", Publish: true, Builds: []string{"bar"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", filepath.Join(dist, "foo"), "foo") addBinaries(t, ctx, "bar", filepath.Join(dist, "bar"), "bar") assert.NoError(t, Pipe{}.Run(ctx)) assert.Len(t, ctx.Artifacts.Filter(artifact.ByType(artifact.PublishableSnapcraft)).List(), 9) } func TestRunPipeInvalidNameTemplate(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "mybin", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}", Summary: "test summary", Description: "test description", Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "mybin") assert.EqualError(t, Pipe{}.Run(ctx), `template: tmpl:1: unexpected "}" in operand`) } func TestRunPipeWithName(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "testprojectname", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Name: "testsnapname", Base: "core18", License: "MIT", Summary: "test summary", Description: "test description", Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "mybin") assert.NoError(t, Pipe{}.Run(ctx)) yamlFile, err := ioutil.ReadFile(filepath.Join(dist, "foo_amd64", "prime", "meta", "snap.yaml")) assert.NoError(t, err) var metadata Metadata err = yaml.Unmarshal(yamlFile, &metadata) assert.NoError(t, err) assert.Equal(t, "testsnapname", metadata.Name) assert.Equal(t, "core18", metadata.Base) assert.Equal(t, "MIT", metadata.License) assert.Equal(t, "mybin", metadata.Apps["mybin"].Command) assert.Equal(t, "mybin", metadata.Apps["testsnapname"].Command) } func TestRunPipeWithBinaryInDir(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "testprojectname", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Name: "testsnapname", Summary: "test summary", Description: "test description", Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "bin/mybin") assert.NoError(t, Pipe{}.Run(ctx)) yamlFile, err := ioutil.ReadFile(filepath.Join(dist, "foo_amd64", "prime", "meta", "snap.yaml")) assert.NoError(t, err) var metadata Metadata err = yaml.Unmarshal(yamlFile, &metadata) assert.NoError(t, err) assert.Equal(t, "testsnapname", metadata.Name) assert.Equal(t, "", metadata.Base) assert.Equal(t, "", metadata.License) assert.Equal(t, "mybin", metadata.Apps["mybin"].Command) assert.Equal(t, "mybin", metadata.Apps["testsnapname"].Command) } func TestRunPipeMetadata(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "testprojectname", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Summary: "test summary", Description: "test description", Apps: map[string]config.SnapcraftAppMetadata{ "mybin": { Plugs: []string{"home", "network", "personal-files"}, Daemon: "simple", Args: "--foo --bar", }, }, Plugs: map[string]interface{}{ "personal-files": map[string]interface{}{ "read": []string{"$HOME/test"}, }, }, Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "mybin") assert.NoError(t, Pipe{}.Run(ctx)) yamlFile, err := ioutil.ReadFile(filepath.Join(dist, "foo_amd64", "prime", "meta", "snap.yaml")) assert.NoError(t, err) var metadata Metadata err = yaml.Unmarshal(yamlFile, &metadata) assert.NoError(t, err) assert.Equal(t, []string{"home", "network", "personal-files"}, metadata.Apps["mybin"].Plugs) assert.Equal(t, "simple", metadata.Apps["mybin"].Daemon) assert.Equal(t, "mybin --foo --bar", metadata.Apps["mybin"].Command) assert.Equal(t, []string{"home", "network", "personal-files"}, metadata.Apps["testprojectname"].Plugs) assert.Equal(t, "simple", metadata.Apps["testprojectname"].Daemon) assert.Equal(t, "mybin --foo --bar", metadata.Apps["testprojectname"].Command) assert.Equal(t, map[interface{}]interface{}(map[interface{}]interface{}{"read": []interface{}{"$HOME/test"}}), metadata.Plugs["personal-files"]) } func TestNoSnapcraftInPath(t *testing.T) { var path = os.Getenv("PATH") defer func() { assert.NoError(t, os.Setenv("PATH", path)) }() assert.NoError(t, os.Setenv("PATH", "")) var ctx = context.New(config.Project{ Snapcrafts: []config.Snapcraft{ { Summary: "dummy", Description: "dummy", }, }, }) assert.EqualError(t, Pipe{}.Run(ctx), ErrNoSnapcraft.Error()) } func TestRunNoArguments(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") assert.NoError(t, err) var dist = filepath.Join(folder, "dist") assert.NoError(t, os.Mkdir(dist, 0755)) assert.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "testprojectname", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Summary: "test summary", Description: "test description", Apps: map[string]config.SnapcraftAppMetadata{ "mybin": { Daemon: "simple", Args: "", }, }, Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "mybin") assert.NoError(t, Pipe{}.Run(ctx)) yamlFile, err := ioutil.ReadFile(filepath.Join(dist, "foo_amd64", "prime", "meta", "snap.yaml")) assert.NoError(t, err) var metadata Metadata err = yaml.Unmarshal(yamlFile, &metadata) assert.NoError(t, err) assert.Equal(t, "mybin", metadata.Apps["mybin"].Command) } func TestCompleter(t *testing.T) { folder, err := ioutil.TempDir("", "archivetest") require.NoError(t, err) var dist = filepath.Join(folder, "dist") require.NoError(t, os.Mkdir(dist, 0755)) require.NoError(t, err) var ctx = context.New(config.Project{ ProjectName: "testprojectname", Dist: dist, Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo_{{.Arch}}", Summary: "test summary", Description: "test description", Apps: map[string]config.SnapcraftAppMetadata{ "mybin": { Daemon: "simple", Args: "", Completer: "mybin-completer.bash", }, }, Builds: []string{"foo"}, }, }, }) ctx.Git.CurrentTag = "v1.2.3" ctx.Version = "v1.2.3" addBinaries(t, ctx, "foo", dist, "mybin") require.NoError(t, Pipe{}.Run(ctx)) yamlFile, err := ioutil.ReadFile(filepath.Join(dist, "foo_amd64", "prime", "meta", "snap.yaml")) require.NoError(t, err) var metadata Metadata err = yaml.Unmarshal(yamlFile, &metadata) require.NoError(t, err) assert.Equal(t, "mybin", metadata.Apps["mybin"].Command) assert.Equal(t, "mybin-completer.bash", metadata.Apps["mybin"].Completer) } func TestDefault(t *testing.T) { var ctx = context.New(config.Project{ Builds: []config.Build{ { ID: "foo", }, }, }) assert.NoError(t, Pipe{}.Default(ctx)) assert.Equal(t, defaultNameTemplate, ctx.Config.Snapcrafts[0].NameTemplate) assert.Equal(t, []string{"foo"}, ctx.Config.Snapcrafts[0].Builds) } func TestPublish(t *testing.T) { var ctx = context.New(config.Project{}) ctx.Artifacts.Add(artifact.Artifact{ Name: "mybin", Path: "nope.snap", Goarch: "amd64", Goos: "linux", Type: artifact.PublishableSnapcraft, }) err := Pipe{}.Publish(ctx) assert.Contains(t, err.Error(), "failed to push nope.snap package") } func TestDefaultSet(t *testing.T) { var ctx = context.New(config.Project{ Snapcrafts: []config.Snapcraft{ { NameTemplate: "foo", }, }, }) assert.NoError(t, Pipe{}.Default(ctx)) assert.Equal(t, "foo", ctx.Config.Snapcrafts[0].NameTemplate) } func TestDefaultDeprecate(t *testing.T) { var ctx = context.New(config.Project{ Snapcraft: config.Snapcraft{ NameTemplate: "foo", }, }) assert.NoError(t, Pipe{}.Default(ctx)) assert.Equal(t, "foo", ctx.Config.Snapcrafts[0].NameTemplate) } func addBinaries(t *testing.T, ctx *context.Context, name, dist, dest string) { for _, goos := range []string{"linux", "darwin"} { for _, goarch := range []string{"amd64", "386", "arm6"} { var folder = goos + goarch assert.NoError(t, os.MkdirAll(filepath.Join(dist, folder), 0755)) var binPath = filepath.Join(dist, folder, name) _, err := os.Create(binPath) assert.NoError(t, err) ctx.Artifacts.Add(artifact.Artifact{ Name: dest, Path: binPath, Goarch: goarch, Goos: goos, Type: artifact.Binary, Extra: map[string]interface{}{ "ID": name, }, }) } } } func TestSeveralSnapssWithTheSameID(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Snapcrafts: []config.Snapcraft{ { ID: "a", }, { ID: "a", }, }, }, } require.EqualError(t, Pipe{}.Default(ctx), "found 2 snapcrafts with the ID 'a', please fix your config") }
[ "\"PATH\"" ]
[]
[ "PATH" ]
[]
["PATH"]
go
1
0
wip/ray/archive/pytorch-huggingface.py
######################### # Import required modules ######################### import argparse import pprint import json import logging import os import sys import pandas as pd import random import time import glob import numpy as np from collections import defaultdict import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data import torch.utils.data.distributed from torch.utils.data import Dataset, DataLoader from transformers import RobertaModel, RobertaConfig from transformers import RobertaForSequenceClassification from transformers import AdamW, get_linear_schedule_with_warmup import ray from ray.train import Trainer ####################### # Parse input arguments ####################### def parse_args(): parser = argparse.ArgumentParser() # CLI args parser.add_argument('--train_batch_size', type=int, default=64) parser.add_argument('--train_steps_per_epoch', type=int, default=64) parser.add_argument('--validation_batch_size', type=int, default=64) parser.add_argument('--validation_steps_per_epoch', type=int, default=64) parser.add_argument('--epochs', type=int, default=1) parser.add_argument('--freeze_bert_layer', type=eval, default=False) parser.add_argument('--learning_rate', type=float, default=0.01) parser.add_argument('--momentum', type=float, default=0.5) parser.add_argument('--seed', type=int, default=42) parser.add_argument('--log_interval', type=int, default=100) parser.add_argument('--backend', type=str, default='gloo') parser.add_argument('--max_seq_length', type=int, default=128) parser.add_argument('--run_validation', type=eval, default=False) # Container environment # BEFORE RAY # parser.add_argument('--hosts', # type=list, # default='127.0.0.1') # BEFORE RAY # parser.add_argument('--current_host', # type=str, # default='127.0.0.1') parser.add_argument('--model_dir', type=str, default='./model/') parser.add_argument('--train_data', type=str, default='./data/train/') parser.add_argument('--validation_data', type=str, default='./data/validation/') parser.add_argument('--output_dir', type=str, default='./output') parser.add_argument('--num_gpus', type=int, default=0) # Debugger args # parser.add_argument("--save-frequency", # type=int, # default=10, # help="frequency with which to save steps") # parser.add_argument("--smdebug_path", # type=str, # help="output directory to save data in", # default="/opt/ml/output/tensors",) # parser.add_argument("--hook-type", # type=str, # choices=["saveall", "module-input-output", "weights-bias-gradients"], # default="saveall",) return parser.parse_args() ##################### # Tools and variables ##################### # Model name according to the PyTorch documentation: # https://github.com/aws/sagemaker-pytorch-inference-toolkit/blob/6936c08581e26ff3bac26824b1e4946ec68ffc85/src/sagemaker_pytorch_serving_container/torchserve.py#L45 MODEL_NAME = 'model.pth' # Hugging face list of models: https://huggingface.co/models PRE_TRAINED_MODEL_NAME = 'roberta-base' def create_list_input_files(path): print('************* path {}'.format(path)) input_files = glob.glob('{}/*.tsv'.format(path)) print(input_files) return input_files def save_transformer_model(model, model_dir): path = '{}/transformer'.format(model_dir) os.makedirs(path, exist_ok=True) print('Saving Transformer model to {}'.format(path)) model.save_pretrained(path) def save_pytorch_model(model, model_dir): os.makedirs(model_dir, exist_ok=True) print('Saving PyTorch model to {}'.format(model_dir)) save_path = os.path.join(model_dir, MODEL_NAME) torch.save(model.state_dict(), save_path) ##################### # Configure the model ##################### def configure_model(): classes = [-1, 0, 1] config = RobertaConfig.from_pretrained( PRE_TRAINED_MODEL_NAME, num_labels=len(classes), id2label={ ### BEGIN SOLUTION - DO NOT delete this comment for grading purposes 0: -1, # Replace all None 1: 0, # Replace all None 2: 1, # Replace all None ### END SOLUTION - DO NOT delete this comment for grading purposes }, label2id={ -1: 0, 0: 1, 1: 2, } ) config.output_attentions=True return config ################################ # PyTorch Dataset and DataLoader ################################ # PyTorch dataset retrieves the dataset’s features and labels one sample at a time # Create a custom Dataset class for the reviews class ReviewDataset(Dataset): def __init__(self, input_ids_list, label_id_list): self.input_ids_list = input_ids_list self.label_id_list = label_id_list def __len__(self): return len(self.input_ids_list) def __getitem__(self, item): # convert list of token_ids into an array of PyTorch LongTensors input_ids = json.loads(self.input_ids_list[item]) label_id = self.label_id_list[item] input_ids_tensor = torch.LongTensor(input_ids) label_id_tensor = torch.tensor(label_id, dtype=torch.long) return input_ids_tensor, label_id_tensor # PyTorch DataLoader helps to to organise the input training data in “minibatches” and reshuffle the data at every epoch # It takes Dataset as an input def create_data_loader(path, batch_size): print("Get data loader") df = pd.DataFrame(columns=['input_ids', 'label_id']) input_files = create_list_input_files(path) for file in input_files: df_temp = pd.read_csv(file, sep='\t', usecols=['input_ids', 'label_id']) df = df.append(df_temp) ds = ReviewDataset( input_ids_list=df.input_ids.to_numpy(), label_id_list=df.label_id.to_numpy(), ) return DataLoader( ds, batch_size=batch_size, shuffle=True, drop_last=True, ), df ############# # Train model ############# def train_model(config): # model, # train_data_loader, # df_train, # val_data_loader, # df_val, # args): model = config["model"] train_data_loader = config["train_data_loader"] df_train = config["df_train"] val_data_loader = config["val_data_loader"] df_val = config["df_val"] args = config["args"] loss_function = nn.CrossEntropyLoss() optimizer = optim.Adam(params=model.parameters(), lr=args.learning_rate) if args.freeze_bert_layer: print('Freezing BERT base layers...') for name, param in model.named_parameters(): if 'classifier' not in name: # classifier layer param.requires_grad = False print('Set classifier layers to `param.requires_grad=False`.') train_correct = 0 train_total = 0 for epoch in range(args.epochs): print('EPOCH -- {}'.format(epoch)) for i, (sent, label) in enumerate(train_data_loader): if i < args.train_steps_per_epoch: model.train() optimizer.zero_grad() sent = sent.squeeze(0) if torch.cuda.is_available(): sent = sent.cuda() label = label.cuda() output = model(sent)[0] _, predicted = torch.max(output, 1) loss = loss_function(output, label) loss.backward() optimizer.step() if args.run_validation and i % args.validation_steps_per_epoch == 0: print('RUNNING VALIDATION:') correct = 0 total = 0 model.eval() for sent, label in val_data_loader: sent = sent.squeeze(0) if torch.cuda.is_available(): sent = sent.cuda() label = label.cuda() output = model(sent)[0] _, predicted = torch.max(output.data, 1) total += label.size(0) correct += (predicted.cpu() ==label.cpu()).sum() accuracy = 100.00 * correct.numpy() / total print('[epoch/step: {0}/{1}] val_loss: {2:.2f} - val_acc: {3:.2f}%'.format(epoch, i, loss.item(), accuracy)) else: break print('TRAINING COMPLETED.') return model ###### # Main ###### if __name__ == '__main__': # Parse args args = parse_args() print('Loaded arguments:') print(args) # Get environment variables env_var = os.environ print('Environment variables:') pprint.pprint(dict(env_var), width = 1) # Check if distributed training #is_distributed = len(args.hosts) > 1 and args.backend is not None # is_distributed = True #print("Distributed training - {}".format(is_distributed)) use_cuda = args.num_gpus > 0 print("Number of gpus available - {}".format(args.num_gpus)) kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {} device = torch.device('cuda' if use_cuda else 'cpu') # Initialize the distributed environment. #if is_distributed: # BEFORE RAY world_size = len(args.hosts) #world_size = num_workers #os.environ['WORLD_SIZE'] = str(world_size) #host_rank = num_workers # BEFORE RAY host_rank = args.hosts.index(args.current_host) #os.environ['RANK'] = str(host_rank) #dist.init_process_group(backend=args.backend, rank=host_rank, world_size=world_size) #print('Initialized the distributed environment: \'{}\' backend on {} nodes. '.format( # args.backend, dist.get_world_size()) + 'Current host rank is {}. Number of gpus: {}'.format( # dist.get_rank(), args.num_gpus)) # Set the seed for generating random numbers torch.manual_seed(args.seed) if use_cuda: torch.cuda.manual_seed(args.seed) # Instantiate model config = None model = None successful_download = False retries = 0 while (retries < 5 and not successful_download): try: # Configure model config = configure_model() model = RobertaForSequenceClassification.from_pretrained( 'roberta-base', config=config ) model.to(device) successful_download = True print('Sucessfully downloaded after {} retries.'.format(retries)) except: retries = retries + 1 random_sleep = random.randint(1, 30) print('Retry #{}. Sleeping for {} seconds'.format(retries, random_sleep)) time.sleep(random_sleep) if not model: print('Not properly initialized...') # Create data loaders train_data_loader, df_train = create_data_loader(args.train_data, args.train_batch_size) val_data_loader, df_val = create_data_loader(args.validation_data, args.validation_batch_size) print("Processes {}/{} ({:.0f}%) of train data".format( len(train_data_loader.sampler), len(train_data_loader.dataset), 100. * len(train_data_loader.sampler) / len(train_data_loader.dataset) )) print("Processes {}/{} ({:.0f}%) of validation data".format( len(val_data_loader.sampler), len(val_data_loader.dataset), 100. * len(val_data_loader.sampler) / len(val_data_loader.dataset) )) print('model_dir: {}'.format(args.model_dir)) print('model summary: {}'.format(model)) callbacks = [] initial_epoch_number = 0 # Start training # model = train_model( # model, # train_data_loader, # df_train, # val_data_loader, # df_val, # args # ) ray.init(address="auto") trainer = Trainer("torch", num_workers=40, use_gpu=False) trainer.start() config = { "model": model, "train_data_loader": train_data_loader, "df_train": df_train, "val_data_loader": val_data_loader, "df_val": df_val, "args": args } model = trainer.run(train_model, config) save_transformer_model(model, args.model_dir) save_pytorch_model(model, args.model_dir) # Prepare for inference which will be used in deployment # You will need three files for it: inference.py, requirements.txt, config.json inference_path = os.path.join(args.model_dir, "code/") os.makedirs(inference_path, exist_ok=True) os.system("cp inference.py {}".format(inference_path)) os.system("cp requirements.txt {}".format(inference_path)) os.system("cp config.json {}".format(inference_path))
[]
[]
[ "RANK", "WORLD_SIZE" ]
[]
["RANK", "WORLD_SIZE"]
python
2
0
src/cmd/linuxkit/vendor/github.com/docker/cli/cli/flags/common.go
package flags import ( "fmt" "os" "path/filepath" cliconfig "github.com/docker/cli/cli/config" "github.com/docker/cli/opts" "github.com/docker/go-connections/tlsconfig" "github.com/sirupsen/logrus" "github.com/spf13/pflag" ) const ( // DefaultCaFile is the default filename for the CA pem file DefaultCaFile = "ca.pem" // DefaultKeyFile is the default filename for the key pem file DefaultKeyFile = "key.pem" // DefaultCertFile is the default filename for the cert pem file DefaultCertFile = "cert.pem" // FlagTLSVerify is the flag name for the TLS verification option FlagTLSVerify = "tlsverify" ) var ( dockerCertPath = os.Getenv("DOCKER_CERT_PATH") dockerTLSVerify = os.Getenv("DOCKER_TLS_VERIFY") != "" dockerTLS = os.Getenv("DOCKER_TLS") != "" ) // CommonOptions are options common to both the client and the daemon. type CommonOptions struct { Debug bool Hosts []string LogLevel string TLS bool TLSVerify bool TLSOptions *tlsconfig.Options } // NewCommonOptions returns a new CommonOptions func NewCommonOptions() *CommonOptions { return &CommonOptions{} } // InstallFlags adds flags for the common options on the FlagSet func (commonOpts *CommonOptions) InstallFlags(flags *pflag.FlagSet) { if dockerCertPath == "" { dockerCertPath = cliconfig.Dir() } flags.BoolVarP(&commonOpts.Debug, "debug", "D", false, "Enable debug mode") flags.StringVarP(&commonOpts.LogLevel, "log-level", "l", "info", `Set the logging level ("debug"|"info"|"warn"|"error"|"fatal")`) flags.BoolVar(&commonOpts.TLS, "tls", dockerTLS, "Use TLS; implied by --tlsverify") flags.BoolVar(&commonOpts.TLSVerify, FlagTLSVerify, dockerTLSVerify, "Use TLS and verify the remote") // TODO use flag flags.String("identity"}, "i", "", "Path to libtrust key file") commonOpts.TLSOptions = &tlsconfig.Options{ CAFile: filepath.Join(dockerCertPath, DefaultCaFile), CertFile: filepath.Join(dockerCertPath, DefaultCertFile), KeyFile: filepath.Join(dockerCertPath, DefaultKeyFile), } tlsOptions := commonOpts.TLSOptions flags.Var(opts.NewQuotedString(&tlsOptions.CAFile), "tlscacert", "Trust certs signed only by this CA") flags.Var(opts.NewQuotedString(&tlsOptions.CertFile), "tlscert", "Path to TLS certificate file") flags.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "tlskey", "Path to TLS key file") hostOpt := opts.NewNamedListOptsRef("hosts", &commonOpts.Hosts, opts.ValidateHost) flags.VarP(hostOpt, "host", "H", "Daemon socket(s) to connect to") } // SetDefaultOptions sets default values for options after flag parsing is // complete func (commonOpts *CommonOptions) SetDefaultOptions(flags *pflag.FlagSet) { // Regardless of whether the user sets it to true or false, if they // specify --tlsverify at all then we need to turn on TLS // TLSVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need // to check that here as well if flags.Changed(FlagTLSVerify) || commonOpts.TLSVerify { commonOpts.TLS = true } if !commonOpts.TLS { commonOpts.TLSOptions = nil } else { tlsOptions := commonOpts.TLSOptions tlsOptions.InsecureSkipVerify = !commonOpts.TLSVerify // Reset CertFile and KeyFile to empty string if the user did not specify // the respective flags and the respective default files were not found. if !flags.Changed("tlscert") { if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) { tlsOptions.CertFile = "" } } if !flags.Changed("tlskey") { if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) { tlsOptions.KeyFile = "" } } } } // SetLogLevel sets the logrus logging level func SetLogLevel(logLevel string) { if logLevel != "" { lvl, err := logrus.ParseLevel(logLevel) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", logLevel) os.Exit(1) } logrus.SetLevel(lvl) } else { logrus.SetLevel(logrus.InfoLevel) } }
[ "\"DOCKER_CERT_PATH\"", "\"DOCKER_TLS_VERIFY\"", "\"DOCKER_TLS\"" ]
[]
[ "DOCKER_CERT_PATH", "DOCKER_TLS_VERIFY", "DOCKER_TLS" ]
[]
["DOCKER_CERT_PATH", "DOCKER_TLS_VERIFY", "DOCKER_TLS"]
go
3
0
test/esme_op_test.go
// Copyright 2022 The sacloud/iaas-api-go Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package test import ( "os" "testing" "github.com/sacloud/iaas-api-go" "github.com/sacloud/iaas-api-go/testutil" "github.com/sacloud/iaas-api-go/types" ) func TestESMEOpCRUD(t *testing.T) { testutil.PreCheckEnvsFunc("SAKURACLOUD_ESME_DESTINATION")(t) destination := os.Getenv("SAKURACLOUD_ESME_DESTINATION") testutil.RunCRUD(t, &testutil.CRUDTestCase{ Parallel: true, SetupAPICallerFunc: singletonAPICaller, Create: &testutil.CRUDTestFunc{ Func: testESMECreate, CheckFunc: testutil.AssertEqualWithExpected(&testutil.CRUDTestExpect{ ExpectValue: createESMEExpected, IgnoreFields: ignoreESMEFields, }), }, Read: &testutil.CRUDTestFunc{ Func: testESMERead, CheckFunc: testutil.AssertEqualWithExpected(&testutil.CRUDTestExpect{ ExpectValue: createESMEExpected, IgnoreFields: ignoreESMEFields, }), }, Updates: []*testutil.CRUDTestFunc{ { Func: testESMEUpdate, CheckFunc: testutil.AssertEqualWithExpected(&testutil.CRUDTestExpect{ ExpectValue: updateESMEExpected, IgnoreFields: ignoreESMEFields, }), }, { Func: testESMEUpdateToMin, CheckFunc: testutil.AssertEqualWithExpected(&testutil.CRUDTestExpect{ ExpectValue: updateESMEToMinExpected, IgnoreFields: ignoreESMEFields, }), }, // send SMS { Func: func(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) _, err := client.SendMessageWithGeneratedOTP(ctx, ctx.ID, &iaas.ESMESendMessageWithGeneratedOTPRequest{ Destination: destination, Sender: "libsacloud-test", DomainName: "www.example.com", }) return nil, err }, }, { Func: func(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) logs, err := client.Logs(ctx, ctx.ID) if err != nil { return nil, err } return nil, testutil.DoAsserts( testutil.AssertLenFunc(t, logs, 1, "Logs"), ) }, }, { Func: func(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) _, err := client.SendMessageWithInputtedOTP(ctx, ctx.ID, &iaas.ESMESendMessageWithInputtedOTPRequest{ Destination: destination, Sender: "libsacloud-test", DomainName: "www.example.com", OTP: "397397", }) return nil, err }, }, { Func: func(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) logs, err := client.Logs(ctx, ctx.ID) if err != nil { return nil, err } return nil, testutil.DoAsserts( testutil.AssertLenFunc(t, logs, 2, "Logs"), ) }, }, }, Delete: &testutil.CRUDTestDeleteFunc{ Func: testESMEDelete, }, }) } var ( ignoreESMEFields = []string{ "ID", "Class", "Settings", "SettingsHash", "CreatedAt", "ModifiedAt", } createESMEParam = &iaas.ESMECreateRequest{ Name: testutil.ResourceName("esme"), Description: "desc", Tags: []string{"tag1", "tag2"}, } createESMEExpected = &iaas.ESME{ Name: createESMEParam.Name, Description: createESMEParam.Description, Tags: createESMEParam.Tags, Availability: types.Availabilities.Available, } updateESMEParam = &iaas.ESMEUpdateRequest{ Name: testutil.ResourceName("esme-upd"), Description: "desc-upd", Tags: []string{"tag1-upd", "tag2-upd"}, IconID: testIconID, } updateESMEExpected = &iaas.ESME{ Name: updateESMEParam.Name, Description: updateESMEParam.Description, Tags: updateESMEParam.Tags, Availability: types.Availabilities.Available, IconID: testIconID, } updateESMEToMinParam = &iaas.ESMEUpdateRequest{ Name: testutil.ResourceName("esme-to-min"), } updateESMEToMinExpected = &iaas.ESME{ Name: updateESMEToMinParam.Name, Availability: types.Availabilities.Available, } ) func testESMECreate(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) return client.Create(ctx, createESMEParam) } func testESMERead(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) return client.Read(ctx, ctx.ID) } func testESMEUpdate(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) return client.Update(ctx, ctx.ID, updateESMEParam) } func testESMEUpdateToMin(ctx *testutil.CRUDTestContext, caller iaas.APICaller) (interface{}, error) { client := iaas.NewESMEOp(caller) return client.Update(ctx, ctx.ID, updateESMEToMinParam) } func testESMEDelete(ctx *testutil.CRUDTestContext, caller iaas.APICaller) error { client := iaas.NewESMEOp(caller) return client.Delete(ctx, ctx.ID) }
[ "\"SAKURACLOUD_ESME_DESTINATION\"" ]
[]
[ "SAKURACLOUD_ESME_DESTINATION" ]
[]
["SAKURACLOUD_ESME_DESTINATION"]
go
1
0
hstore/hstore_test.go
package hstore import ( "database/sql" "os" "testing" _ "github.com/ownersroom/pq" ) type Fatalistic interface { Fatal(args ...interface{}) } func openTestConn(t Fatalistic) *sql.DB { datname := os.Getenv("PGDATABASE") sslmode := os.Getenv("PGSSLMODE") if datname == "" { os.Setenv("PGDATABASE", "pqgotest") } if sslmode == "" { os.Setenv("PGSSLMODE", "disable") } conn, err := sql.Open("postgres", "") if err != nil { t.Fatal(err) } return conn } func TestHstore(t *testing.T) { db := openTestConn(t) defer db.Close() // quitely create hstore if it doesn't exist _, err := db.Exec("CREATE EXTENSION IF NOT EXISTS hstore") if err != nil { t.Skipf("Skipping hstore tests - hstore extension create failed: %s", err.Error()) } hs := Hstore{} // test for null-valued hstores err = db.QueryRow("SELECT NULL::hstore").Scan(&hs) if err != nil { t.Fatal(err) } if hs.Map != nil { t.Fatalf("expected null map") } err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) if err != nil { t.Fatalf("re-query null map failed: %s", err.Error()) } if hs.Map != nil { t.Fatalf("expected null map") } // test for empty hstores err = db.QueryRow("SELECT ''::hstore").Scan(&hs) if err != nil { t.Fatal(err) } if hs.Map == nil { t.Fatalf("expected empty map, got null map") } if len(hs.Map) != 0 { t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) } err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) if err != nil { t.Fatalf("re-query empty map failed: %s", err.Error()) } if hs.Map == nil { t.Fatalf("expected empty map, got null map") } if len(hs.Map) != 0 { t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) } // a few example maps to test out hsOnePair := Hstore{ Map: map[string]sql.NullString{ "key1": {String: "value1", Valid: true}, }, } hsThreePairs := Hstore{ Map: map[string]sql.NullString{ "key1": {String: "value1", Valid: true}, "key2": {String: "value2", Valid: true}, "key3": {String: "value3", Valid: true}, }, } hsSmorgasbord := Hstore{ Map: map[string]sql.NullString{ "nullstring": {String: "NULL", Valid: true}, "actuallynull": {String: "", Valid: false}, "NULL": {String: "NULL string key", Valid: true}, "withbracket": {String: "value>42", Valid: true}, "withequal": {String: "value=42", Valid: true}, `"withquotes1"`: {String: `this "should" be fine`, Valid: true}, `"withquotes"2"`: {String: `this "should\" also be fine`, Valid: true}, "embedded1": {String: "value1=>x1", Valid: true}, "embedded2": {String: `"value2"=>x2`, Valid: true}, "withnewlines": {String: "\n\nvalue\t=>2", Valid: true}, "<<all sorts of crazy>>": {String: `this, "should,\" also, => be fine`, Valid: true}, }, } // test encoding in query params, then decoding during Scan testBidirectional := func(h Hstore) { err = db.QueryRow("SELECT $1::hstore", h).Scan(&hs) if err != nil { t.Fatalf("re-query %d-pair map failed: %s", len(h.Map), err.Error()) } if hs.Map == nil { t.Fatalf("expected %d-pair map, got null map", len(h.Map)) } if len(hs.Map) != len(h.Map) { t.Fatalf("expected %d-pair map, got len(map)=%d", len(h.Map), len(hs.Map)) } for key, val := range hs.Map { otherval, found := h.Map[key] if !found { t.Fatalf(" key '%v' not found in %d-pair map", key, len(h.Map)) } if otherval.Valid != val.Valid { t.Fatalf(" value %v <> %v in %d-pair map", otherval, val, len(h.Map)) } if otherval.String != val.String { t.Fatalf(" value '%v' <> '%v' in %d-pair map", otherval.String, val.String, len(h.Map)) } } } testBidirectional(hsOnePair) testBidirectional(hsThreePairs) testBidirectional(hsSmorgasbord) }
[ "\"PGDATABASE\"", "\"PGSSLMODE\"" ]
[]
[ "PGSSLMODE", "PGDATABASE" ]
[]
["PGSSLMODE", "PGDATABASE"]
go
2
0
model_evaluation/score_test_data.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Convenience script to score some data with CMLE models.""" import getpass import nltk import os import pandas as pd import random import tensorflow as tf import input_fn_example from utils_export.dataset import Dataset, Model from utils_export import utils_cloudml from utils_export import utils_tfrecords tf.app.flags.DEFINE_string( 'model_names', None, 'Comma separated list of model names deployed on ML Engine.') tf.app.flags.DEFINE_string( 'class_names', None, 'Comma separated list of class names to evaluate.') tf.app.flags.DEFINE_string('test_data', None, 'Test data to evaluate on. Must correspond to one in input_fn_example.py.') tf.app.flags.DEFINE_string('output_path', None, 'Path to write scored test data.') tf.app.flags.DEFINE_string('project_name', 'conversationai-models', 'Name of GCS project.') tf.app.flags.DEFINE_string('text_feature_name', 'tokens', 'Name of the text feature (see serving function call in run.py).') tf.app.flags.DEFINE_string('sentence_key', 'comment_key', 'Name of input key (see serving function call in run.py).') tf.app.flags.DEFINE_string('prediction_name', 'probabilities', 'Name of output prediction.') tf.app.flags.DEFINE_integer('dataset_size', 100000, 'Maximum size of dataset to score.') FLAGS = tf.app.flags.FLAGS def get_input_fn(test_data, tokenizer, model_input_comment_field): if test_data == 'biasbios': return input_fn_example.create_input_fn_biasbios(tokenizer, model_input_comment_field) elif test_data == 'scrubbed_biasbios': return input_fn_example.create_input_fn_biasbios(tokenizer, model_input_comment_field, scrubbed=True) else: raise ValueError('Dataset not currently supported.') def tokenizer(text, lowercase=True): """Converts text to a list of words. Args: text: piece of text to tokenize (string). lowercase: whether to include lowercasing in preprocessing (boolean). tokenizer: Python function to tokenize the text on. Returns: A list of strings (words). """ words = nltk.word_tokenize(text.decode('utf-8')) if lowercase: words = [w.lower() for w in words] return words def score_data(model_names, class_names, test_data, output_path, project_name, text_feature_name, sentence_key, prediction_name, dataset_size): """Scores a test dataset with ML engine models and writes output as csv. Args: model_names: list of model names deployed on ML Engine. class_names: list of class names to evaluate. test_data: test data to evaluate on, must be defined in get_input_fn. output_path: path to write scored test data. project_name: name of Google Cloud project. text_feature_name: name of the text feature (see serving function call in run.py). sentence_key: name of input key (see serving function call in run.py). prediction_name: name of output prediction. dataset_size: maximum size of dataset to score. """ os.environ['GCS_READ_CACHE_MAX_SIZE_MB'] = '0' #Faster to access GCS file + https://github.com/tensorflow/tensorflow/issues/15530 nltk.download('punkt') # Load data. input_fn = get_input_fn(test_data, tokenizer, model_input_comment_field=text_feature_name, ) performance_dataset_dir = os.path.join( 'gs://conversationai-models/', getpass.getuser(), 'tfrecords', 'performance_dataset_dir_3') dataset = Dataset(input_fn, performance_dataset_dir) random.seed(2018) # Need to set seed before loading data to be able to reload same data in the future # Define and call model. model_input_spec = { text_feature_name: utils_tfrecords.EncodingFeatureSpec.LIST_STRING} #library will use this automatically dataset.load_data(dataset_size, random_filter_keep_rate=0.5) model = Model( feature_keys_spec=model_input_spec, prediction_keys=prediction_name, example_key=sentence_key, model_names=model_names, project_name=project_name) dataset.add_model_prediction_to_data(model, recompute_predictions=True, class_names=class_names) # Save data. scored_test_df = dataset.show_data() scored_test_df.to_csv(tf.gfile.Open(output_path, 'w'), index = False) if __name__ == "__main__": tf.logging.set_verbosity(tf.logging.INFO) model_names = [name.strip() for name in FLAGS.model_names.split(',')] print(model_names) class_names = [name.strip() for name in FLAGS.class_names.split(',')] print(class_names) score_data(model_names, class_names, FLAGS.test_data, FLAGS.output_path, FLAGS.project_name, FLAGS.text_feature_name, FLAGS.sentence_key, FLAGS.prediction_name, FLAGS.dataset_size)
[]
[]
[ "GCS_READ_CACHE_MAX_SIZE_MB" ]
[]
["GCS_READ_CACHE_MAX_SIZE_MB"]
python
1
0
secrets/hashivault/vault.go
// Copyright 2019 The Go Cloud Development Kit Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limtations under the License. // Package hashivault provides a secrets implementation using the Transit // Secrets Engine of Vault by Hashicorp. // Use OpenKeeper to construct a *secrets.Keeper. // // URLs // // For secrets.OpenKeeper, hashivault registers for the scheme "hashivault". // The default URL opener will dial a Vault server using the environment // variables "VAULT_SERVER_URL" and "VAULT_SERVER_TOKEN". // To customize the URL opener, or for more details on the URL format, // see URLOpener. // See https://gocloud.dev/concepts/urls/ for background information. // // As // // hashivault does not support any types for As. package hashivault import ( "context" "encoding/base64" "errors" "fmt" "net/url" "os" "path" "sync" "github.com/hashicorp/vault/api" "gocloud.dev/gcerrors" "gocloud.dev/secrets" ) // Config is the authentication configurations of the Vault server. type Config struct { // Token is the access token the Vault client uses to talk to the server. // See https://www.vaultproject.io/docs/concepts/tokens.html for more // information. Token string // APIConfig is used to configure the creation of the client. APIConfig api.Config } // Dial gets a Vault client. func Dial(ctx context.Context, cfg *Config) (*api.Client, error) { if cfg == nil { return nil, errors.New("no auth Config provided") } c, err := api.NewClient(&cfg.APIConfig) if err != nil { return nil, err } if cfg.Token != "" { c.SetToken(cfg.Token) } return c, nil } func init() { secrets.DefaultURLMux().RegisterKeeper(Scheme, new(defaultDialer)) } // defaultDialer dials a default Vault server based on the environment variables // VAULT_SERVER_URL and VAULT_SERVER_TOKEN. type defaultDialer struct { init sync.Once opener *URLOpener err error } func (o *defaultDialer) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { o.init.Do(func() { serverURL := os.Getenv("VAULT_SERVER_URL") if serverURL == "" { o.err = errors.New("VAULT_SERVER_URL environment variable is not set") return } token := os.Getenv("VAULT_SERVER_TOKEN") // token is not required cfg := Config{Token: token, APIConfig: api.Config{Address: serverURL}} client, err := Dial(ctx, &cfg) if err != nil { o.err = fmt.Errorf("failed to Dial default Vault server at %q: %v", serverURL, err) return } o.opener = &URLOpener{Client: client} }) if o.err != nil { return nil, fmt.Errorf("open keeper %v: %v", u, o.err) } return o.opener.OpenKeeperURL(ctx, u) } // Scheme is the URL scheme hashivault registers its URLOpener under on secrets.DefaultMux. const Scheme = "hashivault" // URLOpener opens Vault URLs like "hashivault://mykey". // // The URL Host + Path are used as the keyID. // // No query parameters are supported. type URLOpener struct { // Client must be non-nil. Client *api.Client // Options specifies the options to pass to OpenKeeper. Options KeeperOptions } // OpenKeeperURL opens the Keeper URL. func (o *URLOpener) OpenKeeperURL(ctx context.Context, u *url.URL) (*secrets.Keeper, error) { for param := range u.Query() { return nil, fmt.Errorf("open keeper %v: invalid query parameter %q", u, param) } return OpenKeeper(o.Client, path.Join(u.Host, u.Path), &o.Options), nil } // OpenKeeper returns a *secrets.Keeper that uses the Transit Secrets Engine of // Vault by Hashicorp. // See the package documentation for an example. func OpenKeeper(client *api.Client, keyID string, opts *KeeperOptions) *secrets.Keeper { return secrets.NewKeeper(&keeper{ keyID: keyID, client: client, }) } type keeper struct { // keyID is an encryption key ring name used by the Vault's transit API. keyID string client *api.Client } // Decrypt decrypts the ciphertext into a plaintext. func (k *keeper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { out, err := k.client.Logical().Write( path.Join("transit/decrypt", k.keyID), map[string]interface{}{ "ciphertext": string(ciphertext), }, ) if err != nil { return nil, err } return base64.StdEncoding.DecodeString(out.Data["plaintext"].(string)) } // Encrypt encrypts a plaintext into a ciphertext. func (k *keeper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { secret, err := k.client.Logical().Write( path.Join("transit/encrypt", k.keyID), map[string]interface{}{ "plaintext": plaintext, }, ) if err != nil { return nil, err } return []byte(secret.Data["ciphertext"].(string)), nil } // Close implements driver.Keeper.Close. func (k *keeper) Close() error { return nil } // ErrorAs implements driver.Keeper.ErrorAs. func (k *keeper) ErrorAs(err error, i interface{}) bool { return false } // ErrorCode implements driver.ErrorCode. func (k *keeper) ErrorCode(error) gcerrors.ErrorCode { // TODO(shantuo): try to classify vault error codes return gcerrors.Unknown } // KeeperOptions controls Keeper behaviors. // It is provided for future extensibility. type KeeperOptions struct{}
[ "\"VAULT_SERVER_URL\"", "\"VAULT_SERVER_TOKEN\"" ]
[]
[ "VAULT_SERVER_URL", "VAULT_SERVER_TOKEN" ]
[]
["VAULT_SERVER_URL", "VAULT_SERVER_TOKEN"]
go
2
0
internal/controlplane/xdsmgr/xdsmgr.go
// Package xdsmgr implements a resource discovery manager for envoy. package xdsmgr import ( "context" "encoding/json" "errors" "os" "sync" envoy_service_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" "github.com/google/uuid" lru "github.com/hashicorp/golang-lru" "golang.org/x/sync/errgroup" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/timestamppb" "github.com/pomerium/pomerium/internal/contextkeys" "github.com/pomerium/pomerium/internal/log" "github.com/pomerium/pomerium/internal/signal" "github.com/pomerium/pomerium/pkg/grpc/events" ) const ( maxNonceCacheSize = 1 << 12 ) type streamState struct { typeURL string clientResourceVersions map[string]string unsubscribedResources map[string]struct{} } var onHandleDeltaRequest = func(state *streamState) {} // A Manager manages xDS resources. type Manager struct { signal *signal.Signal eventHandler func(*events.EnvoyConfigurationEvent) mu sync.Mutex nonce string resources map[string][]*envoy_service_discovery_v3.Resource nonceToConfig *lru.Cache hostname string } // NewManager creates a new Manager. func NewManager(resources map[string][]*envoy_service_discovery_v3.Resource, eventHandler func(*events.EnvoyConfigurationEvent)) *Manager { nonceToConfig, _ := lru.New(maxNonceCacheSize) // the only error they return is when size is negative, which never happens return &Manager{ signal: signal.New(), eventHandler: eventHandler, nonceToConfig: nonceToConfig, nonce: uuid.NewString(), resources: resources, hostname: getHostname(), } } // DeltaAggregatedResources implements the increment xDS server. func (mgr *Manager) DeltaAggregatedResources( stream envoy_service_discovery_v3.AggregatedDiscoveryService_DeltaAggregatedResourcesServer, ) error { ch := mgr.signal.Bind() defer mgr.signal.Unbind(ch) stateByTypeURL := map[string]*streamState{} getDeltaResponse := func(ctx context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse { mgr.mu.Lock() defer mgr.mu.Unlock() state, ok := stateByTypeURL[typeURL] if !ok { return nil } res := &envoy_service_discovery_v3.DeltaDiscoveryResponse{ TypeUrl: typeURL, Nonce: mgr.nonce, } seen := map[string]struct{}{} for _, resource := range mgr.resources[typeURL] { seen[resource.Name] = struct{}{} if resource.Version != state.clientResourceVersions[resource.Name] { res.Resources = append(res.Resources, resource) } } for name := range state.clientResourceVersions { _, ok := seen[name] if !ok { res.RemovedResources = append(res.RemovedResources, name) } } if len(res.Resources) == 0 && len(res.RemovedResources) == 0 { return nil } return res } handleDeltaRequest := func(ctx context.Context, req *envoy_service_discovery_v3.DeltaDiscoveryRequest) { mgr.mu.Lock() defer mgr.mu.Unlock() state, ok := stateByTypeURL[req.GetTypeUrl()] if !ok { // first time we've seen a message for this type URL. state = &streamState{ typeURL: req.GetTypeUrl(), clientResourceVersions: req.GetInitialResourceVersions(), unsubscribedResources: make(map[string]struct{}), } if state.clientResourceVersions == nil { state.clientResourceVersions = make(map[string]string) } stateByTypeURL[req.GetTypeUrl()] = state } switch { case req.GetResponseNonce() == "": // neither an ACK or a NACK case req.GetErrorDetail() != nil: // a NACK // - set the client resource versions to the current resource versions state.clientResourceVersions = make(map[string]string) for _, resource := range mgr.resources[req.GetTypeUrl()] { state.clientResourceVersions[resource.Name] = resource.Version } mgr.nackEvent(ctx, req) case req.GetResponseNonce() == mgr.nonce: // an ACK for the last response // - set the client resource versions to the current resource versions state.clientResourceVersions = make(map[string]string) for _, resource := range mgr.resources[req.GetTypeUrl()] { state.clientResourceVersions[resource.Name] = resource.Version } mgr.ackEvent(ctx, req) default: // an ACK for a response that's not the last response mgr.ackEvent(ctx, req) } // update subscriptions for _, name := range req.GetResourceNamesSubscribe() { delete(state.unsubscribedResources, name) } for _, name := range req.GetResourceNamesUnsubscribe() { state.unsubscribedResources[name] = struct{}{} // from the docs: // NOTE: the server must respond with all resources listed in // resource_names_subscribe, even if it believes the client has // the most recent version of them. The reason: the client may // have dropped them, but then regained interest before it had // a chance to send the unsubscribe message. // so we reset the version to treat it like a new version delete(state.clientResourceVersions, name) } onHandleDeltaRequest(state) } incoming := make(chan *envoy_service_discovery_v3.DeltaDiscoveryRequest) outgoing := make(chan *envoy_service_discovery_v3.DeltaDiscoveryResponse) eg, ctx := errgroup.WithContext(stream.Context()) // 1. receive all incoming messages eg.Go(func() error { for { req, err := stream.Recv() if err != nil { return err } select { case <-ctx.Done(): return ctx.Err() case incoming <- req: } } }) // 2. handle incoming requests or resource changes eg.Go(func() error { changeCtx := ctx for { var typeURLs []string select { case <-ctx.Done(): return ctx.Err() case req := <-incoming: handleDeltaRequest(changeCtx, req) typeURLs = []string{req.GetTypeUrl()} case changeCtx = <-ch: mgr.mu.Lock() for typeURL := range mgr.resources { typeURLs = append(typeURLs, typeURL) } mgr.mu.Unlock() } for _, typeURL := range typeURLs { res := getDeltaResponse(changeCtx, typeURL) if res == nil { continue } select { case <-ctx.Done(): return ctx.Err() case outgoing <- res: mgr.changeEvent(ctx, res) } } } }) // 3. send all outgoing messages eg.Go(func() error { for { select { case <-ctx.Done(): return ctx.Err() case res := <-outgoing: err := stream.Send(res) if err != nil { return err } } } }) return eg.Wait() } // StreamAggregatedResources is not implemented. func (mgr *Manager) StreamAggregatedResources( stream envoy_service_discovery_v3.AggregatedDiscoveryService_StreamAggregatedResourcesServer, ) error { return status.Errorf(codes.Unimplemented, "method StreamAggregatedResources not implemented") } // Update updates the state of resources. If any changes are made they will be pushed to any listening // streams. For each TypeURL the list of resources should be the complete list of resources. func (mgr *Manager) Update(ctx context.Context, resources map[string][]*envoy_service_discovery_v3.Resource) { nonce := uuid.New().String() mgr.mu.Lock() mgr.nonce = nonce mgr.resources = resources mgr.nonceToConfig.Add(nonce, ctx.Value(contextkeys.UpdateRecordsVersion)) mgr.mu.Unlock() mgr.signal.Broadcast(ctx) } func (mgr *Manager) nonceToConfigVersion(nonce string) (ver uint64) { val, ok := mgr.nonceToConfig.Get(nonce) if !ok { return 0 } ver, _ = val.(uint64) return ver } func (mgr *Manager) nackEvent(ctx context.Context, req *envoy_service_discovery_v3.DeltaDiscoveryRequest) { mgr.eventHandler(&events.EnvoyConfigurationEvent{ Instance: mgr.hostname, Kind: events.EnvoyConfigurationEvent_EVENT_DISCOVERY_REQUEST_NACK, Time: timestamppb.Now(), Message: req.ErrorDetail.Message, Code: req.ErrorDetail.Code, Details: req.ErrorDetail.Details, ResourceSubscribed: req.ResourceNamesSubscribe, ResourceUnsubscribed: req.ResourceNamesUnsubscribe, ConfigVersion: mgr.nonceToConfigVersion(req.ResponseNonce), TypeUrl: req.TypeUrl, Nonce: req.ResponseNonce, }) bs, _ := json.Marshal(req.ErrorDetail.Details) log.Fatal(). Err(errors.New(req.ErrorDetail.Message)). Str("resource_type", req.TypeUrl). Strs("resources_unsubscribe", req.ResourceNamesUnsubscribe). Strs("resources_subscribe", req.ResourceNamesSubscribe). Uint64("nonce_version", mgr.nonceToConfigVersion(req.ResponseNonce)). Int32("code", req.ErrorDetail.Code). RawJSON("details", bs).Msg("error applying configuration") } func (mgr *Manager) ackEvent(ctx context.Context, req *envoy_service_discovery_v3.DeltaDiscoveryRequest) { mgr.eventHandler(&events.EnvoyConfigurationEvent{ Instance: mgr.hostname, Kind: events.EnvoyConfigurationEvent_EVENT_DISCOVERY_REQUEST_ACK, Time: timestamppb.Now(), ConfigVersion: mgr.nonceToConfigVersion(req.ResponseNonce), ResourceSubscribed: req.ResourceNamesSubscribe, ResourceUnsubscribed: req.ResourceNamesUnsubscribe, TypeUrl: req.TypeUrl, Nonce: req.ResponseNonce, Message: "ok", }) log.Debug(ctx). Str("resource_type", req.TypeUrl). Strs("resources_unsubscribe", req.ResourceNamesUnsubscribe). Strs("resources_subscribe", req.ResourceNamesSubscribe). Uint64("nonce_version", mgr.nonceToConfigVersion(req.ResponseNonce)). Msg("ACK") } func (mgr *Manager) changeEvent(ctx context.Context, res *envoy_service_discovery_v3.DeltaDiscoveryResponse) { mgr.eventHandler(&events.EnvoyConfigurationEvent{ Instance: mgr.hostname, Kind: events.EnvoyConfigurationEvent_EVENT_DISCOVERY_RESPONSE, Time: timestamppb.Now(), Nonce: res.Nonce, Message: "change", ConfigVersion: mgr.nonceToConfigVersion(res.Nonce), TypeUrl: res.TypeUrl, ResourceSubscribed: resourceNames(res.Resources), ResourceUnsubscribed: res.RemovedResources, }) log.Debug(ctx). Uint64("ctx_config_version", mgr.nonceToConfigVersion(res.Nonce)). Str("nonce", res.Nonce). Str("type", res.TypeUrl). Strs("subscribe", resourceNames(res.Resources)). Strs("removed", res.RemovedResources). Msg("sent update") } func resourceNames(res []*envoy_service_discovery_v3.Resource) []string { txt := make([]string, 0, len(res)) for _, r := range res { txt = append(txt, r.Name) } return txt } func getHostname() string { hostname, err := os.Hostname() if err != nil { hostname = os.Getenv("HOSTNAME") } if hostname == "" { hostname = "__unknown__" } return hostname }
[ "\"HOSTNAME\"" ]
[]
[ "HOSTNAME" ]
[]
["HOSTNAME"]
go
1
0
config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' FLASK_ADMIN = os.environ.get('FLASK_ADMIN') SQLALCHEMY_TRACK_MODIFICATIONS = False FLASKY_POSTS_PER_PAGE = 5 FLASKY_COMMENTS_PER_PAGE = 5 FLASKY_FOLLOWERS_PER_PAGE = 10 MAX_CONTENT_LENGTH = 16 * 1024 * 1024 UPLOAD_FOLDER = basedir + '/app/static/' @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite://' class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, 'default': DevelopmentConfig }
[]
[]
[ "FLASK_ADMIN", "DEV_DATABASE_URL", "DATABASE_URL", "SECRET_KEY", "TEST_DATABASE_URL" ]
[]
["FLASK_ADMIN", "DEV_DATABASE_URL", "DATABASE_URL", "SECRET_KEY", "TEST_DATABASE_URL"]
python
5
0
python/build.py
# coding=utf-8 """ Build tasks """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import json import os import subprocess import sys from pynt import task from pyntcontrib import execute, safe_cd from semantic_version import Version PROJECT_NAME = "simple_calls" SRC = '.' # for multitargeting PYTHON = "python" IS_DJANGO = False IS_TRAVIS = 'TRAVIS' in os.environ if IS_TRAVIS: PIPENV = "" else: PIPENV = "pipenv run" GEM_FURY = "" CURRENT_HASH = None MAC_LIBS = "" # ":" # TODO this breaks on windows sys.path.append(os.path.join(os.path.dirname(__file__), '.')) from build_utils import check_is_aws, skip_if_no_change, execute_with_environment, get_versions, execute_get_text, run_gitleaks @task() @skip_if_no_change("git_leaks") def git_leaks(): run_gitleaks() @task() @skip_if_no_change("git_secrets") def git_secrets(): """ Install git secrets if possible. """ print("turning off because I'm on windows ...") return if check_is_aws(): # no easy way to install git secrets on ubuntu. return if IS_TRAVIS: # nothing is edited on travis return try: commands = ["git secrets --install", "git secrets --register-aws"] for command in commands: cp = subprocess.run(command.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, check=True) for stream in [cp.stdout, cp.stderr]: if stream: for line in stream.decode().split("\n"): print("*" + line) except subprocess.CalledProcessError as cpe: print(cpe) installed = False for stream in [cpe.stdout, cpe.stderr]: if stream: for line in stream.decode().split("\n"): print("-" + line) if "commit-msg already exists" in line: print("git secrets installed.") installed = True break if not installed: raise execute(*("git secrets --scan".strip().split(" "))) @task() def clean(): """ Delete all outputs. Blank until I think of a better way to do this. """ return @task() @skip_if_no_change("formatting") def formatting(): with safe_cd(SRC): if sys.version_info < (3, 6): print("Black doesn't work on python 2") return command = "{0} black {1}".format(PIPENV, PROJECT_NAME).strip() print(command) result = execute_get_text(command) assert result changed =[] for line in result.split("\n"): if "reformatted " in line: file = line[len("reformatted "):].strip() changed.append(file) for change in changed: command ="git add {0}".format(change) print(command) execute(*(command.split(" "))) @task() @skip_if_no_change("compile_py") def compile_py(): """ Catch on the worst syntax errors """ with safe_cd(SRC): execute(PYTHON, "-m", "compileall", PROJECT_NAME) @task(formatting, compile_py) @skip_if_no_change("prospector") def prospector(): """ Catch a few things with a non-strict propector run """ with safe_cd(SRC): command = "{0} prospector {1} --profile {1}_style --pylint-config-file=pylintrc.ini --profile-path=.prospector".format( PIPENV, PROJECT_NAME).strip().replace(" ", " ") print(command) execute(*(command .split(" "))) @task() @skip_if_no_change("detect_secrets") def detect_secrets(): """ Call detect-secrets tool """ # use # blah blah = "foo" # pragma: whitelist secret # to ignore a false posites errors_file = "detect-secrets-results.txt" # TODO: not windows compat # print(execute_get_text("pwd")) command = "{0} detect-secrets --scan --base64-limit 4 --exclude .idea|.js|.min.js|.html|.xsd|" \ "lock.json|synced_folders|.scss|Pipfile.lock|" \ "lint.txt|{1}".format(PIPENV, errors_file).strip() print(command) bash_process = subprocess.Popen(command.split(" "), #shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) foo = bash_process.wait() out, err = bash_process.communicate() # wait with open(errors_file, "w+") as file_handle: if len(out)==0: print("Warning- no output from detect secrets. Happens with git hook, but not from ordinary command line.") return file_handle.write(out.decode()) with open(errors_file) as f: try: data = json.load(f) except Exception: print("Can't read json") exit(-1) return if data["results"]: for result in data["results"]: print(result) print("detect-secrets has discovered high entropy strings, possibly passwords?") exit(-1) @task(compile_py, formatting, prospector) @skip_if_no_change("lint") def lint(): """ Lint """ with safe_cd(SRC): if os.path.isfile("lint.txt"): # TODO: detect OS try: execute("rm", "lint.txt") except: # execute("DEL", "lint.txt") # fails... why? os.remove("lint.txt") with safe_cd(SRC): if IS_DJANGO: django_bits = "--load-plugins pylint_django " else: django_bits = "" # command += "{0}--rcfile=pylintrc.ini {1}".format(django_bits, PROJECT_NAME).split(" ") command = "{0} pylint {1} --rcfile=pylintrc.ini {2}".format(PIPENV, django_bits, PROJECT_NAME) \ .strip() \ .replace(" ", " ") print(command) command = command.split(" ") # keep out of src tree, causes extraneous change detections lint_output_file_name = "lint.txt" with open(lint_output_file_name, "w") as outfile: env = config_pythonpath() subprocess.call(command, stdout=outfile, env=env) fatal_errors = sum(1 for line in open(lint_output_file_name) if "no-member" in line or \ "no-name-in-module" in line or \ "import-error" in line) if fatal_errors > 0: for line in open(lint_output_file_name): if "no-member" in line or \ "no-name-in-module" in line or \ "import-error" in line: print(line) print("Fatal lint errors : {0}".format(fatal_errors)) exit(-1) cutoff = 100 num_lines = sum(1 for line in open(lint_output_file_name) if "*************" not in line and "---------------------" not in line and "Your code has been rated at" not in line) if num_lines > cutoff: raise TypeError("Too many lines of lint : {0}, max {1}".format(num_lines, cutoff)) @task(lint) @skip_if_no_change("nose_tests") def nose_tests(): """ Nose tests """ # with safe_cd(SRC): if IS_DJANGO: command = "{0} manage.py test -v 2".format(PYTHON) # We'd expect this to be MAC or a build server. my_env = config_pythonpath() execute_with_environment(command, env=my_env) else: my_env = config_pythonpath() if IS_TRAVIS: command = "{0} -m nose {1}".format(PYTHON, "test").strip() else: command = "{0} {1} -m nose {2}".format(PIPENV, PYTHON, "simple_calls").strip() print(command) execute_with_environment(command, env=my_env) def config_pythonpath(): """ Add to PYTHONPATH """ if check_is_aws(): env = "DEV" else: env = "MAC" my_env = {'ENV': env} for key, value in os.environ.items(): my_env[key] = value my_env["PYTHONPATH"] = my_env.get("PYTHONPATH", "") + MAC_LIBS print(my_env["PYTHONPATH"]) return my_env @task() def coverage(): """ Coverage, which is a bit redundant with nose test """ print("coverage broken on windows... don't know why yet") return # will get back to this.. print("Coverage tests always re-run") with safe_cd(SRC): my_env = config_pythonpath() command = "{0} py.test {1} --cov={2} --cov-report html:coverage --cov-fail-under 1 --verbose".format( PIPENV, "simple_calls", PROJECT_NAME) print(command) execute_with_environment(command, my_env) @task() @skip_if_no_change("docs") def docs(): """ Docs """ with safe_cd(SRC): with safe_cd("docs"): my_env = config_pythonpath() command = "{0} make html".format(PIPENV).strip() print(command) execute_with_environment(command, env=my_env) @task() def pip_check(): """ Are packages ok? """ execute("pip", "check") if PIPENV and not IS_TRAVIS: execute("pipenv", "check") execute("safety", "check", "-r", "requirements_dev.txt") @task() def compile_mark_down(): """ Convert MD to RST """ print("Not compiling README.md because moderately complex MD makes pypi rst parser puke.") # with safe_cd(SRC): # if IS_TRAVIS: # command = "pandoc --from=markdown --to=rst --output=README.rst README.md".strip().split( # " ") # else: # command = "{0} pandoc --from=markdown --to=rst --output=README.rst README.md".format(PIPENV).strip().split( # " ") # execute(*(command)) @task() @skip_if_no_change("mypy") def mypy(): """ Are types ok? """ if sys.version_info < (3, 4): print("Mypy doesn't work on python < 3.4") return if IS_TRAVIS: command = "{0} -m mypy {1} --ignore-missing-imports --strict".format(PYTHON, PROJECT_NAME).strip() else: command = "{0} mypy {1} --ignore-missing-imports --strict".format(PIPENV, PROJECT_NAME).strip() bash_process = subprocess.Popen(command.split(" "), # shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = bash_process.communicate() # wait mypy_file = "mypy_errors.txt" with open(mypy_file, "w+") as lint_file: lines = out.decode().split("\n") for line in lines: if "build_utils.py" in line: continue if "test.py" in line: continue if "tests.py" in line: continue if "/test_" in line: continue if "/tests_" in line: continue else: lint_file.writelines([line + "\n"]) num_lines = sum(1 for line in open(mypy_file) if line and line.strip(" \n")) max_lines = 25 if num_lines > max_lines: raise TypeError("Too many lines of mypy : {0}, max {1}".format(num_lines, max_lines)) @task() def pin_dependencies(): """ Create requirement*.txt """ with safe_cd(SRC): execute(*("{0} pipenv_to_requirements".format(PIPENV).strip().split(" "))) @task() def jiggle_version(): command = "{0} jiggle_version --project={1} --source={2}".format(PIPENV, PROJECT_NAME, "").strip() execute(*(command.split(" "))) @task() def check_setup_py(): # if # ValueError: ZIP does not support timestamps before 1980 # then run this to ID # find . -mtime +13700 -ls with safe_cd(SRC): if IS_TRAVIS: execute(PYTHON, *("setup.py check -r -s".split(" "))) else: execute(*("{0} {1} setup.py check -r -s".format(PIPENV, PYTHON).strip().split(" "))) @task() @skip_if_no_change("vulture", expect_files="dead_code.txt") def dead_code(): """ This also finds code you are working on today! """ with safe_cd(SRC): if IS_TRAVIS: command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split() else: command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split() output_file_name = "dead_code.txt" with open(output_file_name, "w") as outfile: env = config_pythonpath() subprocess.call(command, stdout=outfile, env=env) cutoff = 20 num_lines = sum(1 for line in open(output_file_name) if line) if num_lines > cutoff: print("Too many lines of dead code : {0}, max {1}".format(num_lines, cutoff)) exit(-1) @task(formatting, mypy, detect_secrets, git_secrets,dead_code, nose_tests, coverage, compile_py, lint, compile_mark_down, check_setup_py, pin_dependencies, jiggle_version) # docs ... later @skip_if_no_change("package") def package(): """ package, but don't upload """ with safe_cd(SRC): for folder in ["build", "dist", PROJECT_NAME + ".egg-info"]: # execute("rm", "-rf", folder) if os.path.exists(folder): os.rmdir(folder) with safe_cd(SRC): execute(PYTHON, "setup.py", "sdist", "--formats=gztar,zip") @task(package) def gemfury(): """ Push to gem fury, a repo with private options """ # fury login # fury push dist/*.gz --as=YOUR_ACCT # fury push dist/*.whl --as=YOUR_ACCT cp = subprocess.run(("fury login --as={0}".format(GEM_FURY).split(" ")), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, check=True) print(cp.stdout) about = {} with open(os.path.join(SRC, PROJECT_NAME, "__version__.py")) as f: exec(f.read(), about) version = Version(about["__version__"]) print("Have version : " + str(version)) print("Preparing to upload") if version not in get_versions(): for kind in ["gz", "whl"]: try: files = glob.glob("{0}dist/*.{1}".format(SRC.replace(".", ""), kind)) for file_name in files: cp = subprocess.run(("fury push {0} --as={1}".format(file_name, GEM_FURY).split(" ")), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, check=True) print("result of fury push") for stream in [cp.stdout, cp.stderr]: if stream: for line in stream.decode().split("\n"): print(line) except subprocess.CalledProcessError as cpe: print("result of fury push- got error") for stream in [cp.stdout, cp.stderr]: if stream: for line in stream.decode().split("\n"): print(line) print(cpe) raise # FAST. FATAL ERRORS. DON'T CHANGE THINGS THAT CHECK IN @task(mypy, detect_secrets, git_secrets, check_setup_py, compile_py, dead_code) @skip_if_no_change("pre_commit_hook") def pre_commit_hook(): # Don't format or update version # Don't do slow stuff- discourages frequent check in # Run checks that are likely to have FATAL errors, not just sloppy coding. pass # Don't break the build, but don't change source tree either. @task(mypy, detect_secrets, git_secrets, nose_tests, coverage, check_setup_py, compile_py, dead_code) @skip_if_no_change("pre_push_hook") def pre_push_hook(): # Don't format or update version # Don't do slow stuff- discourages frequent check in # Run checks that are likely to have FATAL errors, not just sloppy coding. pass def do_check_manifest(output_file_name, env): if IS_TRAVIS: command = "check-manifest".format(PYTHON).strip().split() else: command = "{0} check-manifest".format(PIPENV).strip().split() with open(output_file_name, "w") as outfile: subprocess.call(command, stdout=outfile, env=env) @task() @skip_if_no_change("check_manifest", "manifest_errors.txt") def check_manifest(): env = config_pythonpath() output_file_name = "manifest_errors.txt" do_check_manifest(output_file_name, env) with open(output_file_name) as outfile_reader: text = outfile_reader.read() print(text) if not os.path.isfile("MANIFEST.in") and "no MANIFEST.in found" in text: command = "{0} check-manifest -c".format(PIPENV).strip().split() subprocess.call(command, env=env) # print("Had to create MANIFEST.in, please review and redo") do_check_manifest(output_file_name, env) else: pass # print("found it") cutoff = 20 num_lines = sum(1 for line in open(output_file_name) if line) if num_lines > cutoff: print("Too many lines of manifest problems : {0}, max {1}".format(num_lines, cutoff)) exit(-1) @task() def echo(*args, **kwargs): """ Pure diagnostics """ print(args) print(kwargs) # Default task (if specified) is run when no task is specified in the command line # make sure you define the variable __DEFAULT__ after the task is defined # A good convention is to define it at the end of the module # __DEFAULT__ is an optional member __DEFAULT__ = echo
[]
[]
[]
[]
[]
python
0
0
mSite/views.py
from django.shortcuts import render # Create your views here. from mSite.models import FirstPage def web(request): context = { 'data': FirstPage.objects.first(), } return render(request, 'index.html', context=context)
[]
[]
[]
[]
[]
python
null
null
null
ros2_batch_job/osx_batch/__init__.py
# Copyright 2015 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess from ..batch_job import BatchJob from ..util import log from ..util import warn class OSXBatchJob(BatchJob): def __init__(self, args): self.args = args # The BatchJob constructor will set self.run and self.python BatchJob.__init__(self, python_interpreter=args.python_interpreter) def pre(self): # Prepend the PATH with `/usr/local/bin` for global Homebrew binaries. os.environ['PATH'] = '/usr/local/bin' + os.pathsep + os.environ.get('PATH', '') # Check for ccache's directory, as installed by brew ccache_exe_dir = '/usr/local/opt/ccache/libexec' if os.path.isdir(ccache_exe_dir): os.environ['PATH'] = ccache_exe_dir + os.pathsep + os.environ.get('PATH', '') else: warn('ccache does not appear to be installed; not modifying PATH') if 'LANG' not in os.environ: warn('LANG unset; using default value') os.environ['LANG'] = 'en_US.UTF-8' if 'OPENSSL_ROOT_DIR' not in os.environ: warn('OPENSSL_ROOT_DIR not set; finding openssl') brew_openssl_prefix_result = subprocess.run( ['brew', '--prefix', 'openssl'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if not brew_openssl_prefix_result.stderr: os.environ['OPENSSL_ROOT_DIR'] = \ brew_openssl_prefix_result.stdout.decode().strip('\n') else: raise KeyError('Failed to find openssl') if 'OSPL_HOME' not in os.environ: warn('OSPL_HOME not set; using default value') os.environ['OSPL_HOME'] = os.path.join( os.environ['HOME'], 'opensplice', 'HDE', 'x86_64.darwin10_clang') # TODO(wjwwood): remove this when qt5 is linked on macOS by default # See: https://github.com/Homebrew/homebrew-core/issues/8392#issuecomment-334328367 os.environ['CMAKE_PREFIX_PATH'] = os.environ.get('CMAKE_PREFIX_PATH', '') + os.pathsep + \ '/usr/local/opt/qt' def post(self): pass def show_env(self): # Show the env self.run(['export'], shell=True) # Show what brew has self.run(['brew', 'list', '--versions']) # Show what pip has self.run(['"%s"' % self.python, '-m', 'pip', 'freeze'], shell=True) def setup_env(self): connext_env_file = None if 'rmw_connext_cpp' not in self.args.ignore_rmw: # or 'rmw_connext_dynamic_cpp' not in self.args.ignore_rmw: # Try to find the connext env file and source it connext_env_file = os.path.join( '/Applications', 'rti_connext_dds-5.3.1', 'resource', 'scripts', 'rtisetenv_x64Darwin16clang8.0.bash') if not os.path.exists(connext_env_file): warn("Asked to use Connext but the RTI env was not found at '{0}'".format( connext_env_file)) connext_env_file = None # There is nothing extra to be done for OpenSplice ros1_setup_file = None if self.args.ros1_path: # Try to find the setup file and source it ros1_setup_file = os.path.join(self.args.ros1_path, 'setup.sh') if not os.path.exists(ros1_setup_file): warn("Asked to use ROS 1 but the setup file was not found at '{0}'".format( ros1_setup_file)) ros1_setup_file = None current_run = self.run def with_vendors(cmd, **kwargs): # Ensure shell is on since we're using && kwargs['shell'] = True # If the connext file is there, source it. if connext_env_file is not None: cmd = ['.', '"%s"' % connext_env_file, '&&'] + cmd log('(RTI)') if ros1_setup_file: cmd = ['.', '"%s"' % ros1_setup_file, '&&'] + cmd log('(ROS1)') # Pass along to the original runner return current_run(cmd, **kwargs) # Push the custom runner self.push_run(with_vendors)
[]
[]
[ "OPENSSL_ROOT_DIR", "CMAKE_PREFIX_PATH", "OSPL_HOME", "HOME", "LANG", "PATH" ]
[]
["OPENSSL_ROOT_DIR", "CMAKE_PREFIX_PATH", "OSPL_HOME", "HOME", "LANG", "PATH"]
python
6
0
app/app/settings.py
""" Django settings for app project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('WEBSITE_DJANGO_SECRET') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' ### New Settings AUTH_USER_MODEL = 'core.User'
[]
[]
[ "DB_HOST", "DB_NAME", "WEBSITE_DJANGO_SECRET", "DB_PASS", "DB_USER" ]
[]
["DB_HOST", "DB_NAME", "WEBSITE_DJANGO_SECRET", "DB_PASS", "DB_USER"]
python
5
0
pkg/common/config/config.go
package config import ( "io/ioutil" "os" "path/filepath" "runtime" "gopkg.in/yaml.v3" ) var ( _, b, _, _ = runtime.Caller(0) // Root folder of this project Root = filepath.Join(filepath.Dir(b), "../../..") ) var Config config type callBackConfig struct { Enable bool `yaml:"enable"` CallbackTimeOut int `yaml:"callbackTimeOut"` CallbackFailedContinue bool `yaml:"callbackFailedContinue"` } type config struct { ServerIP string `yaml:"serverip"` RpcRegisterIP string `yaml:"rpcRegisterIP"` ListenIP string `yaml:"listenIP"` ServerVersion string `yaml:"serverversion"` Api struct { GinPort []int `yaml:"openImApiPort"` ListenIP string `yaml:"listenIP"` } CmsApi struct { GinPort []int `yaml:"openImCmsApiPort"` ListenIP string `yaml:"listenIP"` } Sdk struct { WsPort []int `yaml:"openImSdkWsPort"` DataDir []string `yaml:"dataDir"` } Credential struct { Tencent struct { AppID string `yaml:"appID"` Region string `yaml:"region"` Bucket string `yaml:"bucket"` SecretID string `yaml:"secretID"` SecretKey string `yaml:"secretKey"` } Ali struct { RegionID string `yaml:"regionID"` AccessKeyID string `yaml:"accessKeyID"` AccessKeySecret string `yaml:"accessKeySecret"` StsEndpoint string `yaml:"stsEndpoint"` OssEndpoint string `yaml:"ossEndpoint"` Bucket string `yaml:"bucket"` FinalHost string `yaml:"finalHost"` StsDurationSeconds int64 `yaml:"stsDurationSeconds"` OssRoleArn string `yaml:"OssRoleArn"` } Minio struct { Bucket string `yaml:"bucket"` AppBucket string `yaml:"appBucket"` Location string `yaml:"location"` Endpoint string `yaml:"endpoint"` AccessKeyID string `yaml:"accessKeyID"` SecretAccessKey string `yaml:"secretAccessKey"` EndpointInner string `yaml:"endpointInner"` EndpointInnerEnable bool `yaml:"endpointInnerEnable"` } `yaml:"minio"` } Mysql struct { DBAddress []string `yaml:"dbMysqlAddress"` DBUserName string `yaml:"dbMysqlUserName"` DBPassword string `yaml:"dbMysqlPassword"` DBDatabaseName string `yaml:"dbMysqlDatabaseName"` DBTableName string `yaml:"DBTableName"` DBMsgTableNum int `yaml:"dbMsgTableNum"` DBMaxOpenConns int `yaml:"dbMaxOpenConns"` DBMaxIdleConns int `yaml:"dbMaxIdleConns"` DBMaxLifeTime int `yaml:"dbMaxLifeTime"` } Mongo struct { DBUri string `yaml:"dbUri"` DBAddress []string `yaml:"dbAddress"` DBDirect bool `yaml:"dbDirect"` DBTimeout int `yaml:"dbTimeout"` DBDatabase string `yaml:"dbDatabase"` DBSource string `yaml:"dbSource"` DBUserName string `yaml:"dbUserName"` DBPassword string `yaml:"dbPassword"` DBMaxPoolSize int `yaml:"dbMaxPoolSize"` DBRetainChatRecords int `yaml:"dbRetainChatRecords"` } Redis struct { DBAddress string `yaml:"dbAddress"` DBMaxIdle int `yaml:"dbMaxIdle"` DBMaxActive int `yaml:"dbMaxActive"` DBIdleTimeout int `yaml:"dbIdleTimeout"` DBPassWord string `yaml:"dbPassWord"` } RpcPort struct { OpenImUserPort []int `yaml:"openImUserPort"` openImFriendPort []int `yaml:"openImFriendPort"` RpcMessagePort []int `yaml:"rpcMessagePort"` RpcPushMessagePort []int `yaml:"rpcPushMessagePort"` OpenImGroupPort []int `yaml:"openImGroupPort"` RpcModifyUserInfoPort []int `yaml:"rpcModifyUserInfoPort"` RpcGetTokenPort []int `yaml:"rpcGetTokenPort"` } RpcRegisterName struct { OpenImStatisticsName string `yaml:"openImStatisticsName"` OpenImUserName string `yaml:"openImUserName"` OpenImFriendName string `yaml:"openImFriendName"` OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"` OpenImPushName string `yaml:"openImPushName"` OpenImOnlineMessageRelayName string `yaml:"openImOnlineMessageRelayName"` OpenImGroupName string `yaml:"openImGroupName"` OpenImAuthName string `yaml:"openImAuthName"` OpenImMessageCMSName string `yaml:"openImMessageCMSName"` OpenImAdminCMSName string `yaml:"openImAdminCMSName"` OpenImOfficeName string `yaml:"openImOfficeName"` OpenImOrganizationName string `yaml:"openImOrganizationName"` OpenImConversationName string `yaml:"openImConversationName"` OpenImCacheName string `yaml:"openImCacheName"` OpenImRealTimeCommName string `yaml:"openImRealTimeCommName"` } Etcd struct { EtcdSchema string `yaml:"etcdSchema"` EtcdAddr []string `yaml:"etcdAddr"` } Log struct { StorageLocation string `yaml:"storageLocation"` RotationTime int `yaml:"rotationTime"` RemainRotationCount uint `yaml:"remainRotationCount"` RemainLogLevel uint `yaml:"remainLogLevel"` ElasticSearchSwitch bool `yaml:"elasticSearchSwitch"` ElasticSearchAddr []string `yaml:"elasticSearchAddr"` ElasticSearchUser string `yaml:"elasticSearchUser"` ElasticSearchPassword string `yaml:"elasticSearchPassword"` } ModuleName struct { LongConnSvrName string `yaml:"longConnSvrName"` MsgTransferName string `yaml:"msgTransferName"` PushName string `yaml:"pushName"` } LongConnSvr struct { WebsocketPort []int `yaml:"openImWsPort"` WebsocketMaxConnNum int `yaml:"websocketMaxConnNum"` WebsocketMaxMsgLen int `yaml:"websocketMaxMsgLen"` WebsocketTimeOut int `yaml:"websocketTimeOut"` } Push struct { Tpns struct { Ios struct { AccessID string `yaml:"accessID"` SecretKey string `yaml:"secretKey"` } Android struct { AccessID string `yaml:"accessID"` SecretKey string `yaml:"secretKey"` } Enable bool `yaml:"enable"` } Jpns struct { AppKey string `yaml:"appKey"` MasterSecret string `yaml:"masterSecret"` PushUrl string `yaml:"pushUrl"` PushIntent string `yaml:"pushIntent"` Enable bool `yaml:"enable"` } Getui struct { PushUrl string `yaml:"pushUrl"` AppKey string `yaml:"appKey"` Enable bool `yaml:"enable"` Intent string `yaml:"intent"` MasterSecret string `yaml:"masterSecret"` } } Manager struct { AppManagerUid []string `yaml:"appManagerUid"` Secrets []string `yaml:"secrets"` } Kafka struct { Ws2mschat struct { Addr []string `yaml:"addr"` Topic string `yaml:"topic"` } Ws2mschatOffline struct { Addr []string `yaml:"addr"` Topic string `yaml:"topic"` } Ms2pschat struct { Addr []string `yaml:"addr"` Topic string `yaml:"topic"` } ConsumerGroupID struct { MsgToMongo string `yaml:"msgToMongo"` MsgToMongoOffline string `yaml:"msgToMongoOffline"` MsgToMySql string `yaml:"msgToMySql"` MsgToPush string `yaml:"msgToPush"` } } Secret string `yaml:"secret"` MultiLoginPolicy int `yaml:"multiloginpolicy"` ChatPersistenceMysql bool `yaml:"chatPersistenceMysql"` TokenPolicy struct { AccessSecret string `yaml:"accessSecret"` AccessExpire int64 `yaml:"accessExpire"` } MessageVerify struct { FriendVerify bool `yaml:"friendVerify"` } IOSPush struct { PushSound string `yaml:"pushSound"` BadgeCount bool `yaml:"badgeCount"` } Callback struct { CallbackUrl string `yaml:"callbackUrl"` CallbackBeforeSendSingleMsg callBackConfig `yaml:"callbackbeforeSendSingleMsg"` CallbackAfterSendSingleMsg callBackConfig `yaml:"callbackAfterSendSingleMsg"` CallbackBeforeSendGroupMsg callBackConfig `yaml:"callbackBeforeSendGroupMsg"` CallbackAfterSendGroupMsg callBackConfig `yaml:"callbackAfterSendGroupMsg"` CallbackWordFilter callBackConfig `yaml:"callbackWordFilter"` } `yaml:"callback"` Notification struct { ///////////////////////group///////////////////////////// GroupCreated struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupCreated"` GroupInfoSet struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupInfoSet"` JoinGroupApplication struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"joinGroupApplication"` MemberQuit struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"memberQuit"` GroupApplicationAccepted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupApplicationAccepted"` GroupApplicationRejected struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupApplicationRejected"` GroupOwnerTransferred struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupOwnerTransferred"` MemberKicked struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"memberKicked"` MemberInvited struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"memberInvited"` MemberEnter struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"memberEnter"` GroupDismissed struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupDismissed"` GroupMuted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupMuted"` GroupCancelMuted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupCancelMuted"` GroupMemberMuted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupMemberMuted"` GroupMemberCancelMuted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupMemberCancelMuted"` GroupMemberInfoSet struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"groupMemberInfoSet"` OrganizationChanged struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"organizationChanged"` ////////////////////////user/////////////////////// UserInfoUpdated struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"userInfoUpdated"` //////////////////////friend/////////////////////// FriendApplication struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendApplicationAdded"` FriendApplicationApproved struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendApplicationApproved"` FriendApplicationRejected struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendApplicationRejected"` FriendAdded struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendAdded"` FriendDeleted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendDeleted"` FriendRemarkSet struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"friendRemarkSet"` BlackAdded struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"blackAdded"` BlackDeleted struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"blackDeleted"` ConversationOptUpdate struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"conversationOptUpdate"` ConversationSetPrivate struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips struct { OpenTips string `yaml:"openTips"` CloseTips string `yaml:"closeTips"` } `yaml:"defaultTips"` } `yaml:"conversationSetPrivate"` WorkMomentsNotification struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"workMomentsNotification"` JoinDepartmentNotification struct { Conversation PConversation `yaml:"conversation"` OfflinePush POfflinePush `yaml:"offlinePush"` DefaultTips PDefaultTips `yaml:"defaultTips"` } `yaml:"joinDepartmentNotification"` } Demo struct { Port []int `yaml:"openImDemoPort"` ListenIP string `yaml:"listenIP"` AliSMSVerify struct { AccessKeyID string `yaml:"accessKeyId"` AccessKeySecret string `yaml:"accessKeySecret"` SignName string `yaml:"signName"` VerificationCodeTemplateCode string `yaml:"verificationCodeTemplateCode"` } SuperCode string `yaml:"superCode"` CodeTTL int `yaml:"codeTTL"` Mail struct { Title string `yaml:"title"` SenderMail string `yaml:"senderMail"` SenderAuthorizationCode string `yaml:"senderAuthorizationCode"` SmtpAddr string `yaml:"smtpAddr"` SmtpPort int `yaml:"smtpPort"` } TestDepartMentID string `yaml:"testDepartMentID"` } Rtc struct { Port int `yaml:"port"` Address string `yaml:"address"` } `yaml:"rtc"` } type PConversation struct { ReliabilityLevel int `yaml:"reliabilityLevel"` UnreadCount bool `yaml:"unreadCount"` } type POfflinePush struct { PushSwitch bool `yaml:"switch"` Title string `yaml:"title"` Desc string `yaml:"desc"` Ext string `yaml:"ext"` } type PDefaultTips struct { Tips string `yaml:"tips"` } func init() { cfgName := os.Getenv("CONFIG_NAME") if len(cfgName) == 0 { cfgName = Root + "/config/config.yaml" } bytes, err := ioutil.ReadFile(cfgName) if err != nil { panic(err.Error()) } if err = yaml.Unmarshal(bytes, &Config); err != nil { panic(err.Error()) } }
[ "\"CONFIG_NAME\"" ]
[]
[ "CONFIG_NAME" ]
[]
["CONFIG_NAME"]
go
1
0
django_reddit/settings/production.py
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use mailgun to send emails ''' from django.utils import six from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env("DJANGO_SECRET_KEY") # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # django-secure # ------------------------------------------------------------------------------ INSTALLED_APPS += ("djangosecure", ) SECURITY_MIDDLEWARE = ( 'djangosecure.middleware.SecurityMiddleware', ) MIDDLEWARE_CLASSES = () # Make sure djangosecure.middleware.SecurityMiddleware is listed first MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES # set this to 60 seconds and then to 518400 when you can prove it works SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool( "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True) SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # SITE CONFIGURATION # ------------------------------------------------------------------------------ # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['example.com']) # END SITE CONFIGURATION INSTALLED_APPS += ("gunicorn", ) # EMAIL # ------------------------------------------------------------------------------ DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', default='django_reddit <noreply@domain_name') EMAIL_BACKEND = 'django_mailgun.MailgunBackend' MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY') MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME') EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[django_reddit] ') SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ # See: # https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader TEMPLATES[0]['OPTIONS']['loaders'] = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ DATABASES['default'] = env.db("DATABASE_URL") # CACHING # ------------------------------------------------------------------------------ # Heroku URL does not pass the DB number, so we parse it in CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "{0}/{1}".format(env.cache_url('REDIS_URL', default="redis://127.0.0.1:6379"), 0), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, # mimics memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior } } } # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } } # Custom Admin URL ADMIN_URL = env('DJANGO_ADMIN_URL') # Your production stuff: Below this line define 3rd party library settings
[]
[]
[]
[]
[]
python
0
0
src/syscall/syscall_unix_test.go
// Copyright 2013-2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris zos package syscall_test import ( "flag" "fmt" "internal/testenv" "io/ioutil" "net" "os" "os/exec" "path/filepath" "runtime" "syscall" "testing" "time" ) // Tests that below functions, structures and constants are consistent // on all Unix-like systems. func _() { // program scheduling priority functions and constants var ( _ func(int, int, int) error = syscall.Setpriority _ func(int, int) (int, error) = syscall.Getpriority ) const ( _ int = syscall.PRIO_USER _ int = syscall.PRIO_PROCESS _ int = syscall.PRIO_PGRP ) // termios constants const ( _ int = syscall.TCIFLUSH _ int = syscall.TCIOFLUSH _ int = syscall.TCOFLUSH ) // fcntl file locking structure and constants var ( _ = syscall.Flock_t{ Type: int16(0), Whence: int16(0), Start: int64(0), Len: int64(0), Pid: int32(0), } ) const ( _ = syscall.F_GETLK _ = syscall.F_SETLK _ = syscall.F_SETLKW ) } // TestFcntlFlock tests whether the file locking structure matches // the calling convention of each kernel. // On some Linux systems, glibc uses another set of values for the // commands and translates them to the correct value that the kernel // expects just before the actual fcntl syscall. As Go uses raw // syscalls directly, it must use the real value, not the glibc value. // Thus this test also verifies that the Flock_t structure can be // roundtripped with F_SETLK and F_GETLK. func TestFcntlFlock(t *testing.T) { if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") { t.Skip("skipping; no child processes allowed on iOS") } flock := syscall.Flock_t{ Type: syscall.F_WRLCK, Start: 31415, Len: 271828, Whence: 1, } if os.Getenv("GO_WANT_HELPER_PROCESS") == "" { // parent name := filepath.Join(os.TempDir(), "TestFcntlFlock") fd, err := syscall.Open(name, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0) if err != nil { t.Fatalf("Open failed: %v", err) } defer syscall.Unlink(name) defer syscall.Close(fd) if err := syscall.Ftruncate(fd, 1<<20); err != nil { t.Fatalf("Ftruncate(1<<20) failed: %v", err) } if err := syscall.FcntlFlock(uintptr(fd), syscall.F_SETLK, &flock); err != nil { t.Fatalf("FcntlFlock(F_SETLK) failed: %v", err) } cmd := exec.Command(os.Args[0], "-test.run=^TestFcntlFlock$") cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") cmd.ExtraFiles = []*os.File{os.NewFile(uintptr(fd), name)} out, err := cmd.CombinedOutput() if len(out) > 0 || err != nil { t.Fatalf("child process: %q, %v", out, err) } } else { // child got := flock // make sure the child lock is conflicting with the parent lock got.Start-- got.Len++ if err := syscall.FcntlFlock(3, syscall.F_GETLK, &got); err != nil { t.Fatalf("FcntlFlock(F_GETLK) failed: %v", err) } flock.Pid = int32(syscall.Getppid()) // Linux kernel always set Whence to 0 flock.Whence = 0 if got.Type == flock.Type && got.Start == flock.Start && got.Len == flock.Len && got.Pid == flock.Pid && got.Whence == flock.Whence { os.Exit(0) } t.Fatalf("FcntlFlock got %v, want %v", got, flock) } } // TestPassFD tests passing a file descriptor over a Unix socket. // // This test involved both a parent and child process. The parent // process is invoked as a normal test, with "go test", which then // runs the child process by running the current test binary with args // "-test.run=^TestPassFD$" and an environment variable used to signal // that the test should become the child process instead. func TestPassFD(t *testing.T) { switch runtime.GOOS { case "dragonfly": // TODO(jsing): Figure out why sendmsg is returning EINVAL. t.Skip("skipping test on dragonfly") case "solaris": // TODO(aram): Figure out why ReadMsgUnix is returning empty message. t.Skip("skipping test on solaris, see issue 7402") case "zos": // TODO(mundaym): Figure out why sendmsg is returning EINVAL. t.Skip("skipping test on zos") } testenv.MustHaveExec(t) if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { passFDChild() return } tempDir, err := ioutil.TempDir("", "TestPassFD") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer syscall.Close(fds[0]) defer syscall.Close(fds[1]) writeFile := os.NewFile(uintptr(fds[0]), "child-writes") readFile := os.NewFile(uintptr(fds[1]), "parent-reads") defer writeFile.Close() defer readFile.Close() cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") cmd.ExtraFiles = []*os.File{writeFile} out, err := cmd.CombinedOutput() if len(out) > 0 || err != nil { t.Fatalf("child process: %q, %v", out, err) } c, err := net.FileConn(readFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer c.Close() uc, ok := c.(*net.UnixConn) if !ok { t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) } buf := make([]byte, 32) // expect 1 byte oob := make([]byte, 32) // expect 24 bytes closeUnix := time.AfterFunc(5*time.Second, func() { t.Logf("timeout reading from unix socket") uc.Close() }) _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) closeUnix.Stop() scms, err := syscall.ParseSocketControlMessage(oob[:oobn]) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != 1 { t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) } scm := scms[0] gotFds, err := syscall.ParseUnixRights(&scm) if err != nil { t.Fatalf("syscall.ParseUnixRights: %v", err) } if len(gotFds) != 1 { t.Fatalf("wanted 1 fd; got %#v", gotFds) } f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") defer f.Close() got, err := ioutil.ReadAll(f) want := "Hello from child process!\n" if string(got) != want { t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) } } // passFDChild is the child process used by TestPassFD. func passFDChild() { defer os.Exit(0) // Look for our fd. It should be fd 3, but we work around an fd leak // bug here (https://golang.org/issue/2603) to let it be elsewhere. var uc *net.UnixConn for fd := uintptr(3); fd <= 10; fd++ { f := os.NewFile(fd, "unix-conn") var ok bool netc, _ := net.FileConn(f) uc, ok = netc.(*net.UnixConn) if ok { break } } if uc == nil { fmt.Println("failed to find unix fd") return } // Make a file f to send to our parent process on uc. // We make it in tempDir, which our parent will clean up. flag.Parse() tempDir := flag.Arg(0) f, err := ioutil.TempFile(tempDir, "") if err != nil { fmt.Printf("TempFile: %v", err) return } f.Write([]byte("Hello from child process!\n")) f.Seek(0, 0) rights := syscall.UnixRights(int(f.Fd())) dummyByte := []byte("x") n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) if err != nil { fmt.Printf("WriteMsgUnix: %v", err) return } if n != 1 || oobn != len(rights) { fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) return } } // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, // and ParseUnixRights are able to successfully round-trip lists of file descriptors. func TestUnixRightsRoundtrip(t *testing.T) { testCases := [...][][]int{ {{42}}, {{1, 2}}, {{3, 4, 5}}, {{}}, {{1, 2}, {3, 4, 5}, {}, {7}}, } for _, testCase := range testCases { b := []byte{} var n int for _, fds := range testCase { // Last assignment to n wins n = len(b) + syscall.CmsgLen(4*len(fds)) b = append(b, syscall.UnixRights(fds...)...) } // Truncate b b = b[:n] scms, err := syscall.ParseSocketControlMessage(b) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != len(testCase) { t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) } for i, scm := range scms { gotFds, err := syscall.ParseUnixRights(&scm) if err != nil { t.Fatalf("ParseUnixRights: %v", err) } wantFds := testCase[i] if len(gotFds) != len(wantFds) { t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) } for j, fd := range gotFds { if fd != wantFds[j] { t.Fatalf("expected fd %v, got %v", wantFds[j], fd) } } } } } func TestRlimit(t *testing.T) { var rlimit, zero syscall.Rlimit err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Getrlimit: save failed: %v", err) } if zero == rlimit { t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) } set := rlimit set.Cur = set.Max - 1 err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &set) if err != nil { t.Fatalf("Setrlimit: set failed: %#v %v", set, err) } var get syscall.Rlimit err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &get) if err != nil { t.Fatalf("Getrlimit: get failed: %v", err) } set = rlimit set.Cur = set.Max - 1 if set != get { // Seems like Darwin requires some privilege to // increase the soft limit of rlimit sandbox, though // Setrlimit never reports an error. switch runtime.GOOS { case "darwin": default: t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) } } err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) } } func TestSeekFailure(t *testing.T) { _, err := syscall.Seek(-1, 0, 0) if err == nil { t.Fatalf("Seek(-1, 0, 0) did not fail") } str := err.Error() // used to crash on Linux t.Logf("Seek: %v", str) if str == "" { t.Fatalf("Seek(-1, 0, 0) return error with empty message") } }
[ "\"GO_WANT_HELPER_PROCESS\"", "\"GO_WANT_HELPER_PROCESS\"" ]
[]
[ "GO_WANT_HELPER_PROCESS" ]
[]
["GO_WANT_HELPER_PROCESS"]
go
1
0
sdk/tables/azure-data-tables/samples/sample_insert_delete_entities.py
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: sample_insert_delete_entities.py DESCRIPTION: These samples demonstrate the following: inserting entities into a table and deleting tables from a table. USAGE: python sample_insert_delete_entities.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account """ import os from dotenv import find_dotenv, load_dotenv class InsertDeleteEntity(object): def __init__(self): load_dotenv(find_dotenv()) self.access_key = os.getenv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY") self.endpoint = os.getenv("TABLES_STORAGE_ENDPOINT_SUFFIX") self.account_name = os.getenv("TABLES_STORAGE_ACCOUNT_NAME") self.account_url = "{}.table.{}".format(self.account_name, self.endpoint) self.connection_string = u"DefaultEndpointsProtocol=https;AccountName={};AccountKey={};EndpointSuffix={}".format( self.account_name, self.access_key, self.endpoint ) self.table_name = "SampleInsertDelete" self.entity = { u'PartitionKey': u'color', u'RowKey': u'brand', u'text': u'Marker', u'color': u'Purple', u'price': u'5' } def create_entity(self): from azure.data.tables import TableClient from azure.core.exceptions import ResourceExistsError, HttpResponseError with TableClient.from_connection_string(self.connection_string, self.table_name) as table_client: # Create a table in case it does not already exist try: table_client.create_table() except HttpResponseError: print("Table already exists") # [START create_entity] try: entity = table_client.create_entity(entity=self.entity) print(entity) except ResourceExistsError: print("Entity already exists") # [END create_entity] def delete_entity(self): from azure.data.tables import TableClient from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError from azure.core.credentials import AzureNamedKeyCredential credential = AzureNamedKeyCredential(self.account_name, self.access_key) with TableClient(account_url=self.account_url, credential=credential, table_name=self.table_name) as table_client: # Create entity to delete (to showcase etag) try: resp = table_client.create_entity(entity=self.entity) except ResourceExistsError: print("Entity already exists!") # [START delete_entity] try: table_client.delete_entity( row_key=self.entity["RowKey"], partition_key=self.entity["PartitionKey"] ) print("Successfully deleted!") except ResourceNotFoundError: print("Entity does not exists") # [END delete_entity] if __name__ == '__main__': ide = InsertDeleteEntity() ide.create_entity() ide.delete_entity()
[]
[]
[ "TABLES_STORAGE_ACCOUNT_NAME", "TABLES_STORAGE_ENDPOINT_SUFFIX", "TABLES_PRIMARY_STORAGE_ACCOUNT_KEY" ]
[]
["TABLES_STORAGE_ACCOUNT_NAME", "TABLES_STORAGE_ENDPOINT_SUFFIX", "TABLES_PRIMARY_STORAGE_ACCOUNT_KEY"]
python
3
0
pkg/cli/rsh/rsh.go
package rsh import ( "fmt" "os" "time" "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/kubectl/pkg/cmd/exec" kcmdutil "k8s.io/kubectl/pkg/cmd/util" "k8s.io/kubectl/pkg/util/templates" "k8s.io/kubectl/pkg/util/term" ) const ( RshRecommendedName = "rsh" DefaultShell = "/bin/sh" defaultPodRshTimeout = 60 * time.Second ) var ( rshUsageStr = "rsh (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]" rshUsageErrStr = fmt.Sprintf("expected '%s'.\nPOD or TYPE/NAME is a required argument for the rsh command", rshUsageStr) rshLong = templates.LongDesc(` Open a remote shell session to a container This command will attempt to start a shell session in a pod for the specified resource. It works with pods, deployment configs, deployments, jobs, daemon sets, replication controllers and replica sets. Any of the aforementioned resources (apart from pods) will be resolved to a ready pod. It will default to the first container if none is specified, and will attempt to use '/bin/sh' as the default shell. You may pass any flags supported by this command before the resource name, and an optional command after the resource name, which will be executed instead of a login shell. A TTY will be automatically allocated if standard input is interactive - use -t and -T to override. A TERM variable is sent to the environment where the shell (or command) will be executed. By default its value is the same as the TERM variable from the local environment; if not set, 'xterm' is used. Note, some containers may not include a shell - use '%[1]s exec' if you need to run commands directly.`) rshExample = templates.Examples(` # Open a shell session on the first container in pod 'foo' %[1]s foo # Open a shell session on the first container in pod 'foo' and namespace 'bar' # (Note that oc client specific arguments must come before the resource name and its arguments) %[1]s -n bar foo # Run the command 'cat /etc/resolv.conf' inside pod 'foo' %[1]s foo cat /etc/resolv.conf # See the configuration of your internal registry %[1]s dc/docker-registry cat config.yml # Open a shell session on the container named 'index' inside a pod of your job %[1]s -c index job/sheduled`) ) // RshOptions declare the arguments accepted by the Rsh command type RshOptions struct { ForceTTY bool DisableTTY bool Executable string Timeout int *exec.ExecOptions } func NewRshOptions(parent string, streams genericclioptions.IOStreams) *RshOptions { return &RshOptions{ ForceTTY: false, DisableTTY: false, Timeout: 10, Executable: DefaultShell, ExecOptions: &exec.ExecOptions{ StreamOptions: exec.StreamOptions{ IOStreams: streams, TTY: true, Stdin: true, }, ParentCommandName: parent, Executor: &exec.DefaultRemoteExecutor{}, }, } } // NewCmdRsh returns a command that attempts to open a shell session to the server. func NewCmdRsh(name string, parent string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command { options := NewRshOptions(parent, streams) cmd := &cobra.Command{ Use: rshUsageStr, DisableFlagsInUseLine: true, Short: "Start a shell session in a container.", Long: fmt.Sprintf(rshLong, parent), Example: fmt.Sprintf(rshExample, parent+" "+name), Run: func(cmd *cobra.Command, args []string) { kcmdutil.CheckErr(options.Complete(f, cmd, args)) kcmdutil.CheckErr(options.Validate()) kcmdutil.CheckErr(options.Run()) }, } kcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodRshTimeout) cmd.Flags().BoolVarP(&options.ForceTTY, "tty", "t", options.ForceTTY, "Force a pseudo-terminal to be allocated") cmd.Flags().BoolVarP(&options.DisableTTY, "no-tty", "T", options.DisableTTY, "Disable pseudo-terminal allocation") cmd.Flags().StringVar(&options.Executable, "shell", options.Executable, "Path to the shell command") cmd.Flags().IntVar(&options.Timeout, "timeout", options.Timeout, "Request timeout for obtaining a pod from the server; defaults to 10 seconds") cmd.Flags().MarkDeprecated("timeout", "use --request-timeout, instead.") cmd.Flags().StringVarP(&options.ContainerName, "container", "c", options.ContainerName, "Container name; defaults to first container") cmd.Flags().SetInterspersed(false) return cmd } // Complete applies the command environment to RshOptions func (o *RshOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error { argsLenAtDash := cmd.ArgsLenAtDash() if len(args) == 0 || argsLenAtDash == 0 { return kcmdutil.UsageErrorf(cmd, "%s", rshUsageErrStr) } switch { case o.ForceTTY && o.DisableTTY: return kcmdutil.UsageErrorf(cmd, "you may not specify -t and -T together") case o.ForceTTY: o.TTY = true case o.DisableTTY: o.TTY = false default: o.TTY = term.IsTerminal(o.In) } // Value of argsLenAtDash is -1 since cmd.ArgsLenAtDash() assumes all the flags // of flag.FlagSet were parsed. The opposite is true. Thus, it needs to be computed manually. // In case the command is present, the first item in args is a pod name, // the rest is a command and its arguments. // Kubectl exec expects the command to be preceded by '--'. // Oc rsh always provides the command as the second item of args. if len(args) > 1 { argsLenAtDash = 1 } if err := o.ExecOptions.Complete(f, cmd, args, argsLenAtDash); err != nil { return err } // overwrite ExecOptions with rsh specifics args = args[1:] if len(args) > 0 { o.Command = args } else { o.Command = []string{o.Executable} } fullCmdName := "" cmdParent := cmd.Parent() if cmdParent != nil { fullCmdName = cmdParent.CommandPath() } o.ExecOptions.EnableSuggestedCmdUsage = len(fullCmdName) > 0 && kcmdutil.IsSiblingCommandExists(cmd, "describe") return nil } // Validate ensures that RshOptions are valid func (o *RshOptions) Validate() error { return o.ExecOptions.Validate() } // Run starts a remote shell session on the server func (o *RshOptions) Run() error { // Insert the TERM into the command to be run if len(o.Command) == 1 && o.Command[0] == DefaultShell { term := os.Getenv("TERM") if len(term) == 0 { term = "xterm" } termsh := fmt.Sprintf("TERM=%q %s", term, DefaultShell) o.Command = append(o.Command, "-c", termsh) } return o.ExecOptions.Run() }
[ "\"TERM\"" ]
[]
[ "TERM" ]
[]
["TERM"]
go
1
0
testutils/clustermanager/e2e-tests/setup_test.go
/* Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clustermanager import ( "fmt" "io/ioutil" "os" "testing" "github.com/google/go-cmp/cmp" "knative.dev/pkg/test/gke" "knative.dev/pkg/testutils/clustermanager/e2e-tests/common" ) var ( fakeProj = "b" fakeCluster = "d" ) func TestSetup(t *testing.T) { minNodesOverride := int64(2) maxNodesOverride := int64(4) nodeTypeOverride := "foonode" regionOverride := "fooregion" zoneOverride := "foozone" boskosResTypeOverride := "customResType" fakeAddons := "fake-addon" fakeBuildID := "1234" type env struct { isProw bool regionEnv string backupRegionEnv string } tests := []struct { name string arg GKERequest env env want *GKECluster }{ { name: "Defaults, not running in Prow", arg: GKERequest{}, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, { name: "Defaults, running in Prow", arg: GKERequest{}, env: env{true, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, { name: "Custom Boskos Resource type, running in Prow", arg: GKERequest{ResourceType: boskosResTypeOverride}, env: env{true, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: boskosResTypeOverride, }, }, }, { name: "Project provided, not running in Prow", arg: GKERequest{ Request: gke.Request{ Project: fakeProj, GKEVersion: "1.2.3", }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", Project: "b", GKEVersion: "1.2.3", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, Project: fakeProj, asyncCleanup: true, }, }, { name: "Project provided, running in Prow", arg: GKERequest{ Request: gke.Request{ Project: fakeProj, }, }, env: env{true, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", Project: "b", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, Project: fakeProj, asyncCleanup: true, }, }, { name: "Cluster name provided, not running in Prow", arg: GKERequest{ Request: gke.Request{ ClusterName: "predefined-cluster-name", }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "predefined-cluster-name", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, { name: "Cluster name provided, running in Prow", arg: GKERequest{ Request: gke.Request{ ClusterName: "predefined-cluster-name", }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "predefined-cluster-name", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, { name: "Override other parts", arg: GKERequest{ Request: gke.Request{ MinNodes: minNodesOverride, MaxNodes: maxNodesOverride, NodeType: nodeTypeOverride, Region: regionOverride, Zone: zoneOverride, }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 2, MaxNodes: 4, NodeType: "foonode", Region: "fooregion", Zone: "foozone", Addons: nil, }, BackupRegions: []string{}, ResourceType: defaultResourceType, }, }, }, { name: "Override other parts but not zone", arg: GKERequest{ Request: gke.Request{ MinNodes: minNodesOverride, MaxNodes: maxNodesOverride, NodeType: nodeTypeOverride, Region: regionOverride, }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 2, MaxNodes: 4, NodeType: "foonode", Region: "fooregion", Zone: "", Addons: nil, }, BackupRegions: nil, ResourceType: defaultResourceType, }, }, }, { name: "Min Nodes > Max Nodes", arg: GKERequest{ Request: gke.Request{ MinNodes: 10, NodeType: nodeTypeOverride, Region: regionOverride, }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 10, MaxNodes: 10, NodeType: "foonode", Region: "fooregion", Zone: "", Addons: nil, }, BackupRegions: nil, ResourceType: defaultResourceType, }, }, }, { name: "Set env Region", arg: GKERequest{}, env: env{false, "customregion", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "customregion", Zone: "", Addons: nil, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, { name: "Set env backupzone", arg: GKERequest{}, env: env{false, "", "backupregion1 backupregion2"}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: nil, }, BackupRegions: []string{"backupregion1", "backupregion2"}, ResourceType: defaultResourceType, }, }, }, { name: "Set addons", arg: GKERequest{ Request: gke.Request{ Addons: []string{fakeAddons}, }, }, env: env{false, "", ""}, want: &GKECluster{ Request: &GKERequest{ Request: gke.Request{ ClusterName: "", MinNodes: 1, MaxNodes: 3, NodeType: "e2-standard-4", Region: "us-central1", Zone: "", Addons: []string{fakeAddons}, }, BackupRegions: []string{"us-west1", "us-east1"}, ResourceType: defaultResourceType, }, }, }, } // mock GetOSEnv for testing oldEnvFunc := common.GetOSEnv oldExecFunc := common.StandardExec oldDefaultCred := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") tf, _ := ioutil.TempFile("", "foo") tf.WriteString(`{"type": "service_account"}`) os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", tf.Name()) defer func() { // restore common.GetOSEnv = oldEnvFunc common.StandardExec = oldExecFunc os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", oldDefaultCred) os.Remove(tf.Name()) }() // mock as kubectl not set and gcloud set as "b", so check environment // return project as "b" common.StandardExec = func(name string, args ...string) ([]byte, error) { var out []byte var err error switch name { case "gcloud": out = []byte("b") err = nil case "kubectl": out = []byte("") err = fmt.Errorf("kubectl not set") default: out, err = oldExecFunc(name, args...) } return out, err } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { common.GetOSEnv = func(s string) string { switch s { case "E2E_CLUSTER_REGION": return tt.env.regionEnv case "E2E_CLUSTER_BACKUP_REGIONS": return tt.env.backupRegionEnv case "BUILD_NUMBER": return fakeBuildID case "PROW_JOB_ID": // needed to mock IsProw() if tt.env.isProw { return "fake_job_id" } return "" } return oldEnvFunc(s) } c := GKEClient{} co := c.Setup(tt.arg) errMsg := fmt.Sprintf("testing setup with:\n\t%+v\n\tregionEnv: %v\n\tbackupRegionEnv: %v", tt.arg, tt.env.regionEnv, tt.env.backupRegionEnv) gotCo := co.(*GKECluster) // mock for easier comparison gotCo.boskosOps = nil if dif := cmp.Diff(gotCo.Request, tt.want.Request); dif != "" { t.Errorf("%s\nRequest got(+) is different from wanted(-)\n%v", errMsg, dif) } }) } }
[ "\"GOOGLE_APPLICATION_CREDENTIALS\"" ]
[]
[ "GOOGLE_APPLICATION_CREDENTIALS" ]
[]
["GOOGLE_APPLICATION_CREDENTIALS"]
go
1
0
torch/distributed/elastic/agent/server/local_elastic_agent.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import shutil import signal import tempfile from typing import Any, Dict, Optional, Tuple from torch.distributed.elastic.agent.server.api import ( RunResult, SimpleElasticAgent, WorkerGroup, WorkerSpec, WorkerState, ) from torch.distributed.elastic.metrics.api import prof from torch.distributed.elastic.multiprocessing import start_processes, PContext from torch.distributed.elastic.utils import macros from torch.distributed.elastic.utils.logging import get_logger log = get_logger() class LocalElasticAgent(SimpleElasticAgent): """ An implementation of :py:class:`torchelastic.agent.server.ElasticAgent` that handles host-local workers. This agent is deployed per host and is configured to spawn ``n`` workers. When using GPUs, ``n`` maps to the number of GPUs available on the host. The local agent does not communicate to other local agents deployed on other hosts, even if the workers may communicate inter-host. The worker id is interpreted to be a local process. The agent starts and stops all worker processes as a single unit. The worker function and argument passed to the worker function must be python multiprocessing compatible. To pass multiprocessing data structures to the workers you may create the data structure in the same multiprocessing context as the specified ``start_method`` and pass it as a function argument. The ``exit_barrier_timeout`` specifies the amount of time (in seconds) to wait for other agents to finish. This acts as a safety net to handle cases where workers finish at different times, to prevent agents from viewing workers that finished early as a scale-down event. It is strongly advised that the user code deal with ensuring that workers are terminated in a synchronous manner rather than relying on the exit_barrier_timeout. Example launching function :: def trainer(args) -> str: return "do train" def main(): start_method="spawn" shared_queue= multiprocessing.get_context(start_method).Queue() spec = WorkerSpec( role="trainer", local_world_size=nproc_per_process, entrypoint=trainer, args=("foobar",), ...<OTHER_PARAMS...>) agent = LocalElasticAgent(spec, start_method) results = agent.run() if results.is_failed(): print("trainer failed") else: print(f"rank 0 return value: {results.return_values[0]}") # prints -> rank 0 return value: do train Example launching binary :: def main(): spec = WorkerSpec( role="trainer", local_world_size=nproc_per_process, entrypoint="/usr/local/bin/trainer", args=("--trainer_args", "foobar"), ...<OTHER_PARAMS...>) agent = LocalElasticAgent(spec) results = agent.run() if not results.is_failed(): print("binary launches do not have return values") """ def __init__( self, spec: WorkerSpec, start_method="spawn", exit_barrier_timeout: float = 300, log_dir: Optional[str] = None, ): super().__init__(spec, exit_barrier_timeout) self._start_method = start_method self._pcontext: Optional[PContext] = None rdzv_run_id = spec.rdzv_handler.get_run_id() self._log_dir = self._make_log_dir(log_dir, rdzv_run_id) def _make_log_dir(self, log_dir: Optional[str], rdzv_run_id: str): base_log_dir = log_dir or tempfile.mkdtemp(prefix="torchelastic_") os.makedirs(base_log_dir, exist_ok=True) dir = tempfile.mkdtemp(prefix=f"{rdzv_run_id}_", dir=base_log_dir) log.info(f"log directory set to: {dir}") return dir @prof def _stop_workers(self, worker_group: WorkerGroup) -> None: self._shutdown() @prof def _start_workers(self, worker_group: WorkerGroup) -> Dict[int, Any]: spec = worker_group.spec store = worker_group.store assert store is not None master_addr, master_port = super()._get_master_addr_port(store) restart_count = spec.max_restarts - self._remaining_restarts use_agent_store = spec.rdzv_handler.get_backend() == "static" args: Dict[int, Tuple] = {} envs: Dict[int, Dict[str, str]] = {} for worker in worker_group.workers: local_rank = worker.local_rank worker_env = { "LOCAL_RANK": str(local_rank), "RANK": str(worker.global_rank), "GROUP_RANK": str(worker_group.group_rank), "ROLE_RANK": str(worker.role_rank), "ROLE_NAME": spec.role, "LOCAL_WORLD_SIZE": str(spec.local_world_size), "WORLD_SIZE": str(worker.world_size), "GROUP_WORLD_SIZE": str(worker_group.group_world_size), "ROLE_WORLD_SIZE": str(worker.role_world_size), "MASTER_ADDR": master_addr, "MASTER_PORT": str(master_port), "TORCHELASTIC_RESTART_COUNT": str(restart_count), "TORCHELASTIC_MAX_RESTARTS": str(spec.max_restarts), "TORCHELASTIC_RUN_ID": spec.rdzv_handler.get_run_id(), "TORCHELASTIC_USE_AGENT_STORE": str(use_agent_store), "NCCL_ASYNC_ERROR_HANDLING": str(1), } if "OMP_NUM_THREADS" in os.environ: worker_env["OMP_NUM_THREADS"] = os.environ["OMP_NUM_THREADS"] envs[local_rank] = worker_env worker_args = list(spec.args) worker_args = macros.substitute(worker_args, str(local_rank)) args[local_rank] = tuple(worker_args) # scaling events do not count towards restarts (gets same attempt #) # remove existing log dir if this restart is due to a scaling event attempt_log_dir = os.path.join(self._log_dir, f"attempt_{restart_count}") shutil.rmtree(attempt_log_dir, ignore_errors=True) os.makedirs(attempt_log_dir) assert spec.entrypoint is not None self._pcontext = start_processes( name=spec.role, entrypoint=spec.entrypoint, args=args, envs=envs, log_dir=attempt_log_dir, start_method=self._start_method, redirects=spec.redirects, tee=spec.tee, ) return self._pcontext.pids() def _shutdown(self, death_sig: signal.Signals = signal.SIGTERM) -> None: if self._pcontext: self._pcontext.close(death_sig) @prof def _monitor_workers(self, worker_group: WorkerGroup) -> RunResult: role = worker_group.spec.role worker_pids = {w.id for w in worker_group.workers} assert self._pcontext is not None pc_pids = set(self._pcontext.pids().values()) if worker_pids != pc_pids: log.error( f"[{role}] worker pids do not match process_context pids." f" Expected: {worker_pids}, actual: {pc_pids}" ) return RunResult(state=WorkerState.UNKNOWN) result = self._pcontext.wait(0) if result: if result.is_failed(): # map local rank failure to global rank worker_failures = {} for local_rank, failure in result.failures.items(): worker = worker_group.workers[local_rank] worker_failures[worker.global_rank] = failure return RunResult( state=WorkerState.FAILED, failures=worker_failures, ) else: # copy ret_val_queue into a map with a global ranks workers_ret_vals = {} for local_rank, ret_val in result.return_values.items(): worker = worker_group.workers[local_rank] workers_ret_vals[worker.global_rank] = ret_val return RunResult( state=WorkerState.SUCCEEDED, return_values=workers_ret_vals, ) else: return RunResult(state=WorkerState.HEALTHY)
[]
[]
[ "OMP_NUM_THREADS" ]
[]
["OMP_NUM_THREADS"]
python
1
0
zap/config/config.py
#!/usr/bin/env python3 """ MIT License Copyright (c) 2020 Srevin Saju Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------- This file is part of Zap AppImage Package Manager """ import json import os import appdirs import click from zap.constants import ZAP_PATH_RC_PATCH, MIRRORS def does_config_exist(): cfgpath = os.path.join(appdirs.user_config_dir('zap'), 'config.json') if os.path.exists(cfgpath): return True else: return False class ConfigManager: def __init__(self): self._config_dir = appdirs.user_config_dir('zap') self._cfgpath = os.path.join(self._config_dir, 'config.json') self._config = { 'version': '0.1', 'name': 'ZapConfiguration', 'storageDirectory': appdirs.user_data_dir('zap'), 'bin': os.path.join(appdirs.user_data_dir('zap'), 'bin'), 'database': os.path.join(appdirs.user_data_dir('zap'), 'db'), 'mirror': MIRRORS.get("0")[0], 'apps': [], 'gh-token': None } if not os.path.exists(self._config_dir): self.make_config_directory() if not os.path.exists(self._cfgpath): self.write_file() self.make_data_directory() self.read_file() def __getattr__(self, item): return self._config.get(item) def __getitem__(self, item): return self._config.get(item) def __setitem__(self, key, value): self._config[key] = value self.write_file() def __repr__(self): return 'ZapConfig({})'.format(json.dumps(self._config, indent=4)) @property def local_storage(self): return self._config['storageDirectory'] @property def shell_wrappers_dir(self): return self._config.get('bin') def add_current_directory_to_path(self): if os.getenv('ZAP_PATH'): # already configured! return path_to_current_shell = os.getenv('SHELL') if path_to_current_shell: current_shell = path_to_current_shell.split(os.path.sep)[-1] print("Detected {} shell".format(current_shell)) path_to_shell_rc = os.path.join(os.path.expanduser('~'), '.{}rc'.format(current_shell)) if os.path.exists(path_to_shell_rc): with open(path_to_shell_rc, 'r') as fp: shrc_file = fp.read() if 'ZAP_PATH' in shrc_file: print("Shell is already configured to use zap! ") return print("Patching .{}rc file to include AppImage configuration" .format(current_shell)) with open(path_to_shell_rc, 'a') as fp: fp.write(ZAP_PATH_RC_PATCH.format(path_to_bin=self['bin'])) else: print("Could not find a .bashrc or .zshrc file on home " "directory. Please add the following code to your " "shell configuration to make appimages run anywhere " "on the command line") print("Code follows below: \n\n") print(ZAP_PATH_RC_PATCH.format(path_to_bin=self['bin'])) else: print("Unable to detect current shell. looks like your $SHELL " "variable is unset. Please set the $SHELL variable or add " "the following code manually to the shell configuration " "file") print(ZAP_PATH_RC_PATCH.format(path_to_bin=self['bin'])) def make_data_directory(self): data_directory = self._config.get('storageDirectory') bin_directory = os.path.join(data_directory, 'bin') db_directory = os.path.join(data_directory, 'db') if not os.path.exists(data_directory): os.makedirs(data_directory) if not os.path.exists(bin_directory): os.makedirs(bin_directory) self['bin'] = bin_directory if not os.path.exists(db_directory): os.makedirs(db_directory) self['database'] = db_directory self.add_current_directory_to_path() def make_config_directory(self): os.makedirs(self._config_dir) self.write_file() def write_file(self): with open(self._cfgpath, 'w') as w: json.dump(self._config, w, indent=4) def read_file(self): with open(self._cfgpath, 'r') as r: self._config.update(json.load(r)) def setup_config_interactive(self): print("Zap AppImage Package Manager configuration wizard") print() path_to_save_appimages = input("Please specify absolute path to " "store appimages: ") path_to_save_appimages = os.path.abspath(path_to_save_appimages) if not os.path.exists(path_to_save_appimages): print("Setting up {}".format(path_to_save_appimages)) os.makedirs(path_to_save_appimages) elif os.path.exists(path_to_save_appimages) and \ os.path.isfile(path_to_save_appimages): raise NotADirectoryError("The path you have provided is not a " "directory. Please provide a valid " "directory") self._config['storageDirectory'] = path_to_save_appimages self.write_file() print("Listing available mirrors: ") for mirror_id in MIRRORS: print("[{id}] {desc}:\t{h}".format( id=mirror_id, desc=MIRRORS[mirror_id][0], h=MIRRORS[mirror_id][1] )) mirror_selection = \ click.prompt("Select mirror:", show_choices=click.Choice(list(MIRRORS.keys()))) if mirror_selection in MIRRORS.keys(): self._config['mirror'] = MIRRORS.get(mirror_selection)[0] self.write_file() else: click.echo("Invalid selection!") print("Done!") print() print("To re-run the configuration wizard, just run") print("$ zap config -i") print() def add_app(self, data): self['apps'].append(data) self.write_file() def remove_app(self, data): self['apps'].remove(data) self.write_file()
[]
[]
[ "SHELL", "ZAP_PATH" ]
[]
["SHELL", "ZAP_PATH"]
python
2
0
trafficlightsfsm.py
import RPi.GPIO as GPIO import time import os import signal import sys class TrafficLightLEDs: RED = 9 AMBER = 10 GREEN = 11 class TrafficLightStates: INITIALIZING = 1 RED = 2 REDAMBER = 3 GREEN = 4 AMBER = 5 # Turn off all lights when user ends demo def allLightsOff(signal, frame): GPIO.output(TrafficLightLEDs.RED, False) GPIO.output(TrafficLightLEDs.AMBER, False) GPIO.output(TrafficLightLEDs.GREEN, False) GPIO.cleanup() sys.exit(0) signal.signal(signal.SIGINT, allLightsOff) currentState = TrafficLightStates.INITIALIZING while True: if (currentState == TrafficLightStates.INITIALIZING): if ('TRAFFIC_LIGHT_COUNTRY' in os.environ) and (os.environ['TRAFFIC_LIGHT_COUNTRY'] in ['UK', 'USA']): pattern = os.environ['TRAFFIC_LIGHT_COUNTRY'].lower() else: print('TRAFFIC_LIGHT_COUNTRY should be set to UK or USA') sys.exit(1) # Setup Hardware GPIO.setmode(GPIO.BCM) GPIO.setup(TrafficLightLEDs.RED, GPIO.OUT) GPIO.setup(TrafficLightLEDs.AMBER, GPIO.OUT) GPIO.setup(TrafficLightLEDs.GREEN, GPIO.OUT) currentState = TrafficLightStates.RED elif (currentState == TrafficLightStates.RED): GPIO.output(TrafficLightLEDs.RED, True) GPIO.output(TrafficLightLEDs.AMBER, False) GPIO.output(TrafficLightLEDs.GREEN, False) time.sleep(3) if pattern == 'uk': currentState = TrafficLightStates.REDAMBER else: currentState = TrafficLightStates.GREEN elif (currentState == TrafficLightStates.REDAMBER): GPIO.output(TrafficLightLEDs.RED, True) GPIO.output(TrafficLightLEDs.AMBER, True) GPIO.output(TrafficLightLEDs.GREEN, False) time.sleep(1) currentState = TrafficLightStates.GREEN elif (currentState == TrafficLightStates.GREEN): GPIO.output(TrafficLightLEDs.RED, False) GPIO.output(TrafficLightLEDs.AMBER, False) GPIO.output(TrafficLightLEDs.GREEN, True) time.sleep(5) currentState = TrafficLightStates.AMBER elif (currentState == TrafficLightStates.AMBER): GPIO.output(TrafficLightLEDs.RED, False) GPIO.output(TrafficLightLEDs.AMBER, True) GPIO.output(TrafficLightLEDs.GREEN, False) if pattern == 'uk': time.sleep(2) else: time.sleep(3) currentState = TrafficLightStates.RED else: print 'Invalid state!'
[]
[]
[ "TRAFFIC_LIGHT_COUNTRY" ]
[]
["TRAFFIC_LIGHT_COUNTRY"]
python
1
0
tools/notifications.py
#!/usr/bin/env python3 # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json import requests from pprint import pprint from requests.exceptions import URLRequired def main(): TOKEN = os.getenv('GITHUB_TOKEN') WEBHOOK = os.getenv('WEBHOOK') GITHUB_REPOSITORY = os.getenv('GITHUB_REPOSITORY') response = open_issue(GITHUB_REPOSITORY) # pprint(response.json()) try: for issue in response.json(): commentcheck = issuecommentcheck(GITHUB_REPOSITORY, issue['number']) if(commentcheck == False): if ("pull_request") in issue.keys(): print("Pull Request: "+ str(issue['number'])) header = 'Pull Request' else: print("Issue: "+ str(issue['number'])) header = 'Issue' labels = '' assignees = '' number = issue['number'] title = issue['title'] user = issue['user']['login'] url = issue['html_url'] try: for label in issue['labels']: labels = labels + label['name'] + ',' labels = labels[:-1] except: labels = '' try: for assignee in issue['assignees']: assignees = assignees + assignee['login'] + ',' assignees = assignees[:-1] except: assignees = '' # print(number) # print(title) # print(user) # print(labels) # print(assignees) # print(url) rawdata = setdata(header, str(number), title, user, labels, assignees, url) # pprint(rawdata) try: comment = sendmsg(WEBHOOK, rawdata) if(comment != ''): print('Message sent for: ' + str(issue['number']) + ' ! Commenting Issue ...') commentissue(GITHUB_REPOSITORY, issue['number'], comment, TOKEN) else: print('Message not sent for: ' + str(issue['number']) + ' ! SKIPPING Commenting Issue...') except requests.exceptions.RequestException as e: raise SystemExit(e) else: print('Notifications already sent for: #' + str(issue['number'])) except requests.exceptions.RequestException as e: print("No Issue in the repo ") raise SystemExit(e) def open_issue(GITHUB_REPOSITORY): print('Fetching open Issues...') try: response = requests.get('https://api.github.com/repos/'+ GITHUB_REPOSITORY +'/issues') return response except requests.exceptions.RequestException as e: raise SystemExit(e) def issuecommentcheck(GITHUB_REPOSITORY, number): print('Checking if the notification has already been sent...') try: status = False response = requests.get('https://api.github.com/repos/'+ GITHUB_REPOSITORY +'/issues/'+ str(number) +'/comments') for comment in response.json(): body = comment['body'] if(body.startswith('<!-- Notification Check -->')): # print(body) status = True break return status except requests.exceptions.RequestException as e: raise SystemExit(e) def setdata(header, number, title, user, labels, assignees, url): rawdata = { "cards": [ { "header": { "title": header + " Tracker", "subtitle": header + " No: #"+number }, "sections": [ { "widgets": [ { "keyValue": { "topLabel": "Creator", "content": user }, }, { "keyValue": { "topLabel": "Title", "content": title } }, { "keyValue": { "topLabel": "Assigned Lables", "content": "- " + labels } }, { "keyValue": { "topLabel": "Assignees", "content": "- " + assignees } }, { "buttons": [ { "textButton": { "text": "OPEN " + header, "onClick": { "openLink": { "url": url } } } } ] } ] } ] } ] } # print(type(rawdata)) rawdata = json.dumps(rawdata) # print(type(rawdata)) return rawdata def sendmsg(WEBHOOK, rawdata): comment = '' headers = {'Content-Type': 'application/json'} try: response = requests.post(WEBHOOK, headers=headers, data=rawdata) comment = '<!-- Notification Check -->\nThank you for raising the request! RAD Lab admins have been notified.' # print(response.text) except requests.exceptions.RequestException as e: print('ERROR: Error Occured posting a message on Webhook!') raise SystemExit(e) return comment def commentissue(GITHUB_REPOSITORY, number, comment, TOKEN): headers = {'Authorization': f'token {TOKEN}', 'Accept': 'application/vnd.github.v3+json'} # print(comment) data = {"body":comment} try: response = requests.post('https://api.github.com/repos/'+ GITHUB_REPOSITORY +'/issues/'+ str(number) +'/comments', data=json.dumps(data), headers=headers) # print(response.text) except requests.exceptions.RequestException as e: raise SystemExit(e) if __name__ == '__main__': main()
[]
[]
[ "WEBHOOK", "GITHUB_REPOSITORY", "GITHUB_TOKEN" ]
[]
["WEBHOOK", "GITHUB_REPOSITORY", "GITHUB_TOKEN"]
python
3
0
config/config.go
package config import ( "os" ) // Server configeration structure type Config struct { ServerAddress string DBUser string DBPassword string DBName string DBURI string // mongodb connection URI } // initialize will read the environment variables and store them in the config struct func (config *Config) initialize() { config.ServerAddress = ":" + os.Getenv("PORT") config.DBUser = os.Getenv("MONGODB_USER") config.DBPassword = os.Getenv("MONGODB_PASSWORD") config.DBName = os.Getenv("MONGODB_NAME") config.DBURI = os.Getenv("MONGODB_URI") } // NewConfig will initialize and return the config func NewConfig() *Config { config := new(Config) config.initialize() return config }
[ "\"PORT\"", "\"MONGODB_USER\"", "\"MONGODB_PASSWORD\"", "\"MONGODB_NAME\"", "\"MONGODB_URI\"" ]
[]
[ "PORT", "MONGODB_PASSWORD", "MONGODB_USER", "MONGODB_NAME", "MONGODB_URI" ]
[]
["PORT", "MONGODB_PASSWORD", "MONGODB_USER", "MONGODB_NAME", "MONGODB_URI"]
go
5
0
integrations/integration_test.go
// Copyright 2017 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package integrations import ( "bytes" "database/sql" "fmt" "io" "log" "net/http" "net/http/cookiejar" "net/url" "os" "strings" "testing" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/routers" "code.gitea.io/gitea/routers/routes" "github.com/Unknwon/com" "github.com/stretchr/testify/assert" "gopkg.in/macaron.v1" "gopkg.in/testfixtures.v2" ) var mac *macaron.Macaron func TestMain(m *testing.M) { initIntegrationTest() mac = routes.NewMacaron() routes.RegisterRoutes(mac) var helper testfixtures.Helper if setting.UseMySQL { helper = &testfixtures.MySQL{} } else if setting.UsePostgreSQL { helper = &testfixtures.PostgreSQL{} } else if setting.UseSQLite3 { helper = &testfixtures.SQLite{} } else { fmt.Println("Unsupported RDBMS for integration tests") os.Exit(1) } err := models.InitFixtures( helper, "models/fixtures/", ) if err != nil { fmt.Printf("Error initializing test database: %v\n", err) os.Exit(1) } os.Exit(m.Run()) } func initIntegrationTest() { if setting.CustomConf = os.Getenv("GITEA_CONF"); setting.CustomConf == "" { fmt.Println("Environment variable $GITEA_CONF not set") os.Exit(1) } if os.Getenv("GITEA_ROOT") == "" { fmt.Println("Environment variable $GITEA_ROOT not set") os.Exit(1) } setting.NewContext() models.LoadConfigs() switch { case setting.UseMySQL: db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/", models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host)) defer db.Close() if err != nil { log.Fatalf("sql.Open: %v", err) } if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS testgitea"); err != nil { log.Fatalf("db.Exec: %v", err) } case setting.UsePostgreSQL: db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s", models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host, models.DbCfg.SSLMode)) defer db.Close() if err != nil { log.Fatalf("sql.Open: %v", err) } rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", models.DbCfg.Name)) if err != nil { log.Fatalf("db.Query: %v", err) } defer rows.Close() if rows.Next() { break } if _, err = db.Exec("CREATE DATABASE testgitea"); err != nil { log.Fatalf("db.Exec: %v", err) } } routers.GlobalInit() } func prepareTestEnv(t *testing.T) { assert.NoError(t, models.LoadFixtures()) assert.NoError(t, os.RemoveAll("integrations/gitea-integration")) assert.NoError(t, com.CopyDir("integrations/gitea-integration-meta", "integrations/gitea-integration")) } type TestSession struct { jar http.CookieJar } func (s *TestSession) GetCookie(name string) *http.Cookie { baseURL, err := url.Parse(setting.AppURL) if err != nil { return nil } for _, c := range s.jar.Cookies(baseURL) { if c.Name == name { return c } } return nil } func (s *TestSession) MakeRequest(t *testing.T, req *http.Request) *TestResponse { baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } resp := MakeRequest(req) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";")) cr := http.Request{Header: ch} s.jar.SetCookies(baseURL, cr.Cookies()) return resp } func loginUser(t *testing.T, userName, password string) *TestSession { req := NewRequest(t, "GET", "/user/login") resp := MakeRequest(req) assert.EqualValues(t, http.StatusOK, resp.HeaderCode) doc, err := NewHtmlParser(resp.Body) assert.NoError(t, err) req = NewRequestBody(t, "POST", "/user/login", bytes.NewBufferString(url.Values{ "_csrf": []string{doc.GetInputValueByName("_csrf")}, "user_name": []string{userName}, "password": []string{password}, }.Encode()), ) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp = MakeRequest(req) assert.EqualValues(t, http.StatusFound, resp.HeaderCode) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";")) cr := http.Request{Header: ch} jar, err := cookiejar.New(nil) assert.NoError(t, err) baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) jar.SetCookies(baseURL, cr.Cookies()) return &TestSession{jar: jar} } type TestResponseWriter struct { HeaderCode int Writer io.Writer Headers http.Header } func (w *TestResponseWriter) Header() http.Header { return w.Headers } func (w *TestResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) } func (w *TestResponseWriter) WriteHeader(n int) { w.HeaderCode = n } type TestResponse struct { HeaderCode int Body []byte Headers http.Header } func NewRequest(t *testing.T, method, url string) *http.Request { return NewRequestBody(t, method, url, nil) } func NewRequestBody(t *testing.T, method, url string, body io.Reader) *http.Request { request, err := http.NewRequest(method, url, body) assert.NoError(t, err) request.RequestURI = url return request } func MakeRequest(req *http.Request) *TestResponse { buffer := bytes.NewBuffer(nil) respWriter := &TestResponseWriter{ Writer: buffer, Headers: make(map[string][]string), } mac.ServeHTTP(respWriter, req) return &TestResponse{ HeaderCode: respWriter.HeaderCode, Body: buffer.Bytes(), Headers: respWriter.Headers, } }
[ "\"GITEA_CONF\"", "\"GITEA_ROOT\"" ]
[]
[ "GITEA_ROOT", "GITEA_CONF" ]
[]
["GITEA_ROOT", "GITEA_CONF"]
go
2
0
main.go
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" ) func main() { if len(os.Args) != 2 { fmt.Printf("Error: You must provide the word whose definition you wish to retrieve.\n") os.Exit(1) } word := os.Args[1] url := fmt.Sprintf("https://od-api.oxforddictionaries.com/api/v2/entries/en/%s", word) client := &http.Client{} request, err := http.NewRequest( http.MethodGet, url, nil, ) request.Header.Add("Content-Type", "application/json") request.Header.Add("app_id", os.Getenv("ODICTAPIID")) request.Header.Add("app_key", os.Getenv("ODICTAPIKEY")) resp, err := client.Do(request) if err != nil { fmt.Printf("%v\n", err) } defer resp.Body.Close() code := resp.StatusCode bytes, err := ioutil.ReadAll(resp.Body) dictResp := &DictResponse{} json.Unmarshal(bytes, dictResp) header := ` =================================================== | + | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | =================================================== ` fmt.Printf(header) if code == 404 { fmt.Printf("Unable to find %s\n", word) os.Exit(1) } entries := dictResp.Results[0].LexicalEntries[0].Entries if len(entries) <= 0 { fmt.Printf("No entries found.\n") os.Exit(0) } senses := entries[0].Senses if len(senses) <= 0 { fmt.Printf("No definitions for %s\n", word) os.Exit(0) } definitions := senses[0].Definitions if len(definitions) <= 0 { fmt.Printf("No definitions for %s\n", word) os.Exit(0) } fmt.Printf("Word:\n\t%s\n\n", word) fmt.Printf("Definition:\n\t%s\n\n", definitions[0]) // Print all of the other definitions. if len(senses[0].Subsenses) > 0 { fmt.Printf("Other Meanings:\n") for index, item := range senses[0].Subsenses { fmt.Printf("\t%d. %s\n", index+1, item.Definitions[0]) } } }
[ "\"ODICTAPIID\"", "\"ODICTAPIKEY\"" ]
[]
[ "ODICTAPIID", "ODICTAPIKEY" ]
[]
["ODICTAPIID", "ODICTAPIKEY"]
go
2
0
api4/system_test.go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package api4 import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strconv" "strings" "testing" "time" "github.com/adacta-ru/mattermost-server/v6/mlog" "github.com/adacta-ru/mattermost-server/v6/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetPing(t *testing.T) { th := Setup(t) defer th.TearDown() th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { t.Run("healthy", func(t *testing.T) { status, resp := client.GetPing() CheckNoError(t, resp) assert.Equal(t, model.STATUS_OK, status) }) t.Run("unhealthy", func(t *testing.T) { goRoutineHealthThreshold := *th.App.Config().ServiceSettings.GoroutineHealthThreshold defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = goRoutineHealthThreshold }) }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = 10 }) status, resp := client.GetPing() CheckInternalErrorStatus(t, resp) assert.Equal(t, model.STATUS_UNHEALTHY, status) }) }, "basic ping") th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { t.Run("healthy", func(t *testing.T) { status, resp := client.GetPingWithServerStatus() CheckNoError(t, resp) assert.Equal(t, model.STATUS_OK, status) }) t.Run("unhealthy", func(t *testing.T) { oldDriver := th.App.Config().FileSettings.DriverName badDriver := "badDriverName" th.App.Config().FileSettings.DriverName = &badDriver defer func() { th.App.Config().FileSettings.DriverName = oldDriver }() status, resp := client.GetPingWithServerStatus() CheckInternalErrorStatus(t, resp) assert.Equal(t, model.STATUS_UNHEALTHY, status) }) }, "with server status") th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { th.App.ReloadConfig() resp, appErr := client.DoApiGet(client.GetSystemRoute()+"/ping", "") require.Nil(t, appErr) require.Equal(t, http.StatusOK, resp.StatusCode) respBytes, err := ioutil.ReadAll(resp.Body) require.Nil(t, err) respString := string(respBytes) require.NotContains(t, respString, "TestFeatureFlag") // Run the environment variable override code to test os.Setenv("MM_FEATUREFLAGS_TESTFEATURE", "testvalueunique") defer os.Unsetenv("MM_FEATUREFLAGS_TESTFEATURE") th.App.ReloadConfig() resp, appErr = client.DoApiGet(client.GetSystemRoute()+"/ping", "") require.Nil(t, appErr) require.Equal(t, http.StatusOK, resp.StatusCode) respBytes, err = ioutil.ReadAll(resp.Body) require.Nil(t, err) respString = string(respBytes) require.Contains(t, respString, "testvalue") }, "ping feature flag test") } func TestGetAudits(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client audits, resp := th.SystemAdminClient.GetAudits(0, 100, "") CheckNoError(t, resp) require.NotEmpty(t, audits, "should not be empty") audits, resp = th.SystemAdminClient.GetAudits(0, 1, "") CheckNoError(t, resp) require.Len(t, audits, 1, "should only be 1") audits, resp = th.SystemAdminClient.GetAudits(1, 1, "") CheckNoError(t, resp) require.Len(t, audits, 1, "should only be 1") _, resp = th.SystemAdminClient.GetAudits(-1, -1, "") CheckNoError(t, resp) _, resp = Client.GetAudits(0, 100, "") CheckForbiddenStatus(t, resp) Client.Logout() _, resp = Client.GetAudits(0, 100, "") CheckUnauthorizedStatus(t, resp) } func TestEmailTest(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client dir, err := ioutil.TempDir("", "") require.NoError(t, err) defer os.RemoveAll(dir) config := model.Config{ ServiceSettings: model.ServiceSettings{ SiteURL: model.NewString(""), }, EmailSettings: model.EmailSettings{ SMTPServer: model.NewString(""), SMTPPort: model.NewString(""), SMTPPassword: model.NewString(""), FeedbackName: model.NewString(""), FeedbackEmail: model.NewString("[email protected]"), ReplyToAddress: model.NewString("[email protected]"), ConnectionSecurity: model.NewString(""), SMTPUsername: model.NewString(""), EnableSMTPAuth: model.NewBool(false), SkipServerCertificateVerification: model.NewBool(true), SendEmailNotifications: model.NewBool(false), SMTPServerTimeout: model.NewInt(15), }, FileSettings: model.FileSettings{ DriverName: model.NewString(model.IMAGE_DRIVER_LOCAL), Directory: model.NewString(dir), }, } t.Run("as system user", func(t *testing.T) { _, resp := Client.TestEmail(&config) CheckForbiddenStatus(t, resp) }) t.Run("as system admin", func(t *testing.T) { _, resp := th.SystemAdminClient.TestEmail(&config) CheckErrorMessage(t, resp, "api.admin.test_email.missing_server") CheckBadRequestStatus(t, resp) inbucket_host := os.Getenv("CI_INBUCKET_HOST") if inbucket_host == "" { inbucket_host = "localhost" } inbucket_port := os.Getenv("CI_INBUCKET_SMTP_PORT") if inbucket_port == "" { inbucket_port = "10025" } *config.EmailSettings.SMTPServer = inbucket_host *config.EmailSettings.SMTPPort = inbucket_port _, resp = th.SystemAdminClient.TestEmail(&config) CheckOKStatus(t, resp) }) t.Run("as restricted system admin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) _, resp := th.SystemAdminClient.TestEmail(&config) CheckForbiddenStatus(t, resp) }) } func TestSiteURLTest(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/valid/api/v4/system/ping") { w.WriteHeader(200) } else { w.WriteHeader(400) } })) defer ts.Close() validSiteURL := ts.URL + "/valid" invalidSiteURL := ts.URL + "/invalid" t.Run("as system admin", func(t *testing.T) { _, resp := th.SystemAdminClient.TestSiteURL("") CheckBadRequestStatus(t, resp) _, resp = th.SystemAdminClient.TestSiteURL(invalidSiteURL) CheckBadRequestStatus(t, resp) _, resp = th.SystemAdminClient.TestSiteURL(validSiteURL) CheckOKStatus(t, resp) }) t.Run("as system user", func(t *testing.T) { _, resp := Client.TestSiteURL(validSiteURL) CheckForbiddenStatus(t, resp) }) t.Run("as restricted system admin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) _, resp := Client.TestSiteURL(validSiteURL) CheckForbiddenStatus(t, resp) }) } func TestDatabaseRecycle(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client t.Run("as system user", func(t *testing.T) { _, resp := Client.DatabaseRecycle() CheckForbiddenStatus(t, resp) }) t.Run("as system admin", func(t *testing.T) { _, resp := th.SystemAdminClient.DatabaseRecycle() CheckNoError(t, resp) }) t.Run("as restricted system admin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) _, resp := th.SystemAdminClient.DatabaseRecycle() CheckForbiddenStatus(t, resp) }) } func TestInvalidateCaches(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client t.Run("as system user", func(t *testing.T) { ok, resp := Client.InvalidateCaches() CheckForbiddenStatus(t, resp) require.False(t, ok, "should not clean the cache due to no permission.") }) t.Run("as system admin", func(t *testing.T) { ok, resp := th.SystemAdminClient.InvalidateCaches() CheckNoError(t, resp) require.True(t, ok, "should clean the cache") }) t.Run("as restricted system admin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) ok, resp := th.SystemAdminClient.InvalidateCaches() CheckForbiddenStatus(t, resp) require.False(t, ok, "should not clean the cache due to no permission.") }) } func TestGetLogs(t *testing.T) { th := Setup(t) defer th.TearDown() for i := 0; i < 20; i++ { mlog.Info(strconv.Itoa(i)) } th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { logs, resp := c.GetLogs(0, 10) CheckNoError(t, resp) require.Len(t, logs, 10) for i := 10; i < 20; i++ { assert.Containsf(t, logs[i-10], fmt.Sprintf(`"msg":"%d"`, i), "Log line doesn't contain correct message") } logs, resp = c.GetLogs(1, 10) CheckNoError(t, resp) require.Len(t, logs, 10) logs, resp = c.GetLogs(-1, -1) CheckNoError(t, resp) require.NotEmpty(t, logs, "should not be empty") }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) _, resp := th.Client.GetLogs(0, 10) CheckForbiddenStatus(t, resp) }) _, resp := th.Client.GetLogs(0, 10) CheckForbiddenStatus(t, resp) th.Client.Logout() _, resp = th.Client.GetLogs(0, 10) CheckUnauthorizedStatus(t, resp) } func TestPostLog(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client enableDev := *th.App.Config().ServiceSettings.EnableDeveloper defer func() { *th.App.Config().ServiceSettings.EnableDeveloper = enableDev }() *th.App.Config().ServiceSettings.EnableDeveloper = true message := make(map[string]string) message["level"] = "ERROR" message["message"] = "this is a test" _, resp := Client.PostLog(message) CheckNoError(t, resp) *th.App.Config().ServiceSettings.EnableDeveloper = false _, resp = Client.PostLog(message) CheckNoError(t, resp) *th.App.Config().ServiceSettings.EnableDeveloper = true Client.Logout() _, resp = Client.PostLog(message) CheckNoError(t, resp) *th.App.Config().ServiceSettings.EnableDeveloper = false _, resp = Client.PostLog(message) CheckForbiddenStatus(t, resp) logMessage, resp := th.SystemAdminClient.PostLog(message) CheckNoError(t, resp) require.NotEmpty(t, logMessage, "should return the log message") } func TestGetAnalyticsOld(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() Client := th.Client rows, resp := Client.GetAnalyticsOld("", "") CheckForbiddenStatus(t, resp) require.Nil(t, rows, "should be nil") rows, resp = th.SystemAdminClient.GetAnalyticsOld("", "") CheckNoError(t, resp) found := false found2 := false for _, row := range rows { if row.Name == "unique_user_count" { found = true } else if row.Name == "inactive_user_count" { found2 = true assert.True(t, row.Value >= 0) } } assert.True(t, found, "should return unique user count") assert.True(t, found2, "should return inactive user count") _, resp = th.SystemAdminClient.GetAnalyticsOld("post_counts_day", "") CheckNoError(t, resp) _, resp = th.SystemAdminClient.GetAnalyticsOld("user_counts_with_posts_day", "") CheckNoError(t, resp) _, resp = th.SystemAdminClient.GetAnalyticsOld("extra_counts", "") CheckNoError(t, resp) rows, resp = th.SystemAdminClient.GetAnalyticsOld("", th.BasicTeam.Id) CheckNoError(t, resp) for _, row := range rows { if row.Name == "inactive_user_count" { assert.Equal(t, float64(-1), row.Value, "inactive user count should be -1 when team specified") } } rows2, resp2 := th.SystemAdminClient.GetAnalyticsOld("standard", "") CheckNoError(t, resp2) assert.Equal(t, "total_websocket_connections", rows2[5].Name) assert.Equal(t, float64(0), rows2[5].Value) WebSocketClient, err := th.CreateWebSocketClient() require.Nil(t, err) time.Sleep(100 * time.Millisecond) rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "") CheckNoError(t, resp2) assert.Equal(t, "total_websocket_connections", rows2[5].Name) assert.Equal(t, float64(1), rows2[5].Value) WebSocketClient.Close() rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "") CheckNoError(t, resp2) assert.Equal(t, "total_websocket_connections", rows2[5].Name) assert.Equal(t, float64(0), rows2[5].Value) Client.Logout() _, resp = Client.GetAnalyticsOld("", th.BasicTeam.Id) CheckUnauthorizedStatus(t, resp) } func TestS3TestConnection(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client s3Host := os.Getenv("CI_MINIO_HOST") if s3Host == "" { s3Host = "localhost" } s3Port := os.Getenv("CI_MINIO_PORT") if s3Port == "" { s3Port = "9000" } s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port) config := model.Config{ FileSettings: model.FileSettings{ DriverName: model.NewString(model.IMAGE_DRIVER_S3), AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY), AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY), AmazonS3Bucket: model.NewString(""), AmazonS3Endpoint: model.NewString(s3Endpoint), AmazonS3Region: model.NewString(""), AmazonS3PathPrefix: model.NewString(""), AmazonS3SSL: model.NewBool(false), }, } t.Run("as system user", func(t *testing.T) { _, resp := Client.TestS3Connection(&config) CheckForbiddenStatus(t, resp) }) t.Run("as system admin", func(t *testing.T) { _, resp := th.SystemAdminClient.TestS3Connection(&config) CheckBadRequestStatus(t, resp) require.Equal(t, resp.Error.Message, "S3 Bucket is required", "should return error - missing s3 bucket") // If this fails, check the test configuration to ensure minio is setup with the // `mattermost-test` bucket defined by model.MINIO_BUCKET. *config.FileSettings.AmazonS3Bucket = model.MINIO_BUCKET config.FileSettings.AmazonS3PathPrefix = model.NewString("") *config.FileSettings.AmazonS3Region = "us-east-1" _, resp = th.SystemAdminClient.TestS3Connection(&config) CheckOKStatus(t, resp) config.FileSettings.AmazonS3Region = model.NewString("") _, resp = th.SystemAdminClient.TestS3Connection(&config) CheckOKStatus(t, resp) config.FileSettings.AmazonS3Bucket = model.NewString("Wrong_bucket") _, resp = th.SystemAdminClient.TestS3Connection(&config) CheckInternalErrorStatus(t, resp) assert.Equal(t, "api.file.test_connection.app_error", resp.Error.Id) *config.FileSettings.AmazonS3Bucket = "shouldcreatenewbucket" _, resp = th.SystemAdminClient.TestS3Connection(&config) CheckOKStatus(t, resp) }) t.Run("as restricted system admin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true }) _, resp := th.SystemAdminClient.TestS3Connection(&config) CheckForbiddenStatus(t, resp) }) } func TestSupportedTimezones(t *testing.T) { th := Setup(t) defer th.TearDown() Client := th.Client supportedTimezonesFromConfig := th.App.Timezones().GetSupported() supportedTimezones, resp := Client.GetSupportedTimezone() CheckNoError(t, resp) assert.Equal(t, supportedTimezonesFromConfig, supportedTimezones) } func TestRedirectLocation(t *testing.T) { expected := "https://mattermost.com/wp-content/themes/mattermostv2/img/logo-light.svg" testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.Header().Set("Location", expected) res.WriteHeader(http.StatusFound) res.Write([]byte("body")) })) defer func() { testServer.Close() }() mockBitlyLink := testServer.URL th := Setup(t) defer th.TearDown() Client := th.Client enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews }) }() *th.App.Config().ServiceSettings.EnableLinkPreviews = true *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections = "127.0.0.1" _, resp := th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "") CheckNoError(t, resp) _, resp = th.SystemAdminClient.GetRedirectLocation("", "") CheckBadRequestStatus(t, resp) actual, resp := th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "") CheckNoError(t, resp) assert.Equal(t, expected, actual) // Check cached value actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "") CheckNoError(t, resp) assert.Equal(t, expected, actual) *th.App.Config().ServiceSettings.EnableLinkPreviews = false actual, resp = th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "") CheckNoError(t, resp) assert.Equal(t, actual, "") actual, resp = th.SystemAdminClient.GetRedirectLocation("", "") CheckNoError(t, resp) assert.Equal(t, actual, "") actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "") CheckNoError(t, resp) assert.Equal(t, actual, "") Client.Logout() _, resp = Client.GetRedirectLocation("", "") CheckUnauthorizedStatus(t, resp) } func TestSetServerBusy(t *testing.T) { th := Setup(t) defer th.TearDown() const secs = 30 t.Run("as system user", func(t *testing.T) { ok, resp := th.Client.SetServerBusy(secs) CheckForbiddenStatus(t, resp) require.False(t, ok, "should not set server busy due to no permission") require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { ok, resp := c.SetServerBusy(secs) CheckNoError(t, resp) require.True(t, ok, "should set server busy successfully") require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") }, "as system admin") } func TestSetServerBusyInvalidParam(t *testing.T) { th := Setup(t) defer th.TearDown() th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { params := []int{-1, 0, MAX_SERVER_BUSY_SECONDS + 1} for _, p := range params { ok, resp := c.SetServerBusy(p) CheckBadRequestStatus(t, resp) require.False(t, ok, "should not set server busy due to invalid param ", p) require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy due to invalid param ", p) } }, "as system admin, invalid param") } func TestClearServerBusy(t *testing.T) { th := Setup(t) defer th.TearDown() th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { ok, resp := th.Client.ClearServerBusy() CheckForbiddenStatus(t, resp) require.False(t, ok, "should not clear server busy flag due to no permission.") require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") }) th.App.Srv().Busy.Set(time.Second * 30) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { ok, resp := c.ClearServerBusy() CheckNoError(t, resp) require.True(t, ok, "should clear server busy flag successfully") require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") }, "as system admin") } func TestGetServerBusy(t *testing.T) { th := Setup(t) defer th.TearDown() th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { _, resp := th.Client.GetServerBusy() CheckForbiddenStatus(t, resp) }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { sbs, resp := c.GetServerBusy() expires := time.Unix(sbs.Expires, 0) CheckNoError(t, resp) require.Greater(t, expires.Unix(), time.Now().Unix()) }, "as system admin") } func TestGetServerBusyExpires(t *testing.T) { th := Setup(t) defer th.TearDown() th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { _, resp := th.Client.GetServerBusyExpires() CheckForbiddenStatus(t, resp) }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { expires, resp := c.GetServerBusyExpires() CheckNoError(t, resp) require.Greater(t, expires.Unix(), time.Now().Unix()) }, "as system admin") } func TestServerBusy503(t *testing.T) { th := Setup(t) defer th.TearDown() th.App.Srv().Busy.Set(time.Second * 30) t.Run("search users while busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} _, resp := th.SystemAdminClient.SearchUsers(us) CheckServiceUnavailableStatus(t, resp) }) t.Run("search teams while busy", func(t *testing.T) { ts := &model.TeamSearch{} _, resp := th.SystemAdminClient.SearchTeams(ts) CheckServiceUnavailableStatus(t, resp) }) t.Run("search channels while busy", func(t *testing.T) { cs := &model.ChannelSearch{} _, resp := th.SystemAdminClient.SearchChannels("foo", cs) CheckServiceUnavailableStatus(t, resp) }) t.Run("search archived channels while busy", func(t *testing.T) { cs := &model.ChannelSearch{} _, resp := th.SystemAdminClient.SearchArchivedChannels("foo", cs) CheckServiceUnavailableStatus(t, resp) }) th.App.Srv().Busy.Clear() t.Run("search users while not busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} _, resp := th.SystemAdminClient.SearchUsers(us) CheckNoError(t, resp) }) } func TestPushNotificationAck(t *testing.T) { th := Setup(t) api := Init(th.Server, th.Server.AppOptions, th.Server.Router) session, _ := th.App.GetSession(th.Client.AuthToken) defer th.TearDown() t.Run("should return error when the ack body is not passed", func(t *testing.T) { handler := api.ApiHandler(pushNotificationAck) resp := httptest.NewRecorder() req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) req.Header.Set(model.HEADER_AUTH, "Bearer "+session.Token) handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusBadRequest, resp.Code) assert.NotNil(t, resp.Body) }) }
[ "\"CI_INBUCKET_HOST\"", "\"CI_INBUCKET_SMTP_PORT\"", "\"CI_MINIO_HOST\"", "\"CI_MINIO_PORT\"" ]
[]
[ "CI_MINIO_PORT", "CI_INBUCKET_SMTP_PORT", "CI_MINIO_HOST", "CI_INBUCKET_HOST" ]
[]
["CI_MINIO_PORT", "CI_INBUCKET_SMTP_PORT", "CI_MINIO_HOST", "CI_INBUCKET_HOST"]
go
4
0
master/test/testutils/fixtures.go
//go:build integration // +build integration package testutils import ( "context" "fmt" "os" "strconv" "time" "github.com/jackc/pgconn" "github.com/pkg/errors" "github.com/determined-ai/determined/master/internal/config" "github.com/determined-ai/determined/master/internal/elastic" "github.com/determined-ai/determined/master/pkg/model" "github.com/sirupsen/logrus" "github.com/ghodss/yaml" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "github.com/determined-ai/determined/master/internal" "github.com/determined-ai/determined/master/pkg/check" "github.com/determined-ai/determined/master/pkg/logger" "github.com/determined-ai/determined/master/version" "github.com/determined-ai/determined/proto/pkg/apiv1" ) const ( defaultUsername = "determined" defaultMasterConfig = ` checkpoint_storage: type: shared_fs host_path: /tmp resource_manager: type: agent db: user: postgres password: postgres name: determined migrations: file://../../../static/migrations root: ../../.. ` ) // ResolveElastic resolves a connection to an elasticsearch database. To debug tests that use this // (or otherwise run the tests outside of the Makefile), make sure to set DET_INTEGRATION_ES_HOST and // DET_INTEGRATION_ES_PORT. func ResolveElastic() (*elastic.Elastic, error) { es, err := elastic.Setup(*DefaultElasticConfig().ElasticLoggingConfig) if err != nil { return nil, fmt.Errorf("failed to connect to elasticsearch: %w", err) } return es, nil } // RunMaster runs a master in a goroutine and returns a reference to the master, // along with all the external context required to interact with the master, and // a function to close it. func RunMaster(ctx context.Context, c *config.Config) ( *internal.Master, *logger.LogBuffer, apiv1.DeterminedClient, context.Context, error, ) { if c == nil { dConf, err := DefaultMasterConfig() if err != nil { return nil, nil, nil, nil, err } c = dConf } logs := logger.NewLogBuffer(100) m := internal.New(version.Version, logs, c) logrus.AddHook(logs) go func() { err := m.Run(ctx) switch { case err == context.Canceled: fmt.Println("master stopped") case err != nil: fmt.Println("error running master: ", err) } }() cl, err := ConnectMaster(c) if err != nil { return nil, nil, nil, nil, err } creds, err := APICredentials(context.Background(), cl) if err != nil { return nil, nil, nil, nil, err } return m, logs, cl, creds, nil } // ConnectMaster blocks until a connection can be made to this master, assumed to be running // on localhost on the port indicated by the configuration. Returns an error if unable to connect // after 5 tries with 100ms delay between each. func ConnectMaster(c *config.Config) (apiv1.DeterminedClient, error) { var cl apiv1.DeterminedClient var clConn *grpc.ClientConn var err error for i := 0; i < 15; i++ { clConn, err = grpc.Dial(fmt.Sprintf("localhost:%d", c.Port), grpc.WithInsecure()) if err != nil { err = fmt.Errorf("failed to dial master: %w", err) continue } cl = apiv1.NewDeterminedClient(clConn) _, err = cl.Login(context.Background(), &apiv1.LoginRequest{Username: defaultUsername}) if err == nil { return cl, nil } time.Sleep(time.Second) } return nil, fmt.Errorf("failed to connect to master: %w", err) } // DefaultMasterConfig returns the default master configuration. func DefaultMasterConfig() (*config.Config, error) { c := config.DefaultConfig() if err := yaml.Unmarshal([]byte(defaultMasterConfig), c, yaml.DisallowUnknownFields); err != nil { return nil, err } pgCfg, err := pgconn.ParseConfig(os.Getenv("DET_INTEGRATION_POSTGRES_URL")) if err != nil { return nil, errors.Wrap(err, "failed to parse database string") } c.DB.Host = pgCfg.Host c.DB.Port = strconv.Itoa(int(pgCfg.Port)) c.DB.User = pgCfg.User c.DB.Password = pgCfg.Password c.DB.Name = pgCfg.Database if err := c.Resolve(); err != nil { return nil, err } if err := check.Validate(c); err != nil { return nil, err } return c, nil } func DefaultElasticConfig() model.LoggingConfig { port, err := strconv.Atoi(os.Getenv("DET_INTEGRATION_ES_PORT")) if err != nil { panic("elastic config had non-numeric port") } return model.LoggingConfig{ ElasticLoggingConfig: &model.ElasticLoggingConfig{ Host: os.Getenv("DET_INTEGRATION_ES_HOST"), Port: port, }, } } // CurrentLogstashElasticIndex returns the current active trial log index. func CurrentLogstashElasticIndex() string { return elastic.CurrentLogstashIndex() } // APICredentials takes a context and a connected apiv1.DeterminedClient and returns a context // with credentials or an error if unable to login with defaults. func APICredentials(ctx context.Context, cl apiv1.DeterminedClient) (context.Context, error) { resp, err := cl.Login(context.TODO(), &apiv1.LoginRequest{Username: defaultUsername}) if err != nil { return nil, fmt.Errorf("failed to login: %w", err) } return metadata.AppendToOutgoingContext( ctx, "x-user-token", fmt.Sprintf("Bearer %s", resp.Token)), nil }
[ "\"DET_INTEGRATION_POSTGRES_URL\"", "\"DET_INTEGRATION_ES_PORT\"", "\"DET_INTEGRATION_ES_HOST\"" ]
[]
[ "DET_INTEGRATION_POSTGRES_URL", "DET_INTEGRATION_ES_HOST", "DET_INTEGRATION_ES_PORT" ]
[]
["DET_INTEGRATION_POSTGRES_URL", "DET_INTEGRATION_ES_HOST", "DET_INTEGRATION_ES_PORT"]
go
3
0
main.py
from model import * from data import * from keras.preprocessing.image import ImageDataGenerator os.environ["CUDA_VISIBLE_DEVICES"] = "1" data_gen_args = dict(rotation_range=0.2, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, horizontal_flip=True, fill_mode='nearest') myGene = trainGenerator(2,'data/membrane/train','image','label',data_gen_args,save_to_dir = None) model = unet() model_checkpoint = ModelCheckpoint('unet_membrane.hdf5', monitor='loss',verbose=1, save_best_only=True) model.fit_generator(myGene,steps_per_epoch=300,epochs=1,callbacks=[model_checkpoint]) # test_dir = "data/membrane/test" # test_datagen = ImageDataGenerator(rescale=1./255) # test_generator = test_datagen.flow_from_directory( # test_dir, # target_size=(256, 256), # color_mode="grayscale", # batch_size=1) # test_path = "data/membrane/test" # image_datagen = ImageDataGenerator(**data_gen_args) # image_generator = image_datagen.flow_from_directory( # test_path, # class_mode = None, # color_mode = "grayscale", # target_size = (256,256), # batch_size = 1, # save_to_dir = None, # seed = 2) # filenames = test_generator.filenames # nb_samples = len(filenames) # print(nb_samples) # predict = model.predict_generator(test_generator,steps = nb_samples) # testGene = testGenerator("data/membrane/test") # filenames = testGene.filenames # nb_samples = len(filenames) # results = model.predict_generator(testGene,30,verbose=1) # saveResult("data/membrane/test",results) test_path = "data/membrane/test" target_size = (256,256) flag_multi_class = False img = io.imread(os.path.join(test_path,"%d.png"%30),as_gray = True) img = img / 255 img = trans.resize(img,target_size) img = np.reshape(img,img.shape+(1,)) if (not flag_multi_class) else img img = np.reshape(img,(1,)+img.shape) results = model.predict(img) print(results) COLOR_DICT = np.array([Sky, Building, Pole, Road, Pavement, Tree, SignSymbol, Fence, Car, Pedestrian, Bicyclist, Unlabelled]) saveResult("data/membrane/test",results) #io.imsave(os.path.join(save_path,"%d_predict.png"%31),results) # testGene = testGenerator("data/membrane/test") # results = model.predict_generator(testGene,31) # saveResult("data/membrane/test",results)
[]
[]
[ "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_VISIBLE_DEVICES"]
python
1
0
config/bosh_path_test.go
package config_test import ( "io/ioutil" "os" "path/filepath" "github.com/cloudfoundry/bosh-bootloader/config" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) var _ = Describe("GetBOSHPath", func() { var ( originalPath string pathToBOSH string ) BeforeEach(func() { originalPath = os.Getenv("PATH") tempDir, err := ioutil.TempDir("", "") Expect(err).NotTo(HaveOccurred()) pathToBOSH = filepath.Join(tempDir, "bosh") err = ioutil.WriteFile(pathToBOSH, []byte("fake"), os.ModePerm) Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { os.Setenv("PATH", originalPath) gexec.CleanupBuildArtifacts() }) Context("when a user has bosh", func() { It("returns bosh", func() { os.Setenv("PATH", filepath.Dir(pathToBOSH)) boshPath, err := config.GetBOSHPath() Expect(boshPath).To(Equal("bosh")) Expect(err).NotTo(HaveOccurred()) }) }) Context("when a user has bosh2", func() { var pathToBOSH2 string BeforeEach(func() { pathToBOSH2 = filepath.Join(filepath.Dir(pathToBOSH), "bosh2") err := os.Rename(pathToBOSH, pathToBOSH2) Expect(err).NotTo(HaveOccurred()) err = os.Setenv("PATH", filepath.Dir(pathToBOSH2)) Expect(err).NotTo(HaveOccurred()) }) It("returns bosh2", func() { boshPath, err := config.GetBOSHPath() Expect(boshPath).To(Equal(pathToBOSH2)) Expect(err).NotTo(HaveOccurred()) }) }) })
[ "\"PATH\"" ]
[]
[ "PATH" ]
[]
["PATH"]
go
1
0
utils/SwiftBuildSupport.py
# utils/SwiftBuildSupport.py - Utilities for Swift build scripts -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors from __future__ import print_function try: # Python 2 import ConfigParser except ImportError: # Python 3 import configparser as ConfigParser import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), 'swift_build_support')) # E402 means module level import not at top of file from swift_build_support import diagnostics # noqa (E402) HOME = os.environ.get("HOME", "/") def _get_default_source_root(): result = "" # Are we in a Swift checkout? Start from this file and check its parent # directories. # # $SWIFT_SOURCE_ROOT/swift/utils/SwiftBuildSupport.py (swift_path, parent_dirname) = os.path.split(os.path.dirname(__file__)) if parent_dirname != "utils": return result if not os.path.exists(os.path.join(swift_path, 'CMakeLists.txt')): return result result = os.path.dirname(swift_path) # Are we in an LLVM checkout? Start from the Swift checkout and check /its/ # parent directories. # # $SWIFT_SOURCE_ROOT/llvm/tools/swift/utils/SwiftBuildSupport.py (llvm_path, parent_dirname) = os.path.split(result) if parent_dirname != "tools": return result if not os.path.exists(os.path.join(llvm_path, 'CMakeLists.txt')): return result result = os.path.dirname(llvm_path) return result # Set SWIFT_SOURCE_ROOT in your environment to control where the sources # are found. SWIFT_SOURCE_ROOT = os.environ.get( "SWIFT_SOURCE_ROOT", _get_default_source_root()) # Set SWIFT_BUILD_ROOT to a directory that will contain a subdirectory # for each build configuration SWIFT_BUILD_ROOT = os.environ.get( "SWIFT_BUILD_ROOT", os.path.join(SWIFT_SOURCE_ROOT, "build")) def _load_preset_files_impl(preset_file_names, substitutions={}): config = ConfigParser.SafeConfigParser(substitutions, allow_no_value=True) if config.read(preset_file_names) == []: diagnostics.fatal( "preset file not found (tried " + str(preset_file_names) + ")") return config _PRESET_PREFIX = "preset: " def _get_preset_options_impl(config, substitutions, preset_name): section_name = _PRESET_PREFIX + preset_name if section_name not in config.sections(): return (None, None, None) build_script_opts = [] build_script_impl_opts = [] missing_opts = [] dash_dash_seen = False for o in config.options(section_name): try: a = config.get(section_name, o) except ConfigParser.InterpolationMissingOptionError as e: # e.reference contains the correctly formatted option missing_opts.append(e.reference) continue if not a: a = "" if o in substitutions: continue opt = None if o == "mixin-preset": # Split on newlines and filter out empty lines. mixins = filter(None, [m.strip() for m in a.splitlines()]) for mixin in mixins: (base_build_script_opts, base_build_script_impl_opts, base_missing_opts) = \ _get_preset_options_impl(config, substitutions, mixin) build_script_opts += base_build_script_opts build_script_impl_opts += base_build_script_impl_opts missing_opts += base_missing_opts elif o == "dash-dash": dash_dash_seen = True elif a == "": opt = "--" + o else: opt = "--" + o + "=" + a if opt: if not dash_dash_seen: build_script_opts.append(opt) else: build_script_impl_opts.append(opt) return (build_script_opts, build_script_impl_opts, missing_opts) def get_preset_options(substitutions, preset_file_names, preset_name): config = _load_preset_files_impl(preset_file_names, substitutions) (build_script_opts, build_script_impl_opts, missing_opts) = \ _get_preset_options_impl(config, substitutions, preset_name) if not build_script_opts and not build_script_impl_opts: diagnostics.fatal("preset '" + preset_name + "' not found") if missing_opts: diagnostics.fatal("missing option(s) for preset '" + preset_name + "': " + ", ".join(missing_opts)) # Migrate 'swift-sdks' parameter to 'stdlib-deployment-targets' swift_sdks_opts = [opt for opt in build_script_impl_opts if opt.startswith("--swift-sdks")] try: swift_sdks_opt = swift_sdks_opts[-1] except IndexError: swift_sdks_opt = None if swift_sdks_opt is not None: sdks_to_configure = swift_sdks_opt.split("=")[1].split(";") tgts = [] # Expand SDKs in to their deployment targets from swift_build_support.targets import StdlibDeploymentTarget for sdk in sdks_to_configure: if sdk == "OSX": tgts += StdlibDeploymentTarget.OSX.targets elif sdk == "IOS": tgts += StdlibDeploymentTarget.iOS.targets elif sdk == "IOS_SIMULATOR": tgts += StdlibDeploymentTarget.iOSSimulator.targets elif sdk == "TVOS": tgts += StdlibDeploymentTarget.AppleTV.targets elif sdk == "TVOS_SIMULATOR": tgts += StdlibDeploymentTarget.AppleTVSimulator.targets elif sdk == "WATCHOS": tgts += StdlibDeploymentTarget.AppleWatch.targets elif sdk == "WATCHOS_SIMULATOR": tgts += StdlibDeploymentTarget.AppleWatchSimulator.targets build_script_opts.append("--stdlib-deployment-targets=" + " ".join([tgt.name for tgt in tgts])) # Filter the swift-sdks parameter build_script_impl_opts = [opt for opt in build_script_impl_opts if not opt.startswith("--swift-sdks")] return build_script_opts + ["--"] + build_script_impl_opts def get_all_preset_names(preset_file_names): config = _load_preset_files_impl(preset_file_names) return [name[len(_PRESET_PREFIX):] for name in config.sections() if name.startswith(_PRESET_PREFIX)]
[]
[]
[ "SWIFT_BUILD_ROOT", "HOME", "SWIFT_SOURCE_ROOT" ]
[]
["SWIFT_BUILD_ROOT", "HOME", "SWIFT_SOURCE_ROOT"]
python
3
0
tests/loggers/test_wandb.py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pickle from argparse import ArgumentParser from unittest import mock import pytest import pytorch_lightning from pytorch_lightning import Trainer from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.helpers import BoringModel @mock.patch("pytorch_lightning.loggers.wandb.wandb") def test_wandb_logger_init(wandb): """Verify that basic functionality of wandb logger works. Wandb doesn't work well with pytest so we have to mock it out here.""" # test wandb.init called when there is no W&B run wandb.run = None logger = WandbLogger( name="test_name", save_dir="test_save_dir", version="test_id", project="test_project", resume="never" ) logger.log_metrics({"acc": 1.0}) wandb.init.assert_called_once_with( name="test_name", dir="test_save_dir", id="test_id", project="test_project", resume="never", anonymous=None ) wandb.init().log.assert_called_once_with({"acc": 1.0}) # test wandb.init and setting logger experiment externally wandb.run = None run = wandb.init() logger = WandbLogger(experiment=run) assert logger.experiment # test wandb.init not called if there is a W&B run wandb.init().log.reset_mock() wandb.init.reset_mock() wandb.run = wandb.init() logger = WandbLogger() # verify default resume value assert logger._wandb_init["resume"] == "allow" _ = logger.experiment assert any("There is a wandb run already in progress" in w for w in pytorch_lightning.loggers.wandb.warning_cache) logger.log_metrics({"acc": 1.0}, step=3) wandb.init.assert_called_once() wandb.init().log.assert_called_once_with({"acc": 1.0, "trainer/global_step": 3}) # continue training on same W&B run and offset step logger.finalize("success") logger.log_metrics({"acc": 1.0}, step=6) wandb.init().log.assert_called_with({"acc": 1.0, "trainer/global_step": 6}) # log hyper parameters logger.log_hyperparams({"test": None, "nested": {"a": 1}, "b": [2, 3, 4]}) wandb.init().config.update.assert_called_once_with( {"test": "None", "nested/a": 1, "b": [2, 3, 4]}, allow_val_change=True ) # watch a model logger.watch("model", "log", 10, False) wandb.init().watch.assert_called_once_with("model", log="log", log_freq=10, log_graph=False) assert logger.name == wandb.init().project_name() assert logger.version == wandb.init().id @mock.patch("pytorch_lightning.loggers.wandb.wandb") def test_wandb_pickle(wandb, tmpdir): """ Verify that pickling trainer with wandb logger works. Wandb doesn't work well with pytest so we have to mock it out here. """ class Experiment: id = "the_id" step = 0 dir = "wandb" def project_name(self): return "the_project_name" wandb.run = None wandb.init.return_value = Experiment() logger = WandbLogger(id="the_id", offline=True) trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, logger=logger) # Access the experiment to ensure it's created assert trainer.logger.experiment, "missing experiment" assert trainer.log_dir == logger.save_dir pkl_bytes = pickle.dumps(trainer) trainer2 = pickle.loads(pkl_bytes) assert os.environ["WANDB_MODE"] == "dryrun" assert trainer2.logger.__class__.__name__ == WandbLogger.__name__ assert trainer2.logger.experiment, "missing experiment" wandb.init.assert_called() assert "id" in wandb.init.call_args[1] assert wandb.init.call_args[1]["id"] == "the_id" del os.environ["WANDB_MODE"] @mock.patch("pytorch_lightning.loggers.wandb.wandb") def test_wandb_logger_dirs_creation(wandb, tmpdir): """Test that the logger creates the folders and files in the right place.""" logger = WandbLogger(save_dir=str(tmpdir), offline=True) assert logger.version is None assert logger.name is None # mock return values of experiment wandb.run = None logger.experiment.id = "1" logger.experiment.project_name.return_value = "project" for _ in range(2): _ = logger.experiment assert logger.version == "1" assert logger.name == "project" assert str(tmpdir) == logger.save_dir assert not os.listdir(tmpdir) version = logger.version model = BoringModel() trainer = Trainer(default_root_dir=tmpdir, logger=logger, max_epochs=1, limit_train_batches=3, limit_val_batches=3) assert trainer.log_dir == logger.save_dir trainer.fit(model) assert trainer.checkpoint_callback.dirpath == str(tmpdir / "project" / version / "checkpoints") assert set(os.listdir(trainer.checkpoint_callback.dirpath)) == {"epoch=0-step=2.ckpt"} assert trainer.log_dir == logger.save_dir @mock.patch("pytorch_lightning.loggers.wandb.wandb") def test_wandb_log_model(wandb, tmpdir): """Test that the logger creates the folders and files in the right place.""" wandb.run = None model = BoringModel() # test log_model=True logger = WandbLogger(log_model=True) logger.experiment.id = "1" logger.experiment.project_name.return_value = "project" trainer = Trainer(default_root_dir=tmpdir, logger=logger, max_epochs=2, limit_train_batches=3, limit_val_batches=3) trainer.fit(model) wandb.init().log_artifact.assert_called_once() # test log_model='all' wandb.init().log_artifact.reset_mock() wandb.init.reset_mock() logger = WandbLogger(log_model="all") logger.experiment.id = "1" logger.experiment.project_name.return_value = "project" trainer = Trainer(default_root_dir=tmpdir, logger=logger, max_epochs=2, limit_train_batches=3, limit_val_batches=3) trainer.fit(model) assert wandb.init().log_artifact.call_count == 2 # test log_model=False wandb.init().log_artifact.reset_mock() wandb.init.reset_mock() logger = WandbLogger(log_model=False) logger.experiment.id = "1" logger.experiment.project_name.return_value = "project" trainer = Trainer(default_root_dir=tmpdir, logger=logger, max_epochs=2, limit_train_batches=3, limit_val_batches=3) trainer.fit(model) assert not wandb.init().log_artifact.called # test correct metadata import pytorch_lightning.loggers.wandb as pl_wandb pl_wandb._WANDB_GREATER_EQUAL_0_10_22 = True wandb.init().log_artifact.reset_mock() wandb.init.reset_mock() wandb.Artifact.reset_mock() logger = pl_wandb.WandbLogger(log_model=True) logger.experiment.id = "1" logger.experiment.project_name.return_value = "project" trainer = Trainer(default_root_dir=tmpdir, logger=logger, max_epochs=2, limit_train_batches=3, limit_val_batches=3) trainer.fit(model) wandb.Artifact.assert_called_once_with( name="model-1", type="model", metadata={ "score": None, "original_filename": "epoch=1-step=5-v3.ckpt", "ModelCheckpoint": { "monitor": None, "mode": "min", "save_last": None, "save_top_k": 1, "save_weights_only": False, "_every_n_train_steps": 0, }, }, ) def test_wandb_sanitize_callable_params(tmpdir): """ Callback function are not serializiable. Therefore, we get them a chance to return something and if the returned type is not accepted, return None. """ opt = "--max_epochs 1".split(" ") parser = ArgumentParser() parser = Trainer.add_argparse_args(parent_parser=parser) params = parser.parse_args(opt) def return_something(): return "something" params.something = return_something def wrapper_something(): return return_something params.wrapper_something_wo_name = lambda: lambda: "1" params.wrapper_something = wrapper_something params = WandbLogger._convert_params(params) params = WandbLogger._flatten_dict(params) params = WandbLogger._sanitize_callable_params(params) assert params["gpus"] == "None" assert params["something"] == "something" assert params["wrapper_something"] == "wrapper_something" assert params["wrapper_something_wo_name"] == "<lambda>" @mock.patch("pytorch_lightning.loggers.wandb.wandb") def test_wandb_logger_offline_log_model(wandb, tmpdir): """Test that log_model=True raises an error in offline mode""" with pytest.raises(MisconfigurationException, match="checkpoints cannot be uploaded in offline mode"): _ = WandbLogger(save_dir=str(tmpdir), offline=True, log_model=True)
[]
[]
[ "WANDB_MODE" ]
[]
["WANDB_MODE"]
python
1
0
docs/conf.py
# This file is execfile()d with the current directory set to its containing dir. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import shutil # -- Path setup -------------------------------------------------------------- __location__ = os.path.dirname(__file__) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.join(__location__, "../src")) # -- Run sphinx-apidoc ------------------------------------------------------- # This hack is necessary since RTD does not issue `sphinx-apidoc` before running # `sphinx-build -b html . _build/html`. See Issue: # https://github.com/readthedocs/readthedocs.org/issues/1139 # DON'T FORGET: Check the box "Install your project inside a virtualenv using # setup.py install" in the RTD Advanced Settings. # Additionally it helps us to avoid running apidoc manually try: # for Sphinx >= 1.7 from sphinx.ext import apidoc except ImportError: from sphinx import apidoc output_dir = os.path.join(__location__, "api") module_dir = os.path.join(__location__, "../src/seleccionestudiante") try: shutil.rmtree(output_dir) except FileNotFoundError: pass try: import sphinx cmd_line = f"sphinx-apidoc --implicit-namespaces -f -o {output_dir} {module_dir}" args = cmd_line.split(" ") if tuple(sphinx.__version__.split(".")) >= ("1", "7"): # This is a rudimentary parse_version to avoid external dependencies args = args[1:] apidoc.main(args) except Exception as e: print("Running `sphinx-apidoc` failed!\n{}".format(e)) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.autosummary", "sphinx.ext.viewcode", "sphinx.ext.coverage", "sphinx.ext.doctest", "sphinx.ext.ifconfig", "sphinx.ext.mathjax", "sphinx.ext.napoleon", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "SeleccionEstudiante" copyright = "2021, d4160" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # version: The short X.Y version. # release: The full version, including alpha/beta/rc tags. # If you don’t need the separation provided between version and release, # just set them both to the same value. try: from seleccionestudiante import __version__ as version except ImportError: version = "" if not version or version.lower() == "unknown": version = os.getenv("READTHEDOCS_VERSION", "unknown") # automatically set by RTD release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".venv"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If this is True, todo emits a warning for each TODO entries. The default is False. todo_emit_warnings = True # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { "sidebar_width": "300px", "page_width": "1200px" } # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = "" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "SeleccionEstudiante-doc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ("letterpaper" or "a4paper"). # "papersize": "letterpaper", # The font size ("10pt", "11pt" or "12pt"). # "pointsize": "10pt", # Additional stuff for the LaTeX preamble. # "preamble": "", } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "user_guide.tex", "SeleccionEstudiante Documentation", "d4160", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = "" # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- External mapping -------------------------------------------------------- python_version = ".".join(map(str, sys.version_info[0:2])) intersphinx_mapping = { "sphinx": ("https://www.sphinx-doc.org/en/master", None), "python": ("https://docs.python.org/" + python_version, None), "matplotlib": ("https://matplotlib.org", None), "numpy": ("https://numpy.org/doc/stable", None), "sklearn": ("https://scikit-learn.org/stable", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), "setuptools": ("https://setuptools.readthedocs.io/en/stable/", None), "pyscaffold": ("https://pyscaffold.org/en/stable", None), } print(f"loading configurations for {project} {version} ...", file=sys.stderr)
[]
[]
[ "READTHEDOCS_VERSION" ]
[]
["READTHEDOCS_VERSION"]
python
1
0
mustache/mustache.go
package mustache import ( "bytes" "errors" "fmt" "html/template" "io" "io/ioutil" "os" "path" "reflect" "strings" ) type textElement struct { text []byte } type varElement struct { name string raw bool } type sectionElement struct { name string inverted bool startline int elems []interface{} } type Template struct { data string otag string ctag string p int curline int dir string elems []interface{} lambdas map[string]func(string) string } type parseError struct { line int message string } func (p parseError) Error() string { return fmt.Sprintf("line %d: %s", p.line, p.message) } var ( esc_quot = []byte("&quot;") esc_apos = []byte("&apos;") esc_amp = []byte("&amp;") esc_lt = []byte("&lt;") esc_gt = []byte("&gt;") ) func (tmpl *Template) readString(s string) (string, error) { i := tmpl.p newlines := 0 for true { //are we at the end of the string? if i+len(s) > len(tmpl.data) { return tmpl.data[tmpl.p:], io.EOF } if tmpl.data[i] == '\n' { newlines++ } if tmpl.data[i] != s[0] { i++ continue } match := true for j := 1; j < len(s); j++ { if s[j] != tmpl.data[i+j] { match = false break } } if match { e := i + len(s) text := tmpl.data[tmpl.p:e] tmpl.p = e tmpl.curline += newlines return text, nil } else { i++ } } //should never be here return "", nil } func (tmpl *Template) parsePartial(name string) (*Template, error) { filenames := []string{ path.Join(tmpl.dir, name), path.Join(tmpl.dir, name+".mustache"), path.Join(tmpl.dir, name+".stache"), name, name + ".mustache", name + ".stache", } var filename string for _, name := range filenames { f, err := os.Open(name) if err == nil { filename = name f.Close() break } } if filename == "" { return nil, errors.New(fmt.Sprintf("Could not find partial %q", name)) } partial, err := ParseFile(filename, tmpl.lambdas) if err != nil { return nil, err } return partial, nil } func (tmpl *Template) parseSection(section *sectionElement) error { for { text, err := tmpl.readString(tmpl.otag) if err == io.EOF { return parseError{section.startline, "Section " + section.name + " has no closing tag"} } // put text into an item text = text[0 : len(text)-len(tmpl.otag)] section.elems = append(section.elems, &textElement{[]byte(text)}) if tmpl.p < len(tmpl.data) && tmpl.data[tmpl.p] == '{' { text, err = tmpl.readString("}" + tmpl.ctag) } else { text, err = tmpl.readString(tmpl.ctag) } if err == io.EOF { //put the remaining text in a block return parseError{tmpl.curline, "unmatched open tag"} } //trim the close tag off the text tag := strings.TrimSpace(text[0 : len(text)-len(tmpl.ctag)]) if len(tag) == 0 { return parseError{tmpl.curline, "empty tag"} } switch tag[0] { case '!': //ignore comment break case '#', '^': name := strings.TrimSpace(tag[1:]) if function, ok := tmpl.lambdas[name]; ok { closeTag := "{{/" + name + "}}" text, _ := tmpl.readString(closeTag) subTmpl, err := ParseString(function(text[:len(text)-len(closeTag)])) if err != nil { return err } section.elems = append(section.elems, subTmpl.elems...) } else { //ignore the newline when a section starts if len(tmpl.data) > tmpl.p && tmpl.data[tmpl.p] == '\n' { tmpl.p += 1 } else if len(tmpl.data) > tmpl.p+1 && tmpl.data[tmpl.p] == '\r' && tmpl.data[tmpl.p+1] == '\n' { tmpl.p += 2 } se := sectionElement{name, tag[0] == '^', tmpl.curline, []interface{}{}} err := tmpl.parseSection(&se) if err != nil { return err } section.elems = append(section.elems, &se) } case '/': name := strings.TrimSpace(tag[1:]) if name != section.name { return parseError{tmpl.curline, "interleaved closing tag: " + name} } else { return nil } case '>': name := strings.TrimSpace(tag[1:]) partial, err := tmpl.parsePartial(name) if err != nil { return err } section.elems = append(section.elems, partial) case '=': if tag[len(tag)-1] != '=' { return parseError{tmpl.curline, "Invalid meta tag"} } tag = strings.TrimSpace(tag[1 : len(tag)-1]) newtags := strings.SplitN(tag, " ", 2) if len(newtags) == 2 { tmpl.otag = newtags[0] tmpl.ctag = newtags[1] } case '{': if tag[len(tag)-1] == '}' { //use a raw tag section.elems = append(section.elems, &varElement{tag[1 : len(tag)-1], true}) } default: section.elems = append(section.elems, &varElement{tag, false}) } } return nil } func (tmpl *Template) parse() error { for { text, err := tmpl.readString(tmpl.otag) if err == io.EOF { //put the remaining text in a block tmpl.elems = append(tmpl.elems, &textElement{[]byte(text)}) return nil } // put text into an item text = text[0 : len(text)-len(tmpl.otag)] tmpl.elems = append(tmpl.elems, &textElement{[]byte(text)}) if tmpl.p < len(tmpl.data) && tmpl.data[tmpl.p] == '{' { text, err = tmpl.readString("}" + tmpl.ctag) } else { text, err = tmpl.readString(tmpl.ctag) } if err == io.EOF { //put the remaining text in a block return parseError{tmpl.curline, "unmatched open tag"} } //trim the close tag off the text tag := strings.TrimSpace(text[0 : len(text)-len(tmpl.ctag)]) if len(tag) == 0 { return parseError{tmpl.curline, "empty tag"} } switch tag[0] { case '!': //ignore comment break case '^', '#': name := strings.TrimSpace(tag[1:]) if function, ok := tmpl.lambdas[name]; ok { closeTag := "{{/" + name + "}}" text, _ := tmpl.readString(closeTag) subTmpl, err := ParseString(function(text[:len(text)-len(closeTag)])) if err != nil { return err } tmpl.elems = append(tmpl.elems, subTmpl.elems...) } else { if len(tmpl.data) > tmpl.p && tmpl.data[tmpl.p] == '\n' { tmpl.p += 1 } else if len(tmpl.data) > tmpl.p+1 && tmpl.data[tmpl.p] == '\r' && tmpl.data[tmpl.p+1] == '\n' { tmpl.p += 2 } se := sectionElement{name, tag[0] == '^', tmpl.curline, []interface{}{}} err := tmpl.parseSection(&se) if err != nil { return err } tmpl.elems = append(tmpl.elems, &se) } case '/': return parseError{tmpl.curline, "unmatched close tag"} case '>': name := strings.TrimSpace(tag[1:]) partial, err := tmpl.parsePartial(name) if err != nil { return err } tmpl.elems = append(tmpl.elems, partial) case '=': if tag[len(tag)-1] != '=' { return parseError{tmpl.curline, "Invalid meta tag"} } tag = strings.TrimSpace(tag[1 : len(tag)-1]) newtags := strings.SplitN(tag, " ", 2) if len(newtags) == 2 { tmpl.otag = newtags[0] tmpl.ctag = newtags[1] } case '{': //use a raw tag if tag[len(tag)-1] == '}' { tmpl.elems = append(tmpl.elems, &varElement{tag[1 : len(tag)-1], true}) } default: tmpl.elems = append(tmpl.elems, &varElement{tag, false}) } } return nil } // See if name is a method of the value at some level of indirection. // The return values are the result of the call (which may be nil if // there's trouble) and whether a method of the right name exists with // any signature. func callMethod(data reflect.Value, name string) (result reflect.Value, found bool) { found = false // Method set depends on pointerness, and the value may be arbitrarily // indirect. Simplest approach is to walk down the pointer chain and // see if we can find the method at each step. // Most steps will see NumMethod() == 0. for { typ := data.Type() if nMethod := data.Type().NumMethod(); nMethod > 0 { for i := 0; i < nMethod; i++ { method := typ.Method(i) if method.Name == name { found = true // we found the name regardless // does receiver type match? (pointerness might be off) if typ == method.Type.In(0) { return call(data, method), found } } } } if nd := data; nd.Kind() == reflect.Ptr { data = nd.Elem() } else { break } } return } // Invoke the method. If its signature is wrong, return nil. func call(v reflect.Value, method reflect.Method) reflect.Value { funcType := method.Type // Method must take no arguments, meaning as a func it has one argument (the receiver) if funcType.NumIn() != 1 { return reflect.Value{} } // Method must return a single value. if funcType.NumOut() == 0 { return reflect.Value{} } // Result will be the zeroth element of the returned slice. return method.Func.Call([]reflect.Value{v})[0] } // Evaluate interfaces and pointers looking for a value that can look up the name, via a // struct field, method, or map key, and return the result of the lookup. func lookup(contextChain []interface{}, name string) reflect.Value { // dot notation if name != "." && strings.Contains(name, ".") { parts := strings.SplitN(name, ".", 2) v := lookup(contextChain, parts[0]) return lookup([]interface{}{v}, parts[1]) } defer func() { if r := recover(); r != nil { fmt.Printf("Panic while looking up %q: %s\n", name, r) } }() Outer: for _, ctx := range contextChain { //i := len(contextChain) - 1; i >= 0; i-- { v := ctx.(reflect.Value) for v.IsValid() { typ := v.Type() if n := v.Type().NumMethod(); n > 0 { for i := 0; i < n; i++ { m := typ.Method(i) mtyp := m.Type if m.Name == name && mtyp.NumIn() == 1 { return v.Method(i).Call(nil)[0] } } } if name == "." { return v } switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() case reflect.Struct: ret := av.FieldByName(name) if ret.IsValid() { return ret } else { continue Outer } case reflect.Map: ret := av.MapIndex(reflect.ValueOf(name)) if ret.IsValid() { return ret } else { continue Outer } default: continue Outer } } } return reflect.Value{} } func isEmpty(v reflect.Value) bool { if !v.IsValid() || v.Interface() == nil { return true } valueInd := indirect(v) if !valueInd.IsValid() { return true } switch val := valueInd; val.Kind() { case reflect.Bool: return !val.Bool() case reflect.Slice: return val.Len() == 0 } return false } func indirect(v reflect.Value) reflect.Value { loop: for v.IsValid() { switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() default: break loop } } return v } func renderSection(section *sectionElement, contextChain []interface{}, buf io.Writer) { value := lookup(contextChain, section.name) var context = contextChain[len(contextChain)-1].(reflect.Value) var contexts = []interface{}{} // if the value is nil, check if it's an inverted section isEmpty := isEmpty(value) if isEmpty && !section.inverted || !isEmpty && section.inverted { return } else if !section.inverted { valueInd := indirect(value) switch val := valueInd; val.Kind() { case reflect.Slice: for i := 0; i < val.Len(); i++ { contexts = append(contexts, val.Index(i)) } case reflect.Array: for i := 0; i < val.Len(); i++ { contexts = append(contexts, val.Index(i)) } case reflect.Map, reflect.Struct: contexts = append(contexts, value) default: contexts = append(contexts, context) } } else if section.inverted { contexts = append(contexts, context) } chain2 := make([]interface{}, len(contextChain)+1) copy(chain2[1:], contextChain) //by default we execute the section for _, ctx := range contexts { chain2[0] = ctx for _, elem := range section.elems { renderElement(elem, chain2, buf) } } } func renderElement(element interface{}, contextChain []interface{}, buf io.Writer) { switch elem := element.(type) { case *textElement: buf.Write(elem.text) case *varElement: defer func() { if r := recover(); r != nil { fmt.Printf("Panic while looking up %q: %s\n", elem.name, r) } }() val := lookup(contextChain, elem.name) if val.IsValid() { if elem.raw { fmt.Fprint(buf, val.Interface()) } else { s := fmt.Sprint(val.Interface()) template.HTMLEscape(buf, []byte(s)) } } case *sectionElement: renderSection(elem, contextChain, buf) case *Template: elem.renderTemplate(contextChain, buf) } } func (tmpl *Template) renderTemplate(contextChain []interface{}, buf io.Writer) { for _, elem := range tmpl.elems { renderElement(elem, contextChain, buf) } } func (tmpl *Template) Render(context ...interface{}) string { var buf bytes.Buffer var contextChain []interface{} for _, c := range context { val := reflect.ValueOf(c) contextChain = append(contextChain, val) } tmpl.renderTemplate(contextChain, &buf) return buf.String() } func (tmpl *Template) RenderInLayout(layout *Template, context ...interface{}) string { content := tmpl.Render(context...) allContext := make([]interface{}, len(context)+1) copy(allContext[1:], context) allContext[0] = map[string]string{"content": content} return layout.Render(allContext...) } func ParseString(data string) (*Template, error) { cwd := os.Getenv("CWD") tmpl := Template{data, "{{", "}}", 0, 1, cwd, []interface{}{}, nil} err := tmpl.parse() if err != nil { return nil, err } return &tmpl, err } func ParseFile(filename string, lambdas map[string]func(string) string) (*Template, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } dirname, _ := path.Split(filename) tmpl := Template{string(data), "{{", "}}", 0, 1, dirname, []interface{}{}, lambdas} err = tmpl.parse() if err != nil { return nil, err } return &tmpl, nil } func Render(data string, context ...interface{}) string { tmpl, err := ParseString(data) if err != nil { return err.Error() } return tmpl.Render(context...) } func RenderFile(filename string, lambdas map[string]func(string) string, context ...interface{}) string { tmpl, err := ParseFile(filename, lambdas) if err != nil { return err.Error() } return tmpl.Render(context...) }
[ "\"CWD\"" ]
[]
[ "CWD" ]
[]
["CWD"]
go
1
0
system_tests/lifecycle/all_lifecycle_tests/feature_toggled_tests.go
package all_lifecycle_tests import ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "strings" "time" "github.com/cloudfoundry/noaa/consumer" "github.com/cloudfoundry/sonde-go/events" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "github.com/pborman/uuid" "github.com/pivotal-cf/on-demand-service-broker/system_tests/test_helpers/bosh_helpers" "github.com/pivotal-cf/on-demand-service-broker/system_tests/test_helpers/cf_helpers" "github.com/pivotal-cf/on-demand-service-broker/system_tests/test_helpers/service_helpers" gouaa "github.com/cloudfoundry-community/go-uaa" ) func FeatureToggledLifecycleTest( serviceType service_helpers.ServiceType, brokerInfo bosh_helpers.BrokerInfo, planName string, newPlanName string, arbitraryParams string, dopplerAddress string) { var ( serviceInstanceName string serviceInstanceGUID string serviceKeyContents string serviceKeyName string appName string appURL string uaaClientCreateTimestamp int64 ) By("logging telemetry data at startup", func() { stdoutLogs := bosh_helpers.GetBrokerLogs(brokerInfo.DeploymentName) telemetryLogTotal := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"broker","operation":"startup"},"service-instances":{"total":0}}`, brokerInfo.ServiceName) telemetryLogPlanSmall := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"broker","operation":"startup"},"service-instances-per-plan":{"plan-id":"%s","total":0}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-small") telemetryLogPlanMedium := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"broker","operation":"startup"},"service-instances-per-plan":{"plan-id":"%s","total":0}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-medium") Expect(stdoutLogs).To(ContainSubstring(telemetryLogTotal)) Expect(stdoutLogs).To(SatisfyAll( ContainSubstring(telemetryLogTotal), ContainSubstring(telemetryLogPlanSmall), ContainSubstring(telemetryLogPlanMedium), )) }) By("creating a service", func() { serviceInstanceName = "service" + brokerInfo.TestSuffix cf_helpers.CreateService(brokerInfo.ServiceName, planName, serviceInstanceName, "") }) By("creating a uaa client for the SI", func() { serviceInstanceGUID = cf_helpers.GetServiceInstanceGUID(serviceInstanceName) siClient := findUAAClient(serviceInstanceGUID) Expect(siClient).NotTo(BeNil(), "client_id not found on UAA: "+serviceInstanceGUID) Expect(siClient.DisplayName).To(Equal("lifecycle_test_client")) Expect(siClient.RedirectURI).To(ContainElement(cf_helpers.GetDashboardURL(serviceInstanceGUID))) uaaClientCreateTimestamp = siClient.LastModified }) By("logging telemetry data after a create-service", func() { stdoutLogs := bosh_helpers.GetBrokerLogs(brokerInfo.DeploymentName) telemetryLogTotal := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"create"},"service-instances":{"total":1}}`, brokerInfo.ServiceName) telemetryLogPlanSmall := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"create"},"service-instances-per-plan":{"plan-id":"%s","total":1}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-small") telemetryLogPlanMedium := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"create"},"service-instances-per-plan":{"plan-id":"%s","total":0}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-medium") Expect(stdoutLogs).To(SatisfyAll( ContainSubstring(telemetryLogTotal), ContainSubstring(telemetryLogPlanSmall), ContainSubstring(telemetryLogPlanMedium), )) }) By("creating a service key", func() { serviceKeyName = "serviceKey" + brokerInfo.TestSuffix cf_helpers.CreateServiceKey(serviceInstanceName, serviceKeyName) serviceKeyContents = cf_helpers.GetServiceKey(serviceInstanceName, serviceKeyName) cf_helpers.LooksLikeAServiceKey(serviceKeyContents) }) By("testing binding with DNS", func() { testBindingWithDNS(serviceKeyContents, "dns_addresses") }) By("binding an app", func() { appName = "example-app" + brokerInfo.TestSuffix appPath := cf_helpers.GetAppPath(serviceType) appURL = cf_helpers.PushAndBindApp(appName, serviceInstanceName, appPath) }) By("ensuring the binding is a runtime credhub reference", func() { testSecureBindings(brokerInfo, appName) }) By("testing the broker emits metrics", func() { testMetrics(brokerInfo, planName, dopplerAddress) }) By("validating the broker indicator protocol", func() { downloadedIndicator := downloadIndicatorFromVM(brokerInfo) cmd := exec.Command("indicator-verification", "-indicators", downloadedIndicator.Name(), "-authorization", cf_helpers.GetOAuthToken(), "-query-endpoint", "https://log-cache."+brokerInfo.BrokerSystemDomain, "-k") session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred(), "failed to run verification tool") Eventually(session, time.Minute).Should(gexec.Exit(0), "Indicators could not be verified") }) By("testing the app can communicate with service", func() { cf_helpers.ExerciseApp(serviceType, appURL) }) By("testing the app works after updating the planName for the service", func() { cf_helpers.UpdateServiceToPlan(serviceInstanceName, newPlanName) cf_helpers.ExerciseApp(serviceType, appURL) }) By("testing the app works after updating arbitrary parameters for the service", func() { cf_helpers.UpdateServiceWithArbitraryParams(serviceInstanceName, arbitraryParams) cf_helpers.ExerciseApp(serviceType, appURL) }) By("verifying that the service instance client is updated", func() { siClient := findUAAClient(serviceInstanceGUID) Expect(siClient).NotTo(BeNil(), "client_id not found on UAA: "+serviceInstanceGUID) Expect(uaaClientCreateTimestamp).To(BeNumerically("<", siClient.LastModified), "Client wasn't modified after update") }) By("unbinding the app", func() { cf_helpers.UnbindAndDeleteApp(appName, serviceInstanceName) }) By("deleting a service key", func() { cf_helpers.DeleteServiceKey(serviceInstanceName, serviceKeyName) }) By("deleting the service", func() { cf_helpers.DeleteService(serviceInstanceName) }) By("deleting the uaa client created for the SI", func() { siClient := findUAAClient(serviceInstanceGUID) Expect(siClient).To(BeNil()) }) By("logging telemetry data after a delete-service", func() { stdoutLogs := bosh_helpers.GetBrokerLogs(brokerInfo.DeploymentName) // total number of instances will not decrease since we are using CF to get the count and CF is not aware of the result of delete at the point of logging. telemetryLogTotal := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"delete"},"service-instances":{"total":1}}`, brokerInfo.ServiceName) telemetryLogPlanSmall := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"delete"},"service-instances-per-plan":{"plan-id":"%s","total":0}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-small") telemetryLogPlanMedium := fmt.Sprintf(`"telemetry-source":"on-demand-broker","service-offering":{"name":"%s"},"event":{"item":"instance","operation":"delete"},"service-instances-per-plan":{"plan-id":"%s","total":1}}`, brokerInfo.ServiceName, brokerInfo.PlanID+"-medium") Expect(stdoutLogs).To(SatisfyAll( ContainSubstring(telemetryLogTotal), ContainSubstring(telemetryLogPlanSmall), ContainSubstring(telemetryLogPlanMedium), )) }) } func findUAAClient(clientGUID string) *gouaa.Client { uaaClientID := os.Getenv("CF_CLIENT_ID") uaaClientSecret := os.Getenv("CF_CLIENT_SECRET") uaaURL := os.Getenv("CF_UAA_URL") api, err := gouaa.New( uaaURL, gouaa.WithClientCredentials(uaaClientID, uaaClientSecret, gouaa.JSONWebToken), gouaa.WithSkipSSLValidation(true), ) Expect(err).ToNot(HaveOccurred()) filter := fmt.Sprintf("client_id eq %q", clientGUID) siClients, _, err := api.ListClients(filter, "", gouaa.SortAscending, 1, 1) Expect(err).ToNot(HaveOccurred()) if len(siClients) == 0 { return nil } return &siClients[0] } func downloadIndicatorFromVM(brokerInfo bosh_helpers.BrokerInfo) *os.File { downloadedIndicator, err := ioutil.TempFile("/tmp", "") Expect(err).NotTo(HaveOccurred()) bosh_helpers.CopyFromVM(brokerInfo.DeploymentName, "broker", "/var/vcap/jobs/broker/config/indicators.yml", downloadedIndicator.Name()) return downloadedIndicator } func testBindingWithDNS(serviceKeyRaw, bindingDNSAttribute string) { var serviceKey map[string]interface{} err := json.Unmarshal([]byte(serviceKeyRaw), &serviceKey) Expect(err).ToNot(HaveOccurred()) dnsInfo, ok := serviceKey[bindingDNSAttribute] Expect(ok).To(BeTrue(), fmt.Sprintf("%s not returned in binding", bindingDNSAttribute)) dnsInfoMap, ok := dnsInfo.(map[string]interface{}) Expect(ok).To(BeTrue(), fmt.Sprintf("Unable to convert dns info to map[string]interface{}, got:%t", dnsInfo)) Expect(len(dnsInfoMap)).To(BeNumerically(">", 0)) } func testSecureBindings(brokerInfo bosh_helpers.BrokerInfo, appName string) { bindingCredentials, err := cf_helpers.AppBindingCreds(appName, brokerInfo.ServiceName) Expect(err).NotTo(HaveOccurred()) credMap, ok := bindingCredentials.(map[string]interface{}) Expect(ok).To(BeTrue()) credhubRef, ok := credMap["credhub-ref"].(string) Expect(ok).To(BeTrue(), fmt.Sprintf("unable to find credhub-ref in credentials %+v", credMap)) Expect(credhubRef).To(ContainSubstring("/c/%s", brokerInfo.ServiceID)) } func testMetrics(brokerInfo bosh_helpers.BrokerInfo, planName string, dopplerAddress string) { brokerDeploymentName := brokerInfo.DeploymentName serviceOfferingName := brokerInfo.ServiceName Expect(dopplerAddress).NotTo(BeEmpty()) firehoseConsumer := consumer.New(dopplerAddress, &tls.Config{InsecureSkipVerify: true}, nil) defer firehoseConsumer.Close() msgChan, errChan := firehoseConsumer.Firehose("SystemTests-"+uuid.New(), cf_helpers.GetOAuthToken()) timeoutChan := time.After(5 * time.Minute) for { select { case msg := <-msgChan: if msg != nil && *msg.EventType == events.Envelope_ValueMetric && strings.HasSuffix(*msg.Deployment, brokerDeploymentName) { fmt.Fprintf(GinkgoWriter, "received metric for deployment %s: %+v\n", brokerDeploymentName, msg) if msg.ValueMetric.GetName() == fmt.Sprintf("/on-demand-broker/%s/%s/total_instances", serviceOfferingName, planName) { fmt.Fprintln(GinkgoWriter, "ODB metrics test successful") return } } case err := <-errChan: Expect(err).NotTo(HaveOccurred()) return case <-timeoutChan: Fail("Service Metrics test timed out after 5 minutes.") return } } }
[ "\"CF_CLIENT_ID\"", "\"CF_CLIENT_SECRET\"", "\"CF_UAA_URL\"" ]
[]
[ "CF_CLIENT_ID", "CF_CLIENT_SECRET", "CF_UAA_URL" ]
[]
["CF_CLIENT_ID", "CF_CLIENT_SECRET", "CF_UAA_URL"]
go
3
0
src/pkg/golang/build.go
// Copyright 2015-2018 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package golang is an API to the Go compiler. package golang import ( "fmt" "go/build" "os" "os/exec" "path/filepath" "strings" ) type Environ struct { build.Context GO111MODULE string } // Default is the default build environment comprised of the default GOPATH, // GOROOT, GOOS, GOARCH, and CGO_ENABLED values. func Default() Environ { return Environ{ Context: build.Default, GO111MODULE: os.Getenv("GO111MODULE"), } } // GoCmd runs a go command in the environment. func (c Environ) GoCmd(args ...string) *exec.Cmd { cmd := exec.Command(filepath.Join(c.GOROOT, "bin", "go"), args...) cmd.Env = append(os.Environ(), c.Env()...) return cmd } // Version returns the Go version string that runtime.Version would return for // the Go compiler in this environ. func (c Environ) Version() (string, error) { cmd := c.GoCmd("version") v, err := cmd.CombinedOutput() if err != nil { return "", err } s := strings.Fields(string(v)) if len(s) < 3 { return "", fmt.Errorf("unknown go version, tool returned weird output for 'go version': %v", string(v)) } return s[2], nil } func (c Environ) envCommon() []string { var env []string if c.GOARCH != "" { env = append(env, fmt.Sprintf("GOARCH=%s", c.GOARCH)) } if c.GOOS != "" { env = append(env, fmt.Sprintf("GOOS=%s", c.GOOS)) } if c.GOPATH != "" { env = append(env, fmt.Sprintf("GOPATH=%s", c.GOPATH)) } var cgo int8 if c.CgoEnabled { cgo = 1 } env = append(env, fmt.Sprintf("CGO_ENABLED=%d", cgo)) env = append(env, fmt.Sprintf("GO111MODULE=%s", c.GO111MODULE)) if c.GOROOT != "" { env = append(env, fmt.Sprintf("GOROOT=%s", c.GOROOT)) } return env } func (c Environ) EnvHuman() []string { env := c.envCommon() if c.GOROOT != "" { env = append(env, fmt.Sprintf("PATH=%s:$PATH", filepath.Join(c.GOROOT, "bin"))) } return env } // Env returns all environment variables for invoking a Go command. func (c Environ) Env() []string { env := c.envCommon() if c.GOROOT != "" { // If GOROOT is set to a different version of Go, we must // ensure that $GOROOT/bin is also in path to make the "go" // binary available to golang.org/x/tools/packages. env = append(env, fmt.Sprintf("PATH=%s:%s", filepath.Join(c.GOROOT, "bin"), os.Getenv("PATH"))) } return env } // String returns all environment variables for Go invocations. func (c Environ) String() string { return strings.Join(c.EnvHuman(), " ") } // Optional arguments to Environ.Build. type BuildOpts struct { // NoStrip builds an unstripped binary. NoStrip bool // ExtraArgs to `go build`. ExtraArgs []string } // BuildDir compiles the package in the directory `dirPath`, writing the build // object to `binaryPath`. func (c Environ) BuildDir(dirPath string, binaryPath string, opts BuildOpts) error { args := []string{ "build", // Force rebuilding of packages. "-a", // Strip all symbols, and don't embed a Go build ID to be reproducible. "-ldflags", "-s -w -buildid=", "-o", binaryPath, "-installsuffix", "uroot", "-gcflags=all=-l", // Disable "function inlining" to get a smaller binary } if !opts.NoStrip { args = append(args, `-ldflags=-s -w`) // Strip all symbols. } // Reproducible builds: Trim any GOPATHs out of the executable's // debugging information. // // E.g. Trim /tmp/bb-*/ from /tmp/bb-12345567/src/github.com/... args = append(args, "-trimpath") if len(c.BuildTags) > 0 { args = append(args, []string{"-tags", strings.Join(c.BuildTags, " ")}...) } // We always set the working directory, so this is always '.'. args = append(args, ".") cmd := c.GoCmd(args...) cmd.Dir = dirPath if o, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("error building go package in %q: %v, %v", dirPath, string(o), err) } return nil }
[ "\"GO111MODULE\"", "\"PATH\"" ]
[]
[ "GO111MODULE", "PATH" ]
[]
["GO111MODULE", "PATH"]
go
2
0
assets/functions/ml_pipeline/upload_result/app.py
''' Input event payload expected to be in the following format: { "Batch_start": "MAC000001", "Batch_end": "MAC000010", "Data_start": "2013-06-01", "Data_end": "2014-01-01", "Forecast_period": 7 } ''' import boto3, os import json import pandas as pd import numpy as np from pyathena import connect REGION = os.environ['AWS_REGION'] ATHENA_OUTPUT_BUCKET = os.environ['Athena_bucket'] S3_BUCKET = os.environ['Working_bucket'] DB_SCHEMA = os.environ['Db_schema'] ATHENA_CONNECTION = connect(s3_staging_dir='s3://{}/'.format(ATHENA_OUTPUT_BUCKET), region_name=REGION) S3 = boto3.resource('s3') def get_meters(connection, start, end, db_schema): selected_households = '''select distinct meter_id from "{}".daily where meter_id between '{}' and '{}' order by meter_id; '''.format(db_schema, start, end) df_meters = pd.read_sql(selected_households, connection) return df_meters['meter_id'].tolist() def lambda_handler(event, context): batch_start = event['Batch_start'] batch_end = event['Batch_end'] forecast_start = event['Data_end'] forecast_period = event['Forecast_period'] prediction_length = forecast_period * 24 output = 'meteranalytics/inference/batch_%s_%s/batch.json.out' % (batch_start, batch_end) S3.Bucket(S3_BUCKET).Object(output).download_file('/tmp/batch.out.json') freq = 'H' prediction_time = pd.Timestamp(forecast_start, freq=freq) prediction_index = pd.date_range(start=prediction_time, end=prediction_time + pd.Timedelta(prediction_length - 1, unit='H'), freq=freq) dict_of_samples = {} meterids = get_meters(ATHENA_CONNECTION, batch_start, batch_end, DB_SCHEMA) results = pd.DataFrame(columns=['meterid', 'datetime', 'kwh']) i = 0 with open('/tmp/batch.out.json') as fp: for line in fp: df = pd.DataFrame(data={**json.loads(line)['quantiles'], **dict_of_samples}, index=prediction_index) dataframe = pd.DataFrame({'meter_id': np.array([meterids[i] for x in range(df['0.9'].count())]), 'datetime': df.index.values, 'consumption': df['0.9'].values}) i = i + 1 results = results.append(dataframe) results.to_csv('/tmp/forecast.csv', index=False) S3.Bucket(S3_BUCKET).Object(os.path.join('meteranalytics', 'forecast/{}/batch_{}_{}.csv'.format( forecast_start, batch_start, batch_end))).upload_file( '/tmp/forecast.csv')
[]
[]
[ "Athena_bucket", "Db_schema", "Working_bucket", "AWS_REGION" ]
[]
["Athena_bucket", "Db_schema", "Working_bucket", "AWS_REGION"]
python
4
0
firestore/firestore_snippets/main.go
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Command firestore_snippets contains runnable snippet code for Cloud Spanner. package main import ( "context" "fmt" "log" "os" "cloud.google.com/go/firestore" ) // [START firestore_data_custom_type_definition] // City represents a city. type City struct { Name string `firestore:"name,omitempty"` State string `firestore:"state,omitempty"` Country string `firestore:"country,omitempty"` Capital bool `firestore:"capital,omitempty"` Population int64 `firestore:"population,omitempty"` Regions []string `firestore:"regions,omitempty"` } // [END firestore_data_custom_type_definition] func main() { ctx := context.Background() projectID := os.Getenv("GCLOUD_PROJECT") if projectID == "" { log.Fatalf("Set Firebase project ID via GCLOUD_PROJECT env variable.") } client, err := firestore.NewClient(ctx, projectID) if err != nil { log.Fatalf("Cannot create client: %v", err) } defer client.Close() if err := prepareQuery(ctx, client); err != nil { log.Fatalf("Cannot prepare query docs: %v", err) } if err := addDocAsMap(ctx, client); err != nil { log.Fatalf("Cannot add document as map: %v", err) } if err := addDocDataTypes(ctx, client); err != nil { log.Fatalf("Cannot add document with more data types: %v", err) } if err := addDocAsEntity(ctx, client); err != nil { log.Fatalf("Cannot add document as entity: %v", err) } if err := addDocWithID(ctx, client); err != nil { log.Fatalf("Cannot add doc with id: %v", err) } if err := addDocWithoutID(ctx, client); err != nil { log.Fatalf("Cannot add doc without id: %v", err) } if err := addDocAfterAutoGeneratedID(ctx, client); err != nil { log.Fatalf("Cannot add document after generating ID: %v", err) } if err := updateDoc(ctx, client); err != nil { log.Fatalf("Cannot update doc: %v", err) } if err := updateDocCreateIfMissing(ctx, client); err != nil { log.Fatalf("Cannot update doc, creating if missing: %v", err) } if err := updateDocMultiple(ctx, client); err != nil { log.Fatalf("Cannot update multiple docs: %v", err) } if err := updateDocNested(ctx, client); err != nil { log.Fatalf("Cannot update nested doc: %v", err) } if err := deleteDoc(ctx, client); err != nil { log.Fatalf("Cannot delete doc: %v", err) } if err := deleteField(ctx, client); err != nil { log.Fatalf("Cannot delete document field: %v", err) } if err := runSimpleTransaction(ctx, client); err != nil { log.Fatalf("Cannot run simple job in transaction: %v", err) } if err := infoTransaction(ctx, client); err != nil { log.Fatalf("Cannot return info in transaction: %v", err) } if err := batchWrite(ctx, client); err != nil { log.Fatalf("Cannot write in a batch: %v", err) } if err := prepareRetrieve(ctx, client); err != nil { log.Fatalf("Cannot prepare for retrieve samples: %v", err) } if err := paginateCursor(ctx, client); err != nil { log.Fatalf("Cannot paginate cursor: %v", err) } doc, err := docAsMap(ctx, client) if err != nil { log.Fatalf("Cannot get doc as map: %v", err) } fmt.Printf("Retrieved doc as map: %v\n", doc) city, err := docAsEntity(ctx, client) if err != nil { log.Fatalf("Cannot get doc as entity: %v", err) } fmt.Printf("Retrieved doc as entity: %v\n", city) if err := multipleDocs(ctx, client); err != nil { log.Fatalf("Cannot retrieve capital cities: %v", err) } if err := allDocs(ctx, client); err != nil { log.Fatalf("Cannot retrieve all docs: %v", err) } if err := getCollections(ctx, client); err != nil { log.Fatalf("Cannot get subcollections for document: %v", err) } if err := createInQuery(ctx, client); err != nil { log.Fatalf("Cannot get query results using in: %v", err) } if err := createInQueryWithArray(ctx, client); err != nil { log.Fatalf("Cannot get query results using in with array: %v", err) } if err := createArrayContainsQuery(ctx, client); err != nil { log.Fatalf("Cannot get query results using array-contains: %v", err) } if err := createArrayContainsAnyQuery(ctx, client); err != nil { log.Fatalf("Cannot get query results using array-contains-any: %v", err) } if err := createStartAtDocSnapshotQuery(ctx, client); err != nil { log.Fatalf("Cannot get query results using document snapshot: %v", err) } if err := deleteCollection(ctx, client, client.Collection("cities"), 2); err != nil { log.Fatalf("Cannot delete collectionL %v", err) } } // TODO(jbd): Add tests.
[ "\"GCLOUD_PROJECT\"" ]
[]
[ "GCLOUD_PROJECT" ]
[]
["GCLOUD_PROJECT"]
go
1
0
integration/test/test_geopmio.py
#!/usr/bin/env python3 # # Copyright (c) 2015 - 2022, Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # import sys import unittest import os import subprocess import io import time import signal from contextlib import contextmanager from integration.test import geopm_test_launcher from integration.test import util @util.skip_unless_do_launch() class TestIntegrationGeopmio(unittest.TestCase): ''' Tests of geopmread and geopmwrite.''' def setUp(self): self.skip_warning_string = 'Incompatible CPU' def check_output(self, args, expected): try: with subprocess.Popen([self.exec_name] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: proc.wait() for exp in expected: line = proc.stdout.readline() while self.skip_warning_string.encode() in line: line = proc.stdout.readline() self.assertIn(exp.encode(), line) for line in proc.stdout: if self.skip_warning_string.encode() not in line: self.assertNotIn(b'Error', line) except subprocess.CalledProcessError as ex: sys.stderr.write('{} {}\n'.format(str(ex), proc.stderr.getvalue())) def check_output_range(self, args, min_exp, max_exp): read_value = geopm_test_launcher.geopmread('{}'.format(' '.join(args))) self.assertLessEqual(min_exp, read_value, msg="Value read for {} smaller than {}: {}.".format(args, min_exp, read_value)) self.assertGreaterEqual(max_exp, read_value, msg="Value read for {} larger than {}: {}.".format(args, max_exp, read_value)) def check_no_error(self, args): stdout = io.StringIO() stderr = io.StringIO() test_exec = 'dummy -- {} {}'.format(self.exec_name, ' '.join(args)) try: geopm_test_launcher.allocation_node_test(test_exec, stdout, stderr) except subprocess.CalledProcessError as ex: sys.stderr.write('{} {}\n'.format(str(ex), stderr.getvalue())) for line in stderr.getvalue().splitlines(): if self.skip_warning_string not in line: self.assertNotIn('Error', line) def test_geopmread_command_line(self): ''' Check that geopmread commandline arguments work. ''' self.exec_name = "geopmread" # no args self.check_no_error([]) # domain flag self.check_output(['--domain'], ['board', 'package', 'core', 'cpu', 'memory', 'package_integrated_memory', 'nic', 'package_integrated_nic', 'gpu', 'package_integrated_gpu']) # read signal self.check_no_error(['TIME', 'board', '0']) # info self.check_no_error(['--info-all']) # errors read_err = 'domain type and domain index are required' self.check_output(['TIME'], [read_err]) self.check_output(['TIME', 'board'], [read_err]) self.check_output(['TIME', 'board', 'bad'], ['invalid domain index']) self.check_output(['CPU_FREQUENCY_STATUS', 'package', '111'], ['cannot read signal']) self.check_output(['ENERGY_PACKAGE', 'cpu', '0'], ['cannot read signal']) self.check_output(['INVALID', 'board', '0'], ['cannot read signal']) self.check_output(['--domain', '--info'], ['info about domain not implemented']) @util.skip_unless_batch() def test_geopmread_all_signal_agg(self): ''' Check that all reported signals can be read for board, aggregating if necessary. ''' self.exec_name = "geopmread" stdout = io.StringIO() stderr = io.StringIO() test_exec = 'dummy -- {}'.format(self.exec_name) try: geopm_test_launcher.allocation_node_test(test_exec, stdout, stderr) except subprocess.CalledProcessError as ex: sys.stderr.write('{} {}\n'.format(str(ex), stderr.getvalue())) raise all_signals = [] for line in stdout.getvalue().splitlines(): if self.skip_warning_string not in line: all_signals.append(line.strip()) # signals to be skipped because no application is attached. # See issue #1475 skip_profile_signals = ["EPOCH_COUNT", "EPOCH::EPOCH_COUNT", "REGION_HASH", "PROFILE::REGION_HASH", "REGION_PROGRESS", "PROFILE::REGION_PROGRESS", "REGION_HINT", "PROFILE::REGION_HINT"] for sig in all_signals: if sig not in skip_profile_signals: self.check_no_error([sig, 'board', '0']) @util.skip_unless_batch() def test_geopmread_signal_value(self): ''' Check that some specific signals give a sane value. ''' self.exec_name = "geopmread" signal_range = { "POWER_PACKAGE": (20, 400), "CPU_FREQUENCY_STATUS": (1.0e8, 5.0e9), "TIME": (0, 10), # time in sec to start geopmread "TEMPERATURE_CORE": (0, 100) } for signal_name, val_range in signal_range.items(): try: self.check_no_error([signal_name, "board", "0"]) except: raise pass # skip missing signals else: self.check_output_range([signal_name, "board", "0"], *val_range) @util.skip_unless_batch() @util.skip_unless_msr_access() def test_geopmread_custom_msr(self): ''' Check that MSRIOGroup picks up additional MSRs in path. ''' self.exec_name = "geopmread" path = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname( os.path.realpath(__file__)))), 'examples/custom_msr/') custom_env = os.environ.copy() custom_env['GEOPM_PLUGIN_PATH'] = path all_signals = [] try: with subprocess.Popen([self.exec_name], env=custom_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: proc.wait() for line in proc.stdout: if self.skip_warning_string.encode() not in line: all_signals.append(line.strip()) except subprocess.CalledProcessError as ex: sys.stderr.write('{}\n'.format(ex.output)) self.assertIn(b'MSR::CORE_PERF_LIMIT_REASONS#', all_signals) @util.skip_unless_msr_access() def test_geopmwrite_command_line(self): ''' Check that geopmwrite commandline arguments work. ''' self.exec_name = "geopmwrite" # no args self.check_no_error([]) # domain flag self.check_output(['--domain'], ['board', 'package', 'core', 'cpu', 'memory', 'package_integrated_memory', 'nic', 'package_integrated_nic', 'gpu', 'package_integrated_gpu']) # errors write_err = 'domain type, domain index, and value are required' self.check_output(['CPU_FREQUENCY_CONTROL'], [write_err]) self.check_output(['CPU_FREQUENCY_CONTROL', 'board'], [write_err]) self.check_output(['CPU_FREQUENCY_CONTROL', 'board', '0'], [write_err]) self.check_output(['CPU_FREQUENCY_CONTROL', 'board', 'bad', '0'], ['invalid domain index']) self.check_output(['CPU_FREQUENCY_CONTROL', 'board', '0', 'bad'], ['invalid write value']) self.check_output(['CPU_FREQUENCY_CONTROL', 'package', '111', '0'], ['cannot write control']) self.check_output(['CPU_FREQUENCY_CONTROL', 'nic', '0', '0'], ['cannot write control']) self.check_output(['INVALID', 'board', '0', '0'], ['cannot write control']) self.check_output(['--domain', '--info'], ['info about domain not implemented']) @util.skip_unless_msr_access() @util.skip_unless_batch() @util.skip_unless_stressng() def test_geopmwrite_set_freq(self): ''' Check that geopmwrite can be used to set frequency. ''' def read_current_freq(domain, signal='CPU_FREQUENCY_STATUS'): return geopm_test_launcher.geopmread('{} {} {}'.format(signal, domain, '0')) def read_min_sticker_freq(): return (geopm_test_launcher.geopmread('{} {} {}'.format('CPUINFO::FREQ_MIN', 'board', '0')), geopm_test_launcher.geopmread('{} {} {}'.format('CPUINFO::FREQ_STICKER', 'board', '0'))) def load_cpu_start(): self.load_pid = subprocess.Popen('stress-ng --cpu=$(lscpu | grep -e "^CPU(" | cut -d: -f2 | tr -d " ")', shell=True) def load_cpu_stop(): self.load_pid.send_signal(signal.SIGTERM) self.load_pid.communicate() @contextmanager def load_cpu(): ''' Context manager to put a load on every CPU on the node ''' try: load_cpu_start() time.sleep(5) # Give the load a moment to spin up yield finally: load_cpu_stop() read_domain = geopm_test_launcher.geopmread('--info CPU_FREQUENCY_STATUS')['domain'] write_domain = geopm_test_launcher.geopmread('--info CPU_FREQUENCY_CONTROL')['domain'] min_freq, sticker_freq = read_min_sticker_freq() old_freq = read_current_freq(write_domain, 'CPU_FREQUENCY_CONTROL') self.assertLess(old_freq, sticker_freq * 2) self.assertGreater(old_freq, min_freq - 1e8) with load_cpu(): # Set to min and check geopm_test_launcher.geopmwrite('{} {} {} {}'.format('CPU_FREQUENCY_CONTROL', write_domain, '0', str(min_freq))), time.sleep(1) result = read_current_freq(read_domain) self.assertEqual(min_freq, result) # Set to sticker and check geopm_test_launcher.geopmwrite('{} {} {} {}'.format('CPU_FREQUENCY_CONTROL', write_domain, '0', str(sticker_freq))), time.sleep(1) result = read_current_freq(read_domain) self.assertEqual(sticker_freq, result) # Restore the original frequency geopm_test_launcher.geopmwrite('{} {} {} {}'.format('CPU_FREQUENCY_CONTROL', write_domain, '0', str(old_freq))), if __name__ == '__main__': unittest.main()
[]
[]
[]
[]
[]
python
0
0
models/redis.go
package models import ( "context" "fmt" "os" "github.com/go-redis/redis/v8" ) var Rdb *redis.Client // open redis connection func RedisInit() { Rdb = redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%s", os.Getenv("redis_host"), os.Getenv("redis_port")), }) pong, err := Rdb.Ping(context.TODO()).Result() fmt.Println("Redis is responding :: ", pong, err) }
[ "\"redis_host\"", "\"redis_port\"" ]
[]
[ "redis_host", "redis_port" ]
[]
["redis_host", "redis_port"]
go
2
0
doc/source/conf.py
# -*- coding: utf-8 -*- # # Zaqar documentation build configuration file, created by # sphinx-quickstart on Sat May 1 15:17:47 2010. # # This file is execfile()d with the current directory set # to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import subprocess import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../')) sys.path.insert(0, os.path.abspath('../')) sys.path.insert(0, os.path.abspath('./')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') # or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.graphviz', 'oslosphinx', ] # autodoc generation is a bit aggressive and a nuisance # when doing heavy text edit cycles. Execute "export SPHINX_DEBUG=1" # in your terminal to disable todo_include_todos = True # Add any paths that contain templates here, relative to this directory. # Changing the path so that the Hudson build output contains GA code # and the source docs do not contain the code so local, offline sphinx builds # are "clean." templates_path = [] if os.getenv('HUDSON_PUBLISH_DOCS'): templates_path = ['_ga', '_templates'] else: templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'zaqar' copyright = u'2010-present, OpenStack Foundation' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # from zaqar.version import version_info # The full version, including alpha/beta/rc tags. release = version_info.release_string() # The short X.Y version. version = version_info.version_string() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. unused_docs = [ 'api_ext/rst_extension_template', 'installer', ] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = [] # The reST default role (used for this markup: `text`) to use # for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. modindex_common_prefix = ['zaqar.'] # -- Options for man page output ---------------------------------------------- # Grouping the document tree for man pages. # List of tuples 'sourcefile', 'target', u'title', u'Authors name', 'manual' # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme_path = ["."] # html_theme = '_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local", "-n1"] html_last_updated_fmt = subprocess.Popen(git_cmd, stdout=subprocess.PIPE).communicate()[0] # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'zaqardoc' # -- Options for LaTeX output ------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'Zaqar.tex', u'Zaqar Documentation', u'Anso Labs, LLC', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
[]
[]
[ "HUDSON_PUBLISH_DOCS" ]
[]
["HUDSON_PUBLISH_DOCS"]
python
1
0
entity_extractor/app.py
import json import hashlib import os import boto3 import logging import spacy import redis # Set up logger logger = logging.getLogger() logger.setLevel(logging.INFO) def get_redis(): redis_config = { "host": os.environ['REDIS_ENDPOINT'], "port": 6379, "db": 0, "ssl": True, "ssl_cert_reqs": None } return redis.Redis(**redis_config) def lambda_handler(event, context): body = json.loads(event['body']) text_to_analyse = body['text'] logger.info("Analysing: {text}".format(text=text_to_analyse)) # Set up Redis configuration, check cache r = get_redis() hash_text = hashlib.md5(text_to_analyse.encode('utf-8')).hexdigest() entities = r.get(hash_text) cache_hit = True if entities == None: # Use spaCy to extract entities from our text nlp = spacy.load("en_core_web_sm") doc = nlp(text_to_analyse) entities = [[e.text, e.label_] for e in doc.ents] cache_hit = False # Update cache, expires in 1 hour r.set(hash_text, json.dumps(entities), ex=3600) else: # Entities stored in JSON in cache entities = json.loads(entities) # Put message on queue to be handled by another function queue_msg_body = json.dumps({ "hashed_key": hash_text, "entities": entities }) sqs = boto3.client('sqs', endpoint_url='https://sqs.{}.amazonaws.com/'.format(os.environ['REGION'])) sqs.send_message( QueueUrl="https://sqs.{}.amazonaws.com/{}/{}".format( os.environ['REGION'], os.environ['ACCOUNT_ID'], os.environ['QUEUE_NAME'] ), MessageBody=queue_msg_body) return { "statusCode": 200, "body": json.dumps({ "text": text_to_analyse, "entities": entities, "cache_hit": cache_hit }), }
[]
[]
[ "ACCOUNT_ID", "REDIS_ENDPOINT", "REGION", "QUEUE_NAME" ]
[]
["ACCOUNT_ID", "REDIS_ENDPOINT", "REGION", "QUEUE_NAME"]
python
4
0
test/test_helpers.py
# Copyright 2019-2020 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pathlib import subprocess import shutil import tempfile import unittest from ops.framework import Framework from ops.model import Model, _ModelBackend from ops.charm import CharmMeta from ops.storage import SQLiteStorage def fake_script(test_case, name, content): if not hasattr(test_case, 'fake_script_path'): fake_script_path = tempfile.mkdtemp('-fake_script') os.environ['PATH'] = '{}:{}'.format(fake_script_path, os.environ["PATH"]) def cleanup(): shutil.rmtree(fake_script_path) os.environ['PATH'] = os.environ['PATH'].replace(fake_script_path + ':', '') test_case.addCleanup(cleanup) test_case.fake_script_path = pathlib.Path(fake_script_path) template_args = { 'name': name, 'path': test_case.fake_script_path, 'content': content, } with (test_case.fake_script_path / name).open('wt') as f: # Before executing the provided script, dump the provided arguments in calls.txt. # ASCII 1E is RS 'record separator', and 1C is FS 'file separator', which seem appropriate. f.write('''#!/bin/sh {{ printf {name}; printf "\\036%s" "$@"; printf "\\034"; }} >> {path}/calls.txt {content}'''.format_map(template_args)) os.chmod(str(test_case.fake_script_path / name), 0o755) def fake_script_calls(test_case, clear=False): try: with (test_case.fake_script_path / 'calls.txt').open('r+t') as f: calls = [line.split('\x1e') for line in f.read().split('\x1c')[:-1]] if clear: f.truncate(0) return calls except FileNotFoundError: return [] class FakeScriptTest(unittest.TestCase): def test_fake_script_works(self): fake_script(self, 'foo', 'echo foo runs') fake_script(self, 'bar', 'echo bar runs') output = subprocess.getoutput('foo a "b c "; bar "d e" f') self.assertEqual(output, 'foo runs\nbar runs') self.assertEqual(fake_script_calls(self), [ ['foo', 'a', 'b c '], ['bar', 'd e', 'f'], ]) def test_fake_script_clear(self): fake_script(self, 'foo', 'echo foo runs') output = subprocess.getoutput('foo a "b c"') self.assertEqual(output, 'foo runs') self.assertEqual(fake_script_calls(self, clear=True), [['foo', 'a', 'b c']]) fake_script(self, 'bar', 'echo bar runs') output = subprocess.getoutput('bar "d e" f') self.assertEqual(output, 'bar runs') self.assertEqual(fake_script_calls(self, clear=True), [['bar', 'd e', 'f']]) self.assertEqual(fake_script_calls(self, clear=True), []) class BaseTestCase(unittest.TestCase): def create_framework(self, *, model=None, tmpdir=None): """Create a Framework object. By default operate in-memory; pass a temporary directory via the 'tmpdir' parameter if you whish to instantiate several frameworks sharing the same dir (e.g. for storing state). """ if tmpdir is None: data_fpath = ":memory:" charm_dir = 'non-existant' else: data_fpath = tmpdir / "framework.data" charm_dir = tmpdir framework = Framework(SQLiteStorage(data_fpath), charm_dir, meta=None, model=model) self.addCleanup(framework.close) return framework def create_model(self): """Create a Model object.""" backend = _ModelBackend(unit_name='myapp/0') meta = CharmMeta() model = Model(meta, backend) return model
[]
[]
[ "PATH" ]
[]
["PATH"]
python
1
0
ipfs-gateway/src/io_gateway/robonomics.py
import os import typing as tp from loguru import logger from robonomicsinterface import RobonomicsInterface DATALOG_ENABLED: bool = bool(os.getenv("ROBONOMICS_ENABLE_DATALOG", False)) ROBONOMICS_ACCOUNT_SEED: str = os.getenv("ROBONOMICS_ACCOUNT_SEED", "") ROBONOMICS_CLIENT: tp.Optional[RobonomicsInterface] = None if DATALOG_ENABLED: assert ROBONOMICS_ACCOUNT_SEED, "Datalog is enabled, but the seed is missing. Export it to ROBONOMICS_ACCOUNT_SEED." ROBONOMICS_CLIENT = RobonomicsInterface( seed=ROBONOMICS_ACCOUNT_SEED, remote_ws=os.getenv("ROBONOMICS_SUBSTRATE_NODE_URL") ) def post_to_datalog(content: str) -> None: """echo provided string to the Robonomics datalog""" logger.info(f"Posting data '{content}' to Robonomics datalog") assert ROBONOMICS_CLIENT txn_hash: str = ROBONOMICS_CLIENT.record_datalog(content) logger.info(f"Data '{content}' has been posted to the Robonomics datalog. {txn_hash=}")
[]
[]
[ "ROBONOMICS_ACCOUNT_SEED", "ROBONOMICS_ENABLE_DATALOG", "ROBONOMICS_SUBSTRATE_NODE_URL" ]
[]
["ROBONOMICS_ACCOUNT_SEED", "ROBONOMICS_ENABLE_DATALOG", "ROBONOMICS_SUBSTRATE_NODE_URL"]
python
3
0
integration-cli/docker_cli_daemon_test.go
// +build linux package main import ( "bufio" "bytes" "context" "crypto/tls" "crypto/x509" "encoding/json" "fmt" "io" "io/ioutil" "net" "os" "os/exec" "path" "path/filepath" "regexp" "strconv" "strings" "sync" "testing" "time" "github.com/cloudflare/cfssl/helpers" "github.com/creack/pty" "github.com/docker/docker/api/types" "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/opts" "github.com/docker/docker/pkg/mount" testdaemon "github.com/docker/docker/testutil/daemon" units "github.com/docker/go-units" "github.com/docker/libnetwork/iptables" "github.com/docker/libtrust" "golang.org/x/sys/unix" "gotest.tools/assert" "gotest.tools/icmd" "gotest.tools/poll" ) const containerdSocket = "/var/run/docker/containerd/containerd.sock" // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon // command. Remove this test when we remove this. func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *testing.T) { cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug") err := cmd.Start() go cmd.Wait() assert.NilError(c, err, "could not start daemon using 'docker daemon'") assert.NilError(c, cmd.Process.Kill()) } func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *testing.T) { s.d.StartWithBusybox(c) cli.Docker( cli.Args("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"), cli.Daemon(s.d), ).Assert(c, icmd.Success) cli.Docker( cli.Args("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"), cli.Daemon(s.d), ).Assert(c, icmd.Success) testRun := func(m map[string]bool, prefix string) { var format string for cont, shouldRun := range m { out := cli.Docker(cli.Args("ps"), cli.Daemon(s.d)).Assert(c, icmd.Success).Combined() if shouldRun { format = "%scontainer %q is not running" } else { format = "%scontainer %q is running" } if shouldRun != strings.Contains(out, cont) { c.Fatalf(format, prefix, cont) } } } testRun(map[string]bool{"top1": true, "top2": true}, "") s.d.Restart(c) testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") } func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *testing.T) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { c.Fatal(err, out) } s.d.Restart(c) if out, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { c.Fatal(err, out) } out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1") assert.NilError(c, err, out) if _, err := inspectMountPointJSON(out, "/foo"); err != nil { c.Fatalf("Expected volume to exist: /foo, error: %v\n", err) } } // #11008 func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top") assert.NilError(c, err, "run top1: %v", out) out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top") assert.NilError(c, err, "run top2: %v", out) out, err = s.d.Cmd("run", "-d", "--name", "exit", "--restart", "unless-stopped", "busybox:latest", "false") assert.NilError(c, err, "run exit: %v", out) testRun := func(m map[string]bool, prefix string) { var format string for name, shouldRun := range m { out, err := s.d.Cmd("ps") assert.Assert(c, err == nil, "run ps: %v", out) if shouldRun { format = "%scontainer %q is not running" } else { format = "%scontainer %q is running" } assert.Equal(c, strings.Contains(out, name), shouldRun, fmt.Sprintf(format, prefix, name)) } } // both running testRun(map[string]bool{"top1": true, "top2": true, "exit": true}, "") out, err = s.d.Cmd("stop", "exit") assert.NilError(c, err, out) out, err = s.d.Cmd("stop", "top1") assert.NilError(c, err, out) out, err = s.d.Cmd("stop", "top2") assert.NilError(c, err, out) // both stopped testRun(map[string]bool{"top1": false, "top2": false, "exit": false}, "") s.d.Restart(c) // restart=always running testRun(map[string]bool{"top1": true, "top2": false, "exit": false}, "After daemon restart: ") out, err = s.d.Cmd("start", "top2") assert.NilError(c, err, "start top2: %v", out) out, err = s.d.Cmd("start", "exit") assert.NilError(c, err, "start exit: %v", out) s.d.Restart(c) // both running testRun(map[string]bool{"top1": true, "top2": true, "exit": true}, "After second daemon restart: ") } func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false") assert.NilError(c, err, "run top1: %v", out) // wait test1 to stop hostArgs := []string{"--host", s.d.Sock()} err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...) assert.NilError(c, err, "test1 should exit but not") // record last start time out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") assert.NilError(c, err, "out: %v", out) lastStartTime := out s.d.Restart(c) // test1 shouldn't restart at all err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...) assert.NilError(c, err, "test1 should exit but not") // make sure test1 isn't restarted when daemon restart // if "StartAt" time updates, means test1 was once restarted. out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") assert.NilError(c, err, "out: %v", out) assert.Equal(c, out, lastStartTime, "test1 shouldn't start after daemon restarts") } func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *testing.T) { s.d.Start(c, "--iptables=false") } // Make sure we cannot shrink base device at daemon restart. func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *testing.T) { testRequires(c, Devicemapper) s.d.Start(c) oldBasesizeBytes := getBaseDeviceSize(c, s.d) var newBasesizeBytes int64 = 1073741824 // 1GB in bytes if newBasesizeBytes < oldBasesizeBytes { err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) assert.Assert(c, err != nil, "daemon should not have started as new base device size is less than existing base device size: %v", err) // 'err != nil' is expected behaviour, no new daemon started, // so no need to stop daemon. if err != nil { return } } s.d.Stop(c) } // Make sure we can grow base device at daemon restart. func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *testing.T) { testRequires(c, Devicemapper) s.d.Start(c) oldBasesizeBytes := getBaseDeviceSize(c, s.d) var newBasesizeBytes int64 = 53687091200 // 50GB in bytes if newBasesizeBytes < oldBasesizeBytes { c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes)))) } err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) assert.Assert(c, err == nil, "we should have been able to start the daemon with increased base device size: %v", err) basesizeAfterRestart := getBaseDeviceSize(c, s.d) newBasesize, err := convertBasesize(newBasesizeBytes) assert.Assert(c, err == nil, "Error in converting base device size: %v", err) assert.Equal(c, newBasesize, basesizeAfterRestart, "Basesize passed is not equal to Basesize set") s.d.Stop(c) } func getBaseDeviceSize(c *testing.T, d *daemon.Daemon) int64 { info := d.Info(c) for _, statusLine := range info.DriverStatus { key, value := statusLine[0], statusLine[1] if key == "Base Device Size" { return parseDeviceSize(c, value) } } c.Fatal("failed to parse Base Device Size from info") return int64(0) } func parseDeviceSize(c *testing.T, raw string) int64 { size, err := units.RAMInBytes(strings.TrimSpace(raw)) assert.NilError(c, err) return size } func convertBasesize(basesizeBytes int64) (int64, error) { basesize := units.HumanSize(float64(basesizeBytes)) basesize = strings.Trim(basesize, " ")[:len(basesize)-3] basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64) if err != nil { return 0, err } return int64(basesizeFloat) * 1024 * 1024 * 1024, nil } // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and // no longer has an IP associated, we should gracefully handle that case and associate // an IP with it rather than fail daemon start func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *testing.T) { // rather than depending on brctl commands to verify docker0 is created and up // let's start the daemon and stop it, and then make a modification to run the // actual test s.d.Start(c) s.d.Stop(c) // now we will remove the ip from docker0 and then try starting the daemon icmd.RunCommand("ip", "addr", "flush", "dev", "docker0").Assert(c, icmd.Success) if err := s.d.StartWithError(); err != nil { warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix" c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning) } } func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *testing.T) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } ipTablesSearchString := "tcp dpt:80" // get output from iptables with container running verifyIPTablesContains(c, ipTablesSearchString) s.d.Stop(c) // get output from iptables after restart verifyIPTablesDoesNotContains(c, ipTablesSearchString) } func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *testing.T) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } // get output from iptables with container running ipTablesSearchString := "tcp dpt:80" verifyIPTablesContains(c, ipTablesSearchString) s.d.Restart(c) // make sure the container is not running runningOut, err := s.d.Cmd("inspect", "--format={{.State.Running}}", "top") if err != nil { c.Fatalf("Could not inspect on container: %s, %v", runningOut, err) } if strings.TrimSpace(runningOut) != "true" { c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut)) } // get output from iptables after restart verifyIPTablesContains(c, ipTablesSearchString) } func verifyIPTablesContains(c *testing.T, ipTablesSearchString string) { result := icmd.RunCommand("iptables", "-nvL") result.Assert(c, icmd.Success) if !strings.Contains(result.Combined(), ipTablesSearchString) { c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, result.Combined()) } } func verifyIPTablesDoesNotContains(c *testing.T, ipTablesSearchString string) { result := icmd.RunCommand("iptables", "-nvL") result.Assert(c, icmd.Success) if strings.Contains(result.Combined(), ipTablesSearchString) { c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, result.Combined()) } } // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge // has the fe80::1 address and that a container is assigned a link-local address func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *testing.T) { testRequires(c, IPv6) setupV6(c) defer teardownV6(c) s.d.StartWithBusybox(c, "--ipv6") iface, err := net.InterfaceByName("docker0") if err != nil { c.Fatalf("Error getting docker0 interface: %v", err) } addrs, err := iface.Addrs() if err != nil { c.Fatalf("Error getting addresses for docker0 interface: %v", err) } var found bool expected := "fe80::1/64" for i := range addrs { if addrs[i].String() == expected { found = true break } } if !found { c.Fatalf("Bridge does not have an IPv6 Address") } if out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil { c.Fatalf("Could not run container: %s, %v", out, err) } out, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } out = strings.Trim(out, " \r\n'") if ip := net.ParseIP(out); ip == nil { c.Fatalf("Container should have a link-local IPv6 address") } out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } out = strings.Trim(out, " \r\n'") if ip := net.ParseIP(out); ip != nil { c.Fatalf("Container should not have a global IPv6 address: %v", out) } } // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR // that running containers are given a link-local and global IPv6 address func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *testing.T) { // IPv6 setup is messing with local bridge address. testRequires(c, testEnv.IsLocalDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100") out, err := s.d.Cmd("run", "-d", "--name=ipv6test", "busybox:latest", "top") assert.NilError(c, err, "Could not run container: %s, %v", out, err) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") assert.NilError(c, err, out) out = strings.Trim(out, " \r\n'") ip := net.ParseIP(out) assert.Assert(c, ip != nil, "Container should have a global IPv6 address") out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test") assert.NilError(c, err, out) assert.Equal(c, strings.Trim(out, " \r\n'"), "2001:db8:2::100", "Container should have a global IPv6 gateway") } // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *testing.T) { // IPv6 setup is messing with local bridge address. testRequires(c, testEnv.IsLocalDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64") out, err := s.d.Cmd("run", "-d", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox", "top") assert.NilError(c, err, out) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") assert.NilError(c, err, out) assert.Equal(c, strings.Trim(out, " \r\n'"), "2001:db8:1::aabb:ccdd:eeff") } // TestDaemonIPv6HostMode checks that when the running a container with // network=host the host ipv6 addresses are not removed func (s *DockerDaemonSuite) TestDaemonIPv6HostMode(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64") out, err := s.d.Cmd("run", "-d", "--name=hostcnt", "--network=host", "busybox:latest", "top") assert.NilError(c, err, "Could not run container: %s, %v", out, err) out, err = s.d.Cmd("exec", "hostcnt", "ip", "-6", "addr", "show", "docker0") assert.NilError(c, err, out) assert.Assert(c, strings.Contains(strings.Trim(out, " \r\n'"), "2001:db8:2::1")) } func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *testing.T) { assert.Assert(c, s.d.StartWithError("--log-level=bogus") != nil, "Daemon shouldn't start with wrong log level") } func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *testing.T) { s.d.Start(c, "--log-level=debug") content, err := s.d.ReadLogFile() assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *testing.T) { // we creating new daemons to create new logFile s.d.Start(c, "--log-level=fatal") content, err := s.d.ReadLogFile() assert.NilError(c, err) if strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagD(c *testing.T) { s.d.Start(c, "-D") content, err := s.d.ReadLogFile() assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *testing.T) { s.d.Start(c, "--debug") content, err := s.d.ReadLogFile() assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *testing.T) { s.d.Start(c, "--debug", "--log-level=fatal") content, err := s.d.ReadLogFile() assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *testing.T) { listeningPorts := [][]string{ {"0.0.0.0", "0.0.0.0", "5678"}, {"127.0.0.1", "127.0.0.1", "1234"}, {"localhost", "127.0.0.1", "1235"}, } cmdArgs := make([]string, 0, len(listeningPorts)*2) for _, hostDirective := range listeningPorts { cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2])) } s.d.StartWithBusybox(c, cmdArgs...) for _, hostDirective := range listeningPorts { output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") if err == nil { c.Fatalf("Container should not start, expected port already allocated error: %q", output) } else if !strings.Contains(output, "port is already allocated") { c.Fatalf("Expected port is already allocated error: %q", output) } } } func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *testing.T) { // TODO: skip or update for Windows daemon os.Remove("/etc/docker/key.json") s.d.Start(c) s.d.Stop(c) k, err := libtrust.LoadKeyFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error opening key file") } kid := k.KeyID() // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF) if len(kid) != 59 { c.Fatalf("Bad key ID: %s", kid) } } // GH#11320 - verify that the daemon exits on failure properly // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *testing.T) { // attempt to start daemon with incorrect flags (we know -b and --bip conflict) if err := s.d.StartWithError("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { // verify we got the right error if !strings.Contains(err.Error(), "daemon exited") { c.Fatalf("Expected daemon not to start, got %v", err) } // look in the log and make sure we got the message that daemon is shutting down icmd.RunCommand("grep", "failed to start daemon", s.d.LogFileName()).Assert(c, icmd.Success) } else { // if we didn't get an error and the daemon is running, this is a failure c.Fatal("Conflicting options should cause the daemon to error out with a failure") } } func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *testing.T) { d := s.d err := d.StartWithError("--bridge", "nosuchbridge") assert.ErrorContains(c, err, "", `--bridge option with an invalid bridge should cause the daemon to fail`) defer d.Restart(c) bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName) ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) out, err := d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top") assert.NilError(c, err, out) containerIP := d.FindContainerIP(c, "ExtContainer") ip := net.ParseIP(containerIP) assert.Assert(c, bridgeIPNet.Contains(ip), "Container IP-Address must be in the same subnet range : %s", containerIP) } func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *testing.T) { // start with bridge none d := s.d d.StartWithBusybox(c, "--bridge", "none") defer d.Restart(c) // verify docker0 iface is not there icmd.RunCommand("ifconfig", "docker0").Assert(c, icmd.Expected{ ExitCode: 1, Error: "exit status 1", Err: "Device not found", }) // verify default "bridge" network is not there out, err := d.Cmd("network", "inspect", "bridge") assert.ErrorContains(c, err, "", `"bridge" network should not be present if daemon started with --bridge=none`) assert.Assert(c, strings.Contains(out, "No such network")) } func createInterface(c *testing.T, ifType string, ifName string, ipNet string) { icmd.RunCommand("ip", "link", "add", "name", ifName, "type", ifType).Assert(c, icmd.Success) icmd.RunCommand("ifconfig", ifName, ipNet, "up").Assert(c, icmd.Success) } func deleteInterface(c *testing.T, ifName string) { icmd.RunCommand("ip", "link", "delete", ifName).Assert(c, icmd.Success) icmd.RunCommand("iptables", "-t", "nat", "--flush").Assert(c, icmd.Success) icmd.RunCommand("iptables", "--flush").Assert(c, icmd.Success) } func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *testing.T) { // TestDaemonBridgeIP Steps // 1. Delete the existing docker0 Bridge // 2. Set --bip daemon configuration and start the new Docker Daemon // 3. Check if the bip config has taken effect using ifconfig and iptables commands // 4. Launch a Container and make sure the IP-Address is in the expected subnet // 5. Delete the docker0 Bridge // 6. Restart the Docker Daemon (via deferred action) // This Restart takes care of bringing docker0 interface back to auto-assigned IP defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1/24" ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) d.StartWithBusybox(c, "--bip", bridgeIP) defer d.Restart(c) ifconfigSearchString := ip.String() icmd.RunCommand("ifconfig", defaultNetworkBridge).Assert(c, icmd.Expected{ Out: ifconfigSearchString, }) ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) out, err := d.Cmd("run", "-d", "--name", "test", "busybox", "top") assert.NilError(c, err, out) containerIP := d.FindContainerIP(c, "test") ip = net.ParseIP(containerIP) assert.Equal(c, bridgeIPNet.Contains(ip), true, fmt.Sprintf("Container IP-Address must be in the same subnet range : %s", containerIP)) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *testing.T) { s.d.Start(c) defer s.d.Restart(c) s.d.Stop(c) // now we will change the docker0's IP and then try starting the daemon bridgeIP := "192.169.100.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) icmd.RunCommand("ifconfig", "docker0", bridgeIP).Assert(c, icmd.Success) s.d.Start(c, "--bip", bridgeIP) // check if the iptables contains new bridgeIP MASQUERADE rule ipTablesSearchString := bridgeIPNet.String() icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ Out: ipTablesSearchString, }) } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *testing.T) { d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"} d.StartWithBusybox(c, args...) defer d.Restart(c) for i := 0; i < 4; i++ { cName := "Container" + strconv.Itoa(i) out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") if err != nil { assert.Assert(c, strings.Contains(out, "no available IPv4 addresses"), "Could not run a Container : %s %s", err.Error(), out) } } } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *testing.T) { d := s.d bridgeName := "external-bridge" bridgeIP := "10.2.2.1/16" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bip", bridgeIP, "--fixed-cidr", "10.2.2.0/24") defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "--name", "bb", "busybox", "top") assert.NilError(c, err, out) defer d.Cmd("stop", "bb") out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") assert.NilError(c, err) assert.Equal(c, out, "10.2.2.0\n") out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") assert.NilError(c, err, out) assert.Equal(c, out, "10.2.2.2\n") } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *testing.T) { d := s.d bridgeName := "external-bridge" bridgeIP := "172.27.42.1/16" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--fixed-cidr", bridgeIP) defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "busybox", "top") assert.NilError(c, err, out) cid1 := strings.TrimSpace(out) defer d.Cmd("stop", cid1) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *testing.T) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1" bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) d.StartWithBusybox(c, "--bip", bridgeIPNet) defer d.Restart(c) expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") assert.NilError(c, err, out) assert.Equal(c, strings.Contains(out, expectedMessage), true, fmt.Sprintf("Implicit default gateway should be bridge IP %s, but default route was '%s'", bridgeIP, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *testing.T) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIP := "192.169.1.1" bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) gatewayIP := "192.169.1.254" d.StartWithBusybox(c, "--bip", bridgeIPNet, "--default-gateway", gatewayIP) defer d.Restart(c) expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") assert.NilError(c, err, out) assert.Equal(c, strings.Contains(out, expectedMessage), true, fmt.Sprintf("Explicit default gateway should be %s, but default route was '%s'", gatewayIP, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainerSubnet(c *testing.T) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) // Program a custom default gateway outside of the container subnet, daemon should accept it and start s.d.StartWithBusybox(c, "--bip", "172.16.0.10/16", "--fixed-cidr", "172.16.1.0/24", "--default-gateway", "172.16.0.254") deleteInterface(c, defaultNetworkBridge) s.d.Restart(c) } func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *testing.T) { // Start daemon without docker0 bridge defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) discoveryBackend := "consul://consuladdr:consulport/some/path" s.d.Start(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) // Start daemon with docker0 bridge result := icmd.RunCommand("ifconfig", defaultNetworkBridge) result.Assert(c, icmd.Success) s.d.Restart(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) } func (s *DockerDaemonSuite) TestDaemonIP(c *testing.T) { d := s.d ipStr := "192.170.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) args := []string{"--ip", ip.String()} d.StartWithBusybox(c, args...) defer d.Restart(c) out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") assert.Assert(c, err != nil, "Running a container must fail with an invalid --ip option") assert.Equal(c, strings.Contains(out, "Error starting userland proxy"), true) ifName := "dummy" createInterface(c, "dummy", ifName, ipStr) defer deleteInterface(c, ifName) _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") assert.NilError(c, err, out) result := icmd.RunCommand("iptables", "-t", "nat", "-nvL") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String()) matched, _ := regexp.MatchString(regex, result.Combined()) assert.Equal(c, matched, true, fmt.Sprintf("iptables output should have contained %q, but was %q", regex, result.Combined())) } func (s *DockerDaemonSuite) TestDaemonICCPing(c *testing.T) { testRequires(c, bridgeNfIptables) d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer d.Restart(c) result := icmd.RunCommand("iptables", "-nvL", "FORWARD") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, result.Combined()) assert.Equal(c, matched, true, fmt.Sprintf("iptables output should have contained %q, but was %q", regex, result.Combined())) // Pinging another container must fail with --icc=false pingContainers(c, d, true) ipStr := "192.171.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) ifName := "icc-dummy" createInterface(c, "dummy", ifName, ipStr) // But, Pinging external or a Host interface must succeed pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd} out, err := d.Cmd(runArgs...) assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *testing.T) { d := s.d bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer d.Restart(c) result := icmd.RunCommand("iptables", "-nvL", "FORWARD") result.Assert(c, icmd.Success) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, result.Combined()) assert.Equal(c, matched, true, fmt.Sprintf("iptables output should have contained %q, but was %q", regex, result.Combined())) out, err := d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567") assert.NilError(c, err, out) out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567") assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *testing.T) { bridgeName := "external-bridge" bridgeIP := "192.169.1.1/24" createInterface(c, "bridge", bridgeName, bridgeIP) defer deleteInterface(c, bridgeName) s.d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") defer s.d.Restart(c) out, err := s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top") assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top") assert.NilError(c, err, out) childIP := s.d.FindContainerIP(c, "child") parentIP := s.d.FindContainerIP(c, "parent") sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"} destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"} if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules not found") } s.d.Cmd("rm", "--link", "parent/http") if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules should be removed when unlink") } s.d.Cmd("kill", "child") s.d.Cmd("kill", "parent") } func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *testing.T) { s.d.StartWithBusybox(c, "--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024") out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") if err != nil { c.Fatal(err, out) } outArr := strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile := strings.TrimSpace(outArr[0]) nproc := strings.TrimSpace(outArr[1]) if nofile != "42" { c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("expected `ulimit -p` to be 2048, got: %s", nproc) } // Now restart daemon with a new default s.d.Restart(c, "--default-ulimit", "nofile=43") out, err = s.d.Cmd("start", "-a", "test") if err != nil { c.Fatal(err, out) } outArr = strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile = strings.TrimSpace(outArr[0]) nproc = strings.TrimSpace(outArr[1]) if nofile != "43" { c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("expected `ulimit -p` to be 2048, got: %s", nproc) } } // #11315 func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *testing.T) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("rename", "test", "test2"); err != nil { c.Fatal(err, out) } s.d.Restart(c) if out, err := s.d.Cmd("start", "test2"); err != nil { c.Fatal(err, out) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") assert.NilError(c, err, out) id, err := s.d.GetIDByName("test") assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } defer f.Close() var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name=test", "--log-driver=none", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *testing.T) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *testing.T) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "--log-driver=json-file", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } defer f.Close() var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *testing.T) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") assert.NilError(c, err, out) out, err = s.d.Cmd("logs", "test") assert.Assert(c, err != nil, "Logs should fail with 'none' driver") expected := `configured logging driver does not support reading` assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerDaemonSuite) TestDaemonLoggingDriverShouldBeIgnoredForBuild(c *testing.T) { s.d.StartWithBusybox(c, "--log-driver=splunk") result := cli.BuildCmd(c, "busyboxs", cli.Daemon(s.d), build.WithDockerfile(` FROM busybox RUN echo foo`), build.WithoutCache, ) comment := fmt.Sprintf("Failed to build image. output %s, exitCode %d, err %v", result.Combined(), result.ExitCode, result.Error) assert.Assert(c, result.Error == nil, comment) assert.Equal(c, result.ExitCode, 0, comment) assert.Assert(c, strings.Contains(result.Combined(), "foo"), comment) } func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *testing.T) { dir, err := ioutil.TempDir("", "socket-cleanup-test") if err != nil { c.Fatal(err) } defer os.RemoveAll(dir) sockPath := filepath.Join(dir, "docker.sock") s.d.Start(c, "--host", "unix://"+sockPath) if _, err := os.Stat(sockPath); err != nil { c.Fatal("socket does not exist") } s.d.Stop(c) if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { c.Fatal("unix socket is not cleaned up") } } func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *testing.T) { type Config struct { Crv string `json:"crv"` D string `json:"d"` Kid string `json:"kid"` Kty string `json:"kty"` X string `json:"x"` Y string `json:"y"` } os.Remove("/etc/docker/key.json") s.d.Start(c) s.d.Stop(c) config := &Config{} bytes, err := ioutil.ReadFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error reading key.json file: %s", err) } // byte[] to Data-Struct if err := json.Unmarshal(bytes, &config); err != nil { c.Fatalf("Error Unmarshal: %s", err) } // replace config.Kid with the fake value config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4" // NEW Data-Struct to byte[] newBytes, err := json.Marshal(&config) if err != nil { c.Fatalf("Error Marshal: %s", err) } // write back if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil { c.Fatalf("Error ioutil.WriteFile: %s", err) } defer os.Remove("/etc/docker/key.json") if err := s.d.StartWithError(); err == nil { c.Fatalf("It should not be successful to start daemon with wrong key: %v", err) } content, err := s.d.ReadLogFile() assert.Assert(c, err == nil) if !strings.Contains(string(content), "Public Key ID does not match") { c.Fatalf("Missing KeyID message from daemon logs: %s", string(content)) } } func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat") if err != nil { c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out) } containerID := strings.TrimSpace(out) if out, err := s.d.Cmd("kill", containerID); err != nil { c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out) } s.d.Restart(c) errchan := make(chan error) go func() { if out, err := s.d.Cmd("wait", containerID); err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } close(errchan) }() select { case <-time.After(5 * time.Second): c.Fatal("Waiting on a stopped (killed) container timed out") case err := <-errchan: if err != nil { c.Fatal(err) } } } // TestHTTPSInfo connects via two-way authenticated HTTPS to the info endpoint func (s *DockerDaemonSuite) TestHTTPSInfo(c *testing.T) { const ( testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "info", } out, err := s.d.Cmd(args...) if err != nil { c.Fatalf("Error Occurred: %s and output: %s", err, out) } } // TestHTTPSRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints. // https://github.com/docker/docker/issues/19280 func (s *DockerDaemonSuite) TestHTTPSRun(c *testing.T) { const ( testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.StartWithBusybox(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "run", "busybox", "echo", "TLS response", } out, err := s.d.Cmd(args...) if err != nil { c.Fatalf("Error Occurred: %s and output: %s", err, out) } if !strings.Contains(out, "TLS response") { c.Fatalf("expected output to include `TLS response`, got %v", out) } } // TestTLSVerify verifies that --tlsverify=false turns on tls func (s *DockerDaemonSuite) TestTLSVerify(c *testing.T) { out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput() if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") { c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out)) } } // TestHTTPSInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint // by using a rogue client certificate and checks that it fails with the expected error. func (s *DockerDaemonSuite) TestHTTPSInfoRogueCert(c *testing.T) { const ( errBadCertificate = "bad certificate" testDaemonHTTPSAddr = "tcp://localhost:4271" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) args := []string{ "--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem", "info", } out, err := s.d.Cmd(args...) if err == nil || !strings.Contains(out, errBadCertificate) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) } } // TestHTTPSInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint // which provides a rogue server certificate and checks that it fails with the expected error func (s *DockerDaemonSuite) TestHTTPSInfoRogueServerCert(c *testing.T) { const ( errCaUnknown = "x509: certificate signed by unknown authority" testDaemonRogueHTTPSAddr = "tcp://localhost:4272" ) s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem", "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHTTPSAddr) args := []string{ "--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem", "info", } out, err := s.d.Cmd(args...) if err == nil || !strings.Contains(out, errCaUnknown) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) } } func pingContainers(c *testing.T, d *daemon.Daemon, expectFailure bool) { var dargs []string if d != nil { dargs = []string{"--host", d.Sock()} } args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top") dockerCmd(c, args...) args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c") pingCmd := "ping -c 1 %s -W 1" args = append(args, fmt.Sprintf(pingCmd, "alias1")) _, _, err := dockerCmdWithError(args...) if expectFailure { assert.ErrorContains(c, err, "") } else { assert.NilError(c, err) } args = append(dargs, "rm", "-f", "container1") dockerCmd(c, args...) } func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *testing.T) { s.d.StartWithBusybox(c) socket := filepath.Join(s.d.Folder, "docker.sock") out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox") assert.NilError(c, err, "Output: %s", out) s.d.Restart(c) } // os.Kill should kill daemon ungracefully, leaving behind container mounts. // A subsequent daemon restart should clean up said mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *testing.T) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) // If there are no mounts with container id visible from the host // (as those are in container's own mount ns), there is nothing // to check here and the test should be skipped. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") assert.NilError(c, err, "Output: %s", mountOut) if !strings.Contains(string(mountOut), id) { d.Stop(c) c.Skip("no container mounts visible in host ns") } // kill the daemon assert.NilError(c, d.Kill()) // kill the container icmd.RunCommand(ctrBinary, "--address", containerdSocket, "--namespace", d.ContainersNamespace(), "tasks", "kill", id).Assert(c, icmd.Success) // restart daemon. d.Restart(c) // Now, container mounts should be gone. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") assert.NilError(c, err, "Output: %s", mountOut) assert.Assert(c, !strings.Contains(string(mountOut), id), "%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) d.Stop(c) } // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *testing.T) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) // Send SIGINT and daemon should clean up assert.NilError(c, d.Signal(os.Interrupt)) // Wait for the daemon to stop. assert.NilError(c, <-d.Wait) mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") assert.NilError(c, err, "Output: %s", mountOut) assert.Assert(c, !strings.Contains(string(mountOut), id), "%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *testing.T) { s.d.StartWithBusybox(t) if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil { t.Fatal(out, err) } s.d.Restart(t) // Container 'test' should be removed without error if out, err := s.d.Cmd("rm", "test"); err != nil { t.Fatal(out, err) } } func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top") if err != nil { c.Fatal(out, err) } // Get sandbox key via inspect out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } fileName := strings.Trim(out, " \r\n'") if out, err := s.d.Cmd("stop", "netns"); err != nil { c.Fatal(out, err) } // Test if the file still exists icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ Out: fileName, }) // Remove the container and restart the daemon if out, err := s.d.Cmd("rm", "netns"); err != nil { c.Fatal(out, err) } s.d.Restart(c) // Test again and see now the netns file does not exist icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ Err: "No such file or directory", ExitCode: 1, }) } // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored func (s *DockerDaemonSuite) TestDaemonTLSVerifyIssue13964(c *testing.T) { host := "tcp://localhost:4271" s.d.Start(c, "-H", host) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "-H", host, "info"}, Env: []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}, }).Assert(c, icmd.Expected{ ExitCode: 1, Err: "error during connect", }) } func setupV6(c *testing.T) { // Hack to get the right IPv6 address on docker0, which has already been created result := icmd.RunCommand("ip", "addr", "add", "fe80::1/64", "dev", "docker0") result.Assert(c, icmd.Success) } func teardownV6(c *testing.T) { result := icmd.RunCommand("ip", "addr", "del", "fe80::1/64", "dev", "docker0") result.Assert(c, icmd.Success) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") assert.NilError(c, err, out) id := strings.TrimSpace(out) out, err = s.d.Cmd("stop", id) assert.NilError(c, err, out) out, err = s.d.Cmd("wait", id) assert.NilError(c, err, out) out, err = s.d.Cmd("ps", "-q") assert.NilError(c, err, out) assert.Equal(c, out, "") s.d.Restart(c) out, err = s.d.Cmd("ps", "-q") assert.NilError(c, err, out) assert.Equal(c, strings.TrimSpace(out), id[:12]) } func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *testing.T) { s.d.StartWithBusybox(c, "--log-opt=max-size=1k") name := "logtest" out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top") assert.NilError(c, err, "Output: %s, err: %v", out, err) out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name) assert.NilError(c, err, "Output: %s", out) assert.Assert(c, strings.Contains(out, "max-size:1k")) assert.Assert(c, strings.Contains(out, "max-file:5")) out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name) assert.NilError(c, err, "Output: %s", out) assert.Equal(c, strings.TrimSpace(out), "json-file") } func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *testing.T) { s.d.StartWithBusybox(c) if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("pause", "test"); err != nil { c.Fatal(err, out) } s.d.Restart(c) errchan := make(chan error) go func() { out, err := s.d.Cmd("start", "test") if err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } name := strings.TrimSpace(out) if name != "test" { errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name) } close(errchan) }() select { case <-time.After(5 * time.Second): c.Fatal("Waiting on start a container timed out") case err := <-errchan: if err != nil { c.Fatal(err) } } } func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *testing.T) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox") assert.NilError(c, err, out) s.d.Restart(c) out, err = s.d.Cmd("volume", "rm", "test") assert.Assert(c, err != nil, "should not be able to remove in use volume after daemon restart") assert.Assert(c, strings.Contains(out, "in use")) } func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *testing.T) { s.d.Start(c) out, err := s.d.Cmd("volume", "create", "test") assert.NilError(c, err, out) s.d.Restart(c) out, err = s.d.Cmd("volume", "inspect", "test") assert.NilError(c, err, out) } // FIXME(vdemeester) should be a unit test func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *testing.T) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) assert.Assert(c, d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42") != nil) expected := "syslog-address should be in form proto://address" icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) } // FIXME(vdemeester) should be a unit test func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *testing.T) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) assert.Assert(c, d.StartWithError("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c") != nil) expected := "invalid fluentd-address corrupted:c: " icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) } // FIXME(vdemeester) Use a new daemon instance instead of the Suite one func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *testing.T) { s.d.UseDefaultHost = true defer func() { s.d.UseDefaultHost = false }() s.d.Start(c) } // FIXME(vdemeester) Use a new daemon instance instead of the Suite one func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *testing.T) { s.d.UseDefaultTLSHost = true defer func() { s.d.UseDefaultTLSHost = false }() s.d.Start(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem") // The client with --tlsverify should also use default host localhost:2376 tmpHost := os.Getenv("DOCKER_HOST") defer func() { os.Setenv("DOCKER_HOST", tmpHost) }() os.Setenv("DOCKER_HOST", "") out, _ := dockerCmd( c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "version", ) if !strings.Contains(out, "Server") { c.Fatalf("docker version should return information of server side") } // ensure when connecting to the server that only a single acceptable CA is requested contents, err := ioutil.ReadFile("fixtures/https/ca.pem") assert.NilError(c, err) rootCert, err := helpers.ParseCertificatePEM(contents) assert.NilError(c, err) rootPool := x509.NewCertPool() rootPool.AddCert(rootCert) var certRequestInfo *tls.CertificateRequestInfo conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort), &tls.Config{ RootCAs: rootPool, GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { certRequestInfo = cri cert, err := tls.LoadX509KeyPair("fixtures/https/client-cert.pem", "fixtures/https/client-key.pem") if err != nil { return nil, err } return &cert, nil }, }) assert.NilError(c, err) conn.Close() assert.Assert(c, certRequestInfo != nil) assert.Equal(c, len(certRequestInfo.AcceptableCAs), 1) assert.DeepEqual(c, certRequestInfo.AcceptableCAs[0], rootCert.RawSubject) } func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *testing.T) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) bridgeIP := "192.169.1.1" bridgeRange := bridgeIP + "/30" s.d.StartWithBusybox(c, "--bip", bridgeRange) defer s.d.Restart(c) var cont int for { contName := fmt.Sprintf("container%d", cont) _, err := s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2") if err != nil { // pool exhausted break } ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName) assert.Assert(c, err == nil, ip) assert.Assert(c, ip != bridgeIP) cont++ } } // Test daemon for no space left on device error func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, Network) testDir, err := ioutil.TempDir("", "no-space-left-on-device-test") assert.NilError(c, err) defer os.RemoveAll(testDir) assert.Assert(c, mount.MakeRShared(testDir) == nil) defer mount.Unmount(testDir) // create a 3MiB image (with a 2MiB ext4 fs) and mount it as graph root // Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:jessie (which is what the test suite runs under if run from the Makefile) dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=3 count=0") icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success) dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", "mkdir -p /test/test-mount/vfs && mount -n -t ext4 /test/testfs.img /test/test-mount/vfs") defer mount.Unmount(filepath.Join(testDir, "test-mount")) s.d.Start(c, "--storage-driver", "vfs", "--data-root", filepath.Join(testDir, "test-mount")) defer s.d.Stop(c) // pull a repository large enough to overfill the mounted filesystem pullOut, err := s.d.Cmd("pull", "debian:stretch") assert.Assert(c, err != nil, pullOut) assert.Assert(c, strings.Contains(pullOut, "no space left on device")) } // Test daemon restart with container links + auto restart func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *testing.T) { s.d.StartWithBusybox(c) var parent1Args []string var parent2Args []string wg := sync.WaitGroup{} maxChildren := 10 chErr := make(chan error, maxChildren) for i := 0; i < maxChildren; i++ { wg.Add(1) name := fmt.Sprintf("test%d", i) if i < maxChildren/2 { parent1Args = append(parent1Args, []string{"--link", name}...) } else { parent2Args = append(parent2Args, []string{"--link", name}...) } go func() { _, err := s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top") chErr <- err wg.Done() }() } wg.Wait() close(chErr) for err := range chErr { assert.NilError(c, err) } parent1Args = append([]string{"run", "-d"}, parent1Args...) parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...) parent2Args = append([]string{"run", "-d"}, parent2Args...) parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...) _, err := s.d.Cmd(parent1Args...) assert.NilError(c, err) _, err = s.d.Cmd(parent2Args...) assert.NilError(c, err) s.d.Stop(c) // clear the log file -- we don't need any of it but may for the next part // can ignore the error here, this is just a cleanup os.Truncate(s.d.LogFileName(), 0) s.d.Start(c) for _, num := range []string{"1", "2"} { out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num) assert.NilError(c, err) if strings.TrimSpace(out) != "true" { log, _ := ioutil.ReadFile(s.d.LogFileName()) c.Fatalf("parent container is not running\n%s", string(log)) } } } func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *testing.T) { testRequires(c, DaemonIsLinux) cgroupParent := "test" name := "cgroup-test" s.d.StartWithBusybox(c, "--cgroup-parent", cgroupParent) defer s.d.Restart(c) out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup") assert.NilError(c, err) cgroupPaths := ParseCgroupPaths(out) assert.Assert(c, len(cgroupPaths) != 0, "unexpected output - %q", out) out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name) assert.NilError(c, err) id := strings.TrimSpace(out) expectedCgroup := path.Join(cgroupParent, id) found := false for _, path := range cgroupPaths { if strings.HasSuffix(path, expectedCgroup) { found = true break } } assert.Assert(c, found, "Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths) } func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc") assert.NilError(c, err, out) s.d.Restart(c) // should fail since test is not running yet out, err = s.d.Cmd("start", "test2") assert.ErrorContains(c, err, "", out) out, err = s.d.Cmd("start", "test") assert.NilError(c, err, out) out, err = s.d.Cmd("start", "-a", "test2") assert.NilError(c, err, out) assert.Equal(c, strings.Contains(out, "1 packets transmitted, 1 packets received"), true, out) } func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "--name=test", "busybox") assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top") assert.NilError(c, err, out) test2ID := strings.TrimSpace(out) out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top") assert.NilError(c, err) test3ID := strings.TrimSpace(out) s.d.Restart(c) _, err = s.d.Cmd("create", "--name=test", "busybox") assert.ErrorContains(c, err, "", "expected error trying to create container with duplicate name") // this one is no longer needed, removing simplifies the remainder of the test out, err = s.d.Cmd("rm", "-f", "test") assert.NilError(c, err, out) out, err = s.d.Cmd("ps", "-a", "--no-trunc") assert.NilError(c, err, out) lines := strings.Split(strings.TrimSpace(out), "\n")[1:] test2validated := false test3validated := false for _, line := range lines { fields := strings.Fields(line) names := fields[len(fields)-1] switch fields[0] { case test2ID: assert.Equal(c, names, "test2,test3/abc") test2validated = true case test3ID: assert.Equal(c, names, "test3") test3validated = true } } assert.Assert(c, test2validated) assert.Assert(c, test3validated) } // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *testing.T) { testRequires(t, DaemonIsLinux) s.d.StartWithBusybox(t) cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") defer s.d.Stop(t) if err != nil { t.Fatal(cid, err) } cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) assert.NilError(t, err) pid = strings.TrimSpace(pid) // Kill the daemon if err := s.d.Kill(); err != nil { t.Fatal(err) } // kill the container icmd.RunCommand(ctrBinary, "--address", containerdSocket, "--namespace", s.d.ContainersNamespace(), "tasks", "kill", cid).Assert(t, icmd.Success) // Give time to containerd to process the command if we don't // the exit event might be received after we do the inspect result := icmd.RunCommand("kill", "-0", pid) for result.ExitCode == 0 { time.Sleep(1 * time.Second) // FIXME(vdemeester) should we check it doesn't error out ? result = icmd.RunCommand("kill", "-0", pid) } // restart the daemon s.d.Start(t) // Check that we've got the correct exit code out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid) assert.NilError(t, err) out = strings.TrimSpace(out) if out != "143" { t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid) } } // os.Kill should kill daemon ungracefully, leaving behind live containers. // The live containers should be known to the restarted daemon. Stopping // them now, should remove the mounts. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *testing.T) { testRequires(c, DaemonIsLinux) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "busybox", "top") assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) // kill the daemon assert.Assert(c, s.d.Kill() == nil) // Check if there are mounts with container id visible from the host. // If not, those mounts exist in container's own mount ns, and so // the following check for mounts being cleared is pointless. skipMountCheck := false mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") assert.Assert(c, err == nil, "Output: %s", mountOut) if !strings.Contains(string(mountOut), id) { skipMountCheck = true } // restart daemon. s.d.Start(c, "--live-restore") // container should be running. out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id) assert.NilError(c, err, "Output: %s", out) out = strings.TrimSpace(out) if out != "true" { c.Fatalf("Container %s expected to stay alive after daemon restart", id) } // 'docker stop' should work. out, err = s.d.Cmd("stop", id) assert.NilError(c, err, "Output: %s", out) if skipMountCheck { return } // Now, container mounts should be gone. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") assert.Assert(c, err == nil, "Output: %s", mountOut) comment := fmt.Sprintf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut) assert.Equal(c, strings.Contains(string(mountOut), id), false, comment) } // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers. func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *testing.T) { testRequires(t, DaemonIsLinux) s.d.StartWithBusybox(t, "--live-restore") cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") defer s.d.Stop(t) if err != nil { t.Fatal(cid, err) } cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) assert.NilError(t, err) // pause the container if _, err := s.d.Cmd("pause", cid); err != nil { t.Fatal(cid, err) } // Kill the daemon if err := s.d.Kill(); err != nil { t.Fatal(err) } // resume the container result := icmd.RunCommand( ctrBinary, "--address", containerdSocket, "--namespace", s.d.ContainersNamespace(), "tasks", "resume", cid) result.Assert(t, icmd.Success) // Give time to containerd to process the command if we don't // the resume event might be received after we do the inspect poll.WaitOn(t, pollCheck(t, func(*testing.T) (interface{}, string) { result := icmd.RunCommand("kill", "-0", strings.TrimSpace(pid)) return result.ExitCode, "" }, checker.Equals(0)), poll.WithTimeout(defaultReconciliationTimeout)) // restart the daemon s.d.Start(t, "--live-restore") // Check that we've got the correct status out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid) assert.NilError(t, err) out = strings.TrimSpace(out) if out != "running" { t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid) } if _, err := s.d.Cmd("kill", cid); err != nil { t.Fatal(err) } } // TestRunLinksChanged checks that creating a new container with the same name does not update links // this ensures that the old, pre gh#16032 functionality continues on func (s *DockerDaemonSuite) TestRunLinksChanged(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows does not support links s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc") assert.NilError(c, err, out) assert.Assert(c, strings.Contains(out, "1 packets transmitted, 1 packets received")) out, err = s.d.Cmd("rm", "-f", "test") assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top") assert.NilError(c, err, out) out, err = s.d.Cmd("start", "-a", "test2") assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "1 packets transmitted, 1 packets received")) s.d.Restart(c) out, err = s.d.Cmd("start", "-a", "test2") assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "1 packets transmitted, 1 packets received")) } func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *testing.T) { testRequires(c, DaemonIsLinux) infoLog := "\x1b[36mINFO\x1b" b := bytes.NewBuffer(nil) done := make(chan bool) p, tty, err := pty.Open() assert.NilError(c, err) defer func() { tty.Close() p.Close() }() go func() { io.Copy(b, p) done <- true }() // Enable coloring explicitly s.d.StartWithLogFile(tty, "--raw-logs=false") s.d.Stop(c) // Wait for io.Copy() before checking output <-done assert.Assert(c, strings.Contains(b.String(), infoLog)) b.Reset() // "tty" is already closed in prev s.d.Stop(), // we have to close the other side "p" and open another pair of // pty for the next test. p.Close() p, tty, err = pty.Open() assert.NilError(c, err) go func() { io.Copy(b, p) done <- true }() // Disable coloring explicitly s.d.StartWithLogFile(tty, "--raw-logs=true") s.d.Stop(c) // Wait for io.Copy() before checking output <-done assert.Assert(c, b.String() != "") assert.Assert(c, !strings.Contains(b.String(), infoLog)) } func (s *DockerDaemonSuite) TestDaemonDebugLog(c *testing.T) { testRequires(c, DaemonIsLinux) debugLog := "\x1b[37mDEBU\x1b" p, tty, err := pty.Open() assert.NilError(c, err) defer func() { tty.Close() p.Close() }() b := bytes.NewBuffer(nil) go io.Copy(b, p) s.d.StartWithLogFile(tty, "--debug") s.d.Stop(c) assert.Assert(c, strings.Contains(b.String(), debugLog)) } func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file daemonConfig := `{ "debug" : false }` configFile, err := ioutil.TempFile("", "test-daemon-discovery-backend-config-reload-config") assert.Assert(c, err == nil, "could not create temp file for config reload") configFilePath := configFile.Name() defer func() { configFile.Close() os.RemoveAll(configFile.Name()) }() _, err = configFile.Write([]byte(daemonConfig)) assert.NilError(c, err) // --log-level needs to be set so that d.Start() doesn't add --debug causing // a conflict with the config s.d.Start(c, "--config-file", configFilePath, "--log-level=info") // daemon config file daemonConfig = `{ "cluster-store": "consul://consuladdr:consulport/some/path", "cluster-advertise": "192.168.56.100:0", "debug" : false }` err = configFile.Truncate(0) assert.NilError(c, err) _, err = configFile.Seek(0, io.SeekStart) assert.NilError(c, err) _, err = configFile.Write([]byte(daemonConfig)) assert.NilError(c, err) err = s.d.ReloadConfig() assert.Assert(c, err == nil, "error reloading daemon config") out, err := s.d.Cmd("info") assert.NilError(c, err) assert.Assert(c, strings.Contains(out, "Cluster Store: consul://consuladdr:consulport/some/path")) assert.Assert(c, strings.Contains(out, "Cluster Advertise: 192.168.56.100:0")) } // Test for #21956 func (s *DockerDaemonSuite) TestDaemonLogOptions(c *testing.T) { s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514") out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top") assert.NilError(c, err, out) id := strings.TrimSpace(out) out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id) assert.NilError(c, err, out) assert.Assert(c, strings.Contains(out, "{json-file map[]}")) } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *testing.T) { s.d.Start(c, "--max-concurrent-uploads=6", "--max-concurrent-downloads=8") expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-downloads" : 8 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) configFile, err = os.Create(configFilePath) assert.NilError(c, err) daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) // unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"` content, err = s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) } // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-uploads" : null }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"` content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) configFile, err = os.Create(configFilePath) assert.NilError(c, err) daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) // unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) configFile, err = os.Create(configFilePath) assert.NilError(c, err) daemonConfig = `{ "labels":["foo=bar"] }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) time.Sleep(3 * time.Second) expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentUploads)) assert.Assert(c, strings.Contains(string(content), expectedMaxConcurrentDownloads)) } func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *testing.T) { s.d.StartWithBusybox(c, "-b=none", "--iptables=false") result := cli.BuildCmd(c, "busyboxs", cli.Daemon(s.d), build.WithDockerfile(` FROM busybox RUN cat /etc/hosts`), build.WithoutCache, ) comment := fmt.Sprintf("Failed to build image. output %s, exitCode %d, err %v", result.Combined(), result.ExitCode, result.Error) assert.Assert(c, result.Error == nil, comment) assert.Equal(c, result.ExitCode, 0, comment) } // Test case for #21976 func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3") expectedOutput := "nameserver 1.2.3.4" out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf") assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) expectedOutput = "search example.com" assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) expectedOutput = "options timeout:3" assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) } func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *testing.T) { conf, err := ioutil.TempFile("", "config-file-") assert.NilError(c, err) configName := conf.Name() conf.Close() defer os.Remove(configName) config := ` { "runtimes": { "oci": { "path": "runc" }, "vm": { "path": "/usr/local/bin/vm-manager", "runtimeArgs": [ "--debug" ] } } } ` ioutil.WriteFile(configName, []byte(config), 0644) s.d.StartWithBusybox(c, "--config-file", configName) // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") assert.NilError(c, err, out) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") assert.NilError(c, err, out) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "/usr/local/bin/vm-manager: no such file or directory")) // Reset config to only have the default config = ` { "runtimes": { } } ` ioutil.WriteFile(configName, []byte(config), 0644) assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) // Give daemon time to reload config <-time.After(1 * time.Second) // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "Unknown runtime specified oci")) // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "Unknown runtime specified oci")) // Check that we can't override the default runtime config = ` { "runtimes": { "runc": { "path": "my-runc" } } } ` ioutil.WriteFile(configName, []byte(config), 0644) assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) // Give daemon time to reload config <-time.After(1 * time.Second) content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), `file configuration validation failed: runtime name 'runc' is reserved`)) // Check that we can select a default runtime config = ` { "default-runtime": "vm", "runtimes": { "oci": { "path": "runc" }, "vm": { "path": "/usr/local/bin/vm-manager", "runtimeArgs": [ "--debug" ] } } } ` ioutil.WriteFile(configName, []byte(config), 0644) assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) // Give daemon time to reload config <-time.After(1 * time.Second) out, err = s.d.Cmd("run", "--rm", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "/usr/local/bin/vm-manager: no such file or directory")) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *testing.T) { s.d.StartWithBusybox(c, "--add-runtime", "oci=runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") assert.NilError(c, err, out) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") assert.NilError(c, err, out) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "/usr/local/bin/vm-manager: no such file or directory")) // Start a daemon without any extra runtimes s.d.Stop(c) s.d.StartWithBusybox(c) // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "Unknown runtime specified oci")) // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "Unknown runtime specified oci")) // Check that we can't override the default runtime s.d.Stop(c) assert.Assert(c, s.d.StartWithError("--add-runtime", "runc=my-runc") != nil) content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), `runtime name 'runc' is reserved`)) // Check that we can select a default runtime s.d.Stop(c) s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") out, err = s.d.Cmd("run", "--rm", "busybox", "ls") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "/usr/local/bin/vm-manager: no such file or directory")) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *testing.T) { s.d.StartWithBusybox(c) // top1 will exist after daemon restarts out, err := s.d.Cmd("run", "-d", "--name", "top1", "busybox:latest", "top") assert.Assert(c, err == nil, "run top1: %v", out) // top2 will be removed after daemon restarts out, err = s.d.Cmd("run", "-d", "--rm", "--name", "top2", "busybox:latest", "top") assert.Assert(c, err == nil, "run top2: %v", out) out, err = s.d.Cmd("ps") assert.NilError(c, err) assert.Assert(c, strings.Contains(out, "top1"), "top1 should be running") assert.Assert(c, strings.Contains(out, "top2"), "top2 should be running") // now restart daemon gracefully s.d.Restart(c) out, err = s.d.Cmd("ps", "-a") assert.NilError(c, err, "out: %v", out) assert.Assert(c, strings.Contains(out, "top1"), "top1 should exist after daemon restarts") assert.Assert(c, !strings.Contains(out, "top2"), "top2 should be removed after daemon restarts") } func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *testing.T) { s.d.StartWithBusybox(c) containerName := "error-values" // Make a container with both a non 0 exit code and an error message // We explicitly disable `--init` for this test, because `--init` is enabled by default // on "experimental". Enabling `--init` results in a different behavior; because the "init" // process itself is PID1, the container does not fail on _startup_ (i.e., `docker-init` starting), // but directly after. The exit code of the container is still 127, but the Error Message is not // captured, so `.State.Error` is empty. // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426, // and https://github.com/docker/docker/pull/26061#r78054578 for more information. _, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto") assert.ErrorContains(c, err, "") // Check that those values were saved on disk out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) assert.NilError(c, err) assert.Equal(c, out, "127") errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) errMsg1 = strings.TrimSpace(errMsg1) assert.NilError(c, err) assert.Assert(c, strings.Contains(errMsg1, "executable file not found")) // now restart daemon s.d.Restart(c) // Check that those values are still around out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) assert.NilError(c, err) assert.Equal(c, out, "127") out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) out = strings.TrimSpace(out) assert.NilError(c, err) assert.Equal(c, out, errMsg1) } func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) dockerProxyPath, err := exec.LookPath("docker-proxy") assert.NilError(c, err) tmpDir, err := ioutil.TempDir("", "test-docker-proxy") assert.NilError(c, err) newProxyPath := filepath.Join(tmpDir, "docker-proxy") cmd := exec.Command("cp", dockerProxyPath, newProxyPath) assert.NilError(c, cmd.Run()) // custom one s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath) out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") assert.NilError(c, err, out) // try with the original one s.d.Restart(c, "--userland-proxy-path", dockerProxyPath) out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") assert.NilError(c, err, out) // not exist s.d.Restart(c, "--userland-proxy-path", "/does/not/exist") out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "driver failed programming external connectivity on endpoint")) assert.Assert(c, strings.Contains(out, "/does/not/exist: no such file or directory")) } // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--shutdown-timeout=3") _, err := s.d.Cmd("run", "-d", "busybox", "top") assert.NilError(c, err) assert.Assert(c, s.d.Signal(unix.SIGINT) == nil) select { case <-s.d.Wait: case <-time.After(5 * time.Second): } expectedMessage := `level=debug msg="daemon configured with a 3 seconds minimum shutdown timeout"` content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMessage)) } // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "shutdown-timeout" : 8 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) configFile, err = os.Create(configFilePath) assert.NilError(c, err) daemonConfig = `{ "shutdown-timeout" : 5 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() assert.Assert(c, s.d.Signal(unix.SIGHUP) == nil) select { case <-s.d.Wait: case <-time.After(3 * time.Second): } expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"` content, err := s.d.ReadLogFile() assert.NilError(c, err) assert.Assert(c, strings.Contains(string(content), expectedMessage)) } // Test case for 29342 func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *testing.T) { testRequires(c, DaemonIsLinux) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "--init", "-d", "--name=top", "busybox", "sh", "-c", "addgroup -S test && adduser -S -G test test -D -s /bin/sh && touch /adduser_end && exec top") assert.NilError(c, err, "Output: %s", out) s.d.WaitRun("top") // Wait for shell command to be completed _, err = s.d.Cmd("exec", "top", "sh", "-c", `for i in $(seq 1 5); do if [ -e /adduser_end ]; then rm -f /adduser_end && break; else sleep 1 && false; fi; done`) assert.Assert(c, err == nil, "Timeout waiting for shell command to be completed") out1, err := s.d.Cmd("exec", "-u", "test", "top", "id") // uid=100(test) gid=101(test) groups=101(test) assert.Assert(c, err == nil, "Output: %s", out1) // restart daemon. s.d.Restart(c, "--live-restore") out2, err := s.d.Cmd("exec", "-u", "test", "top", "id") assert.Assert(c, err == nil, "Output: %s", out2) assert.Equal(c, out2, out1, fmt.Sprintf("Output: before restart '%s', after restart '%s'", out1, out2)) out, err = s.d.Cmd("stop", "top") assert.NilError(c, err, "Output: %s", out) } func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *testing.T) { testRequires(c, DaemonIsLinux, overlayFSSupported, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top") assert.NilError(c, err, "Output: %s", out) s.d.WaitRun("top") // restart daemon. s.d.Restart(c, "--live-restore", "--storage-driver", "overlay") out, err = s.d.Cmd("stop", "top") assert.NilError(c, err, "Output: %s", out) // test if the rootfs mountpoint still exist mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir") assert.NilError(c, err) f, err := os.Open("/proc/self/mountinfo") assert.NilError(c, err) defer f.Close() sc := bufio.NewScanner(f) for sc.Scan() { line := sc.Text() if strings.Contains(line, mountpoint) { c.Fatalf("mountinfo should not include the mountpoint of stop container") } } out, err = s.d.Cmd("rm", "top") assert.NilError(c, err, "Output: %s", out) } // #29598 func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) type state struct { Running bool StartedAt time.Time } out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id) assert.Assert(c, err == nil, "output: %s", out) var origState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState) assert.NilError(c, err) s.d.Restart(c, "--live-restore") pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id) assert.NilError(c, err) pidint, err := strconv.Atoi(strings.TrimSpace(pid)) assert.NilError(c, err) assert.Assert(c, pidint > 0) assert.NilError(c, unix.Kill(pidint, unix.SIGKILL)) ticker := time.NewTicker(50 * time.Millisecond) timeout := time.After(10 * time.Second) for range ticker.C { select { case <-timeout: c.Fatal("timeout waiting for container restart") default: } out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id) assert.Assert(c, err == nil, "output: %s", out) var newState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState) assert.NilError(c, err) if !newState.Running { continue } if newState.StartedAt.After(origState.StartedAt) { break } } out, err = s.d.Cmd("stop", id) assert.NilError(c, err, "Output: %s", out) } func (s *DockerDaemonSuite) TestShmSize(c *testing.T) { testRequires(c, DaemonIsLinux) size := 67108864 * 2 pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size)) name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") assert.NilError(c, err, "Output: %s", out) assert.Assert(c, pattern.MatchString(out)) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) assert.NilError(c, err, "Output: %s", out) assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%v", size)) } func (s *DockerDaemonSuite) TestShmSizeReload(c *testing.T) { testRequires(c, DaemonIsLinux) configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config") assert.Assert(c, err == nil, "could not create temp file for config reload") defer os.RemoveAll(configPath) // clean up configFile := filepath.Join(configPath, "config.json") size := 67108864 * 2 configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) assert.Assert(c, ioutil.WriteFile(configFile, configData, 0666) == nil, "could not write temp file for config reload") pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) s.d.StartWithBusybox(c, "--config-file", configFile) name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") assert.NilError(c, err, "Output: %s", out) assert.Assert(c, pattern.MatchString(out)) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) assert.NilError(c, err, "Output: %s", out) assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%v", size)) size = 67108864 * 3 configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) assert.Assert(c, ioutil.WriteFile(configFile, configData, 0666) == nil, "could not write temp file for config reload") pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) err = s.d.ReloadConfig() assert.Assert(c, err == nil, "error reloading daemon config") name = "shm2" out, err = s.d.Cmd("run", "--name", name, "busybox", "mount") assert.NilError(c, err, "Output: %s", out) assert.Assert(c, pattern.MatchString(out)) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) assert.NilError(c, err, "Output: %s", out) assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%v", size)) } func testDaemonStartIpcMode(c *testing.T, from, mode string, valid bool) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) c.Logf("Checking IpcMode %s set from %s\n", mode, from) var serr error switch from { case "config": f, err := ioutil.TempFile("", "test-daemon-ipc-config") assert.NilError(c, err) defer os.Remove(f.Name()) config := `{"default-ipc-mode": "` + mode + `"}` _, err = f.WriteString(config) assert.NilError(c, f.Close()) assert.NilError(c, err) serr = d.StartWithError("--config-file", f.Name()) case "cli": serr = d.StartWithError("--default-ipc-mode", mode) default: c.Fatalf("testDaemonStartIpcMode: invalid 'from' argument") } if serr == nil { d.Stop(c) } if valid { assert.NilError(c, serr) } else { assert.ErrorContains(c, serr, "") icmd.RunCommand("grep", "-E", "IPC .* is (invalid|not supported)", d.LogFileName()).Assert(c, icmd.Success) } } // TestDaemonStartWithIpcModes checks that daemon starts fine given correct // arguments for default IPC mode, and bails out with incorrect ones. // Both CLI option (--default-ipc-mode) and config parameter are tested. func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ipcModes := []struct { mode string valid bool }{ {"private", true}, {"shareable", true}, {"host", false}, {"container:123", false}, {"nosuchmode", false}, } for _, from := range []string{"config", "cli"} { for _, m := range ipcModes { testDaemonStartIpcMode(c, from, m.mode, m.valid) } } } // TestFailedPluginRemove makes sure that a failed plugin remove does not block // the daemon from starting func (s *DockerDaemonSuite) TestFailedPluginRemove(c *testing.T) { testRequires(c, DaemonIsLinux, IsAmd64, testEnv.IsLocalDaemon) d := daemon.New(c, dockerBinary, dockerdBinary) d.Start(c) cli := d.NewClientT(c) ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) defer cancel() name := "test-plugin-rm-fail" out, err := cli.PluginInstall(ctx, name, types.PluginInstallOptions{ Disabled: true, AcceptAllPermissions: true, RemoteRef: "cpuguy83/docker-logdriver-test", }) assert.NilError(c, err) defer out.Close() io.Copy(ioutil.Discard, out) ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() p, _, err := cli.PluginInspectWithRaw(ctx, name) assert.NilError(c, err) // simulate a bad/partial removal by removing the plugin config. configPath := filepath.Join(d.Root, "plugins", p.ID, "config.json") assert.NilError(c, os.Remove(configPath)) d.Restart(c) ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = cli.Ping(ctx) assert.NilError(c, err) _, _, err = cli.PluginInspectWithRaw(ctx, name) // plugin should be gone since the config.json is gone assert.ErrorContains(c, err, "") }
[ "\"DOCKER_HOST\"" ]
[]
[ "DOCKER_HOST" ]
[]
["DOCKER_HOST"]
go
1
0
config.py
# coding: utf-8 # project base path import os basedir = os.path.abspath(os.path.dirname(__file__)) """ common configuration -- SECRET_KEY: secret key -- SQLALCHEMY_COMMIT_ON_TEARDOWN: True -- SQLALCHEMY_RECORD_QUERIES: -- Can be used to explicitly disable or enable query recording. Query recording automatically happens in debug or testing mode. -- SQLALCHEMY_TRACK_MODIFICATIONS: -- If set to True, Flask-SQLAlchemy will track modifications of objects and emit signals. The default is None, which enables tracking but issues a warning that it will be disabled by default in the future. This requires extra memory and should be disabled if not needed. more configuration keys please see: -- http://flask-sqlalchemy.pocoo.org/2.1/config/#configuration-keys """ class Config: """common configuration""" SECRET_KEY = os.environ.get("SECRET_KEY") or "hard to guess string" SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_RECORD_QUERIES = True SQLALCHEMY_TRACK_MODIFICATIONS = True MAIL_DEFAULT_SENDER=os.environ.get('MAIL_DEFAULT_SENDER') or '[email protected]' MAIL_SERVER = 'smtp.qq.com' # 邮件服务器地址 MAIL_PORT = 25 # 邮件服务器端口 MAIL_USE_TLS = True # 启用 TLS MAIL_USERNAME = os.environ.get("MAIL_USERNAME") or "[email protected]" MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') or "iifwjwzfjxvxchig" CELERY_BROKER_URI = os.environ.get('CELERY_BROKER_URI') or 'redis://127.0.0.1:6379' # 指定 Broker CELERY_BACKEND_URI = os.environ.get('CELERY_BACKEND_URI') or 'redis://127.0.0.1:6379/0' # 指定 Backend @staticmethod def init_app(app): pass """ development configuration -- DEBUG: debug mode -- SQLALCHEMY_DATABASE_URI: -- The database URI that should be used for the connection. more connection URI format: -- Postgres: -- postgresql://scott:tiger@localhost/mydatabase -- MySQL: -- mysql://scott:tiger@localhost/mydatabase -- Oracle: -- oracle://scott:[email protected]:1521/sidname """ class DevelopmentConfig(Config): """development configuration""" DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_ORM_URI") or "sqlite:///" + os.path.join(basedir, "data-dev.sqlite") """ testing configuration -- TESTING: True -- WTF_CSRF_ENABLED: -- in testing environment, we don't need CSRF enabled """ class TestingConfig(Config): """testing configuration""" TESTING = True SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(basedir, "data-tests.sqlite") WTF_CSRF_ENABLED = False # production configuration class ProductionConfig(Config): """production configuration""" SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_ORM_URI') or "sqlite:///" + os.path.join(basedir, "data.sqlite") @classmethod def init_app(cls, app): Config.init_app(app) config = { "develop": DevelopmentConfig, "testing": TestingConfig, "production": ProductionConfig, "default": DevelopmentConfig }
[]
[]
[ "CELERY_BACKEND_URI", "DATABASE_ORM_URI", "MAIL_PASSWORD", "MAIL_DEFAULT_SENDER", "SECRET_KEY", "MAIL_USERNAME", "CELERY_BROKER_URI" ]
[]
["CELERY_BACKEND_URI", "DATABASE_ORM_URI", "MAIL_PASSWORD", "MAIL_DEFAULT_SENDER", "SECRET_KEY", "MAIL_USERNAME", "CELERY_BROKER_URI"]
python
7
0
baas-core/core/tools/fabric/core/config/config.go
/* Copyright Greg Haskins <[email protected]> 2017, All Rights Reserved. Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package config import ( "fmt" "os" "path/filepath" "github.com/jonluo94/baasmanager/baas-core/core/tools/viper" ) func dirExists(path string) bool { fi, err := os.Stat(path) if err != nil { return false } return fi.IsDir() } func AddConfigPath(v *viper.Viper, p string) { if v != nil { v.AddConfigPath(p) } else { viper.AddConfigPath(p) } } //---------------------------------------------------------------------------------- // TranslatePath() //---------------------------------------------------------------------------------- // Translates a relative path into a fully qualified path relative to the config // file that specified it. Absolute paths are passed unscathed. //---------------------------------------------------------------------------------- func TranslatePath(base, p string) string { if filepath.IsAbs(p) { return p } return filepath.Join(base, p) } //---------------------------------------------------------------------------------- // TranslatePathInPlace() //---------------------------------------------------------------------------------- // Translates a relative path into a fully qualified path in-place (updating the // pointer) relative to the config file that specified it. Absolute paths are // passed unscathed. //---------------------------------------------------------------------------------- func TranslatePathInPlace(base string, p *string) { *p = TranslatePath(base, *p) } //---------------------------------------------------------------------------------- // GetPath() //---------------------------------------------------------------------------------- // GetPath allows configuration strings that specify a (config-file) relative path // // For example: Assume our config is located in /etc/hyperledger/fabric/core.yaml with // a key "msp.configPath" = "msp/config.yaml". // // This function will return: // GetPath("msp.configPath") -> /etc/hyperledger/fabric/msp/config.yaml // //---------------------------------------------------------------------------------- func GetPath(key string) string { p := viper.GetString(key) if p == "" { return "" } return TranslatePath(filepath.Dir(viper.ConfigFileUsed()), p) } const OfficialPath = "/etc/hyperledger/fabric" //---------------------------------------------------------------------------------- // InitViper() //---------------------------------------------------------------------------------- // Performs basic initialization of our viper-based configuration layer. // Primary thrust is to establish the paths that should be consulted to find // the configuration we need. If v == nil, we will initialize the global // Viper instance //---------------------------------------------------------------------------------- func InitViper(v *viper.Viper, configName string) error { var altPath = os.Getenv("FABRIC_CFG_PATH") if altPath != "" { // If the user has overridden the path with an envvar, its the only path // we will consider if !dirExists(altPath) { return fmt.Errorf("FABRIC_CFG_PATH %s does not exist", altPath) } AddConfigPath(v, altPath) } else { // If we get here, we should use the default paths in priority order: // // *) CWD // *) /etc/hyperledger/fabric // CWD AddConfigPath(v, "./") // And finally, the official path if dirExists(OfficialPath) { AddConfigPath(v, OfficialPath) } } // Now set the configuration file. if v != nil { v.SetConfigName(configName) } else { viper.SetConfigName(configName) } return nil }
[ "\"FABRIC_CFG_PATH\"" ]
[]
[ "FABRIC_CFG_PATH" ]
[]
["FABRIC_CFG_PATH"]
go
1
0
spreadsheets/spreadsheet.go
package spreadsheets import ( "context" "encoding/base64" "encoding/json" "fmt" "github.com/cloudevents/sdk-go" "github.com/heaptracetechnology/google-sheets/result" "golang.org/x/oauth2/google" driveV3 "google.golang.org/api/drive/v3" sheetsV4 "google.golang.org/api/sheets/v4" "log" "net/http" "net/url" "os" "regexp" "strconv" "strings" "time" ) //ArgsData struct type ArgsData struct { RowLength *sheetsV4.Request `json:"rowLength"` ColumnLength *sheetsV4.Request `json:"columnLength"` Title string `json:"title"` ID string `json:"spreadsheetId"` SheetID int64 `json:"sheetId"` SheetIndex int `json:"sheetIndex"` SheetTitle string `json:"sheetTitle"` Row int64 `json:"row"` Column int64 `json:"column"` Content string `json:"content"` Start int `json:"start"` End int `json:"end"` EmailAddress string `json:"emailAddress"` IsTesting bool `json:"isTesting"` Role string `json:"role"` Type string `json:"type"` CellNumber string `json:"cellNumber"` } //Subscribe struct type Subscribe struct { Data RequestParam `json:"data"` Endpoint string `json:"endpoint"` ID string `json:"id"` IsTesting bool `json:"istesting"` } //SubscribeReturn struct type SubscribeReturn struct { SpreadsheetID string `json:"spreadsheetID"` SheetTitle string `json:"sheetTitle"` TwitterCell string `json:"twitterCell"` EmailAddress string `json:"emailAddress"` } //RequestParam struct type RequestParam struct { SpreadsheetID string `json:"spreadsheetID"` SheetTitle string `json:"sheetTitle"` } //Message struct type Message struct { Success bool `json:"success"` Message string `json:"message"` StatusCode int `json:"statusCode"` } //SheetScope Spreadsheet const ( SheetScope = "https://www.googleapis.com/auth/spreadsheets" DriveScope = "https://www.googleapis.com/auth/drive.file" ) //Global Variables var ( Listener = make(map[string]Subscribe) rtmStarted bool sheetService *sheetsV4.Service sheetServiceErr error oldRowCount int twitterIndex int subReturn SubscribeReturn count int ) //HealthCheck Google-Sheets func HealthCheck(responseWriter http.ResponseWriter, request *http.Request) { bytes, _ := json.Marshal("OK") result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //CreateSpreadsheet func func CreateSpreadsheet(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decodedJSON, err := base64.StdEncoding.DecodeString(key) if err != nil { result.WriteErrorResponseString(responseWriter, err.Error()) return } decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponseString(responseWriter, decodeErr.Error()) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } sheetProperties := sheetsV4.Spreadsheet{ Properties: &sheetsV4.SpreadsheetProperties{ Title: argsdata.Title, }, } newSpreadsheet := sheetService.Spreadsheets.Create(&sheetProperties) spreadsheet, sheetErr := newSpreadsheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } spreadsheetID := spreadsheet.SpreadsheetId driveConf, driveConfErr := google.JWTConfigFromJSON(decodedJSON, DriveScope) if driveConfErr != nil { result.WriteErrorResponseString(responseWriter, driveConfErr.Error()) return } driveClient := driveConf.Client(context.TODO()) driveService, driveServiceErr := driveV3.New(driveClient) if driveServiceErr != nil { result.WriteErrorResponseString(responseWriter, driveServiceErr.Error()) return } driveProperties := driveV3.Permission{ EmailAddress: argsdata.EmailAddress, Role: argsdata.Role, Type: argsdata.Type, } if spreadsheetID != "" { permission := driveService.Permissions.Create(spreadsheetID, &driveProperties) _, doErr := permission.Do() if doErr != nil && argsdata.IsTesting == false { result.WriteErrorResponseString(responseWriter, doErr.Error()) return } } bytes, _ := json.Marshal(spreadsheet) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //FindSpreadsheet func func FindSpreadsheet(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } getSpreadsheet := sheetService.Spreadsheets.Get(argsdata.ID) spreadsheet, sheetErr := getSpreadsheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } bytes, _ := json.Marshal(spreadsheet) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //AddSheet func func AddSheet(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } addSheet := sheetsV4.BatchUpdateSpreadsheetRequest{ Requests: []*sheetsV4.Request{ &sheetsV4.Request{ AddSheet: &sheetsV4.AddSheetRequest{ Properties: &sheetsV4.SheetProperties{ Title: argsdata.SheetTitle, }, }, }, }, } addSpreadsheet := sheetService.Spreadsheets.BatchUpdate(argsdata.ID, &addSheet) spreadsheet, sheetErr := addSpreadsheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } bytes, _ := json.Marshal(spreadsheet) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //FindSheet func func FindSheet(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } if argsdata.SheetID <= 0 && argsdata.SheetIndex <= 0 && argsdata.SheetTitle == "" { message := Message{false, "Please provide at least one argument(sheet Id, title or index)", http.StatusBadRequest} bytes, _ := json.Marshal(message) result.WriteJSONResponse(responseWriter, bytes, http.StatusBadRequest) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } getSheet := sheetService.Spreadsheets.Values.Get(argsdata.ID, argsdata.SheetTitle) sheet, sheetErr := getSheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } bytes, _ := json.Marshal(sheet) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //UpdateSheetSize func func UpdateSheetSize(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } resizeValues := sheetsV4.BatchUpdateSpreadsheetRequest{ Requests: []*sheetsV4.Request{ &sheetsV4.Request{ AppendDimension: &sheetsV4.AppendDimensionRequest{ Length: argsdata.Row, Dimension: "ROWS", SheetId: argsdata.SheetID, }, }, &sheetsV4.Request{ AppendDimension: &sheetsV4.AppendDimensionRequest{ Length: argsdata.Column, Dimension: "COLUMNS", SheetId: argsdata.SheetID, }, }, }, } resizeSheet := sheetService.Spreadsheets.BatchUpdate(argsdata.ID, &resizeValues) _, sheetErr := resizeSheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } message := Message{Success: true, Message: "Updated sheet size successfully", StatusCode: http.StatusOK} bytes, _ := json.Marshal(message) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //UpdateCell func func UpdateCell(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } writeProp := sheetsV4.ValueRange{ MajorDimension: "ROWS", Values: [][]interface{}{{argsdata.Content}}, } writeSheet := sheetService.Spreadsheets.Values.Update(argsdata.ID, argsdata.SheetTitle+"!"+argsdata.CellNumber, &writeProp) writeSheet.ValueInputOption("USER_ENTERED") sheet, sheetErr := writeSheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } bytes, _ := json.Marshal(sheet) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //DeleteSheet func func DeleteSheet(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decoder := json.NewDecoder(request.Body) var argsdata ArgsData decodeErr := decoder.Decode(&argsdata) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } decodedJSON, decodeErr := base64.StdEncoding.DecodeString(key) if decodeErr != nil { result.WriteErrorResponse(responseWriter, decodeErr) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr := sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } deleteProperties := sheetsV4.BatchUpdateSpreadsheetRequest{ Requests: []*sheetsV4.Request{ &sheetsV4.Request{ DeleteSheet: &sheetsV4.DeleteSheetRequest{ SheetId: argsdata.SheetID, }, }, }, } deleteSheet := sheetService.Spreadsheets.BatchUpdate(argsdata.ID, &deleteProperties) _, sheetErr := deleteSheet.Do() if sheetErr != nil { result.WriteErrorResponseString(responseWriter, sheetErr.Error()) return } message := Message{true, "Sheet deleted successfully", http.StatusOK} bytes, _ := json.Marshal(message) result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //SheetSubscribe func func SheetSubscribe(responseWriter http.ResponseWriter, request *http.Request) { var key = os.Getenv("CREDENTIAL_JSON") decodedJSON, err := base64.StdEncoding.DecodeString(key) if err != nil { result.WriteErrorResponseString(responseWriter, err.Error()) return } decoder := json.NewDecoder(request.Body) var sub Subscribe decodeError := decoder.Decode(&sub) if decodeError != nil { result.WriteErrorResponseString(responseWriter, decodeError.Error()) return } sheetConf, sheetConfErr := google.JWTConfigFromJSON(decodedJSON, SheetScope) if sheetConfErr != nil { result.WriteErrorResponseString(responseWriter, sheetConfErr.Error()) return } sheetClient := sheetConf.Client(context.TODO()) sheetService, sheetServiceErr = sheetsV4.New(sheetClient) if sheetServiceErr != nil { result.WriteErrorResponseString(responseWriter, sheetServiceErr.Error()) return } Listener[sub.Data.SpreadsheetID] = sub if !rtmStarted { go SheetRTM() rtmStarted = true } bytes, _ := json.Marshal("Subscribed") result.WriteJSONResponse(responseWriter, bytes, http.StatusOK) } //SheetRTM func func SheetRTM() { isTest := false for { if len(Listener) > 0 { for k, v := range Listener { go getNewRowUpdate(k, v) isTest = v.IsTesting } } else { rtmStarted = false break } time.Sleep(10 * time.Second) if isTest { break } } } func getNewRowUpdate(spreadsheetID string, sub Subscribe) { subReturn.SpreadsheetID = spreadsheetID subReturn.SheetTitle = sub.Data.SheetTitle readSheet := sheetService.Spreadsheets.Values.Get(spreadsheetID, sub.Data.SheetTitle) sheet, readSheetErr := readSheet.Do() if readSheetErr != nil { fmt.Println("Read Sheet error: ", readSheetErr) return } currentRowCount := len(sheet.Values) if currentRowCount > 0 { sheetData := sheet.Values columnHeading := sheetData[0] for index, value := range columnHeading { columnContent := fmt.Sprintf("%v", value) if strings.EqualFold(columnContent, "twitter") { twitterIndex = index + 1 letter := toCharStr(twitterIndex) subReturn.TwitterCell = letter + strconv.FormatInt(int64(currentRowCount), 10) } } if currentRowCount >= 2 { list := sheet.Values extractedList := list[currentRowCount-1] for _, v := range extractedList { columnContent := fmt.Sprintf("%v", v) match, _ := regexp.MatchString("^\\w+([-+.']\\w+)*@[A-Za-z\\d]+\\.com$", columnContent) if match { subReturn.EmailAddress = columnContent } } } contentType := "application/json" transport, err := cloudevents.NewHTTPTransport(cloudevents.WithTarget(sub.Endpoint), cloudevents.WithStructuredEncoding()) if err != nil { fmt.Println("failed to create transport : ", err) return } client, err := cloudevents.NewClient(transport, cloudevents.WithTimeNow()) if err != nil { fmt.Println("failed to create client : ", err) return } source, err := url.Parse(sub.Endpoint) event := cloudevents.Event{ Context: cloudevents.EventContextV01{ EventID: sub.ID, EventType: "listener", Source: cloudevents.URLRef{URL: *source}, ContentType: &contentType, }.AsV01(), Data: subReturn, } if (oldRowCount == 0 || oldRowCount < currentRowCount) && currentRowCount >= 2 { oldRowCount = currentRowCount _, resp, err := client.Send(context.Background(), event) if err != nil { log.Printf("failed to send: %v", err) } subReturn.EmailAddress = "" subReturn.SheetTitle = "" subReturn.SpreadsheetID = "" subReturn.TwitterCell = "" fmt.Printf("Response: \n%s\n", resp) } } } func toCharStr(i int) string { return string('A' - 1 + i) }
[ "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"", "\"CREDENTIAL_JSON\"" ]
[]
[ "CREDENTIAL_JSON" ]
[]
["CREDENTIAL_JSON"]
go
1
0
src/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": # CHANGED manage.py will use development settings by # default. Change the DJANGO_SETTINGS_MODULE environment variable # for using the environment specific settings file. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dnd_spellbook.settings.development") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[]
[]
[]
[]
[]
python
0
0
bsm/cmd/pkg_edit.py
import os import subprocess from bsm.util import which from bsm.cmd import CmdResult from bsm.cmd import CmdError from bsm.cmd.pkg_base import PkgBase from bsm.logger import get_logger _logger = get_logger() DEFAULT_EDITOR = ['vim', 'vi'] def _detect_editor(editors): for editor in editors: if which(editor): return editor return None class PkgEdit(PkgBase): def execute(self, category, subdir, version, package): self._check_release() category, subdir, package, version = self._process_param(package, category, subdir, version) pkg_path = self._bsm.package_path(package, category, subdir, version) pkg_cfg_file = pkg_path['config_file'] editor = None if 'VISUAL' in os.environ: editor = os.environ['VISUAL'] elif 'EDITOR' in os.environ: editor = os.environ['EDITOR'] else: editor = _detect_editor(DEFAULT_EDITOR) if not editor: _logger.warning('Editor open failed. Please edit the package configuration file by yourself: {0}'.format(pkg_cfg_file)) return _logger.info('Edit package configuration file: {0}'.format(pkg_cfg_file)) _logger.debug('Select editor: {0}'.format(editor)) command = [editor, pkg_cfg_file] return CmdResult(commands={'cmd': command})
[]
[]
[ "VISUAL", "EDITOR" ]
[]
["VISUAL", "EDITOR"]
python
2
0
examples/pwr_run/checkpointing/short/max_par/job27.py
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras.callbacks import ReduceLROnPlateau, TensorBoard from keras.preprocessing.image import ImageDataGenerator from keras.regularizers import l2 from keras import backend as K from keras.models import Model from keras.datasets import cifar10 from keras.applications.mobilenet_v2 import MobileNetV2 from keras import models, layers, optimizers from datetime import datetime import tensorflow as tf import numpy as np import os import pdb import sys import argparse import time import signal import glob import json parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training') parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name') parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint') parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use') parser.set_defaults(resume=False) args = parser.parse_args() os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num # Training parameters batch_size = 128 args_lr = 0.005 epoch_begin_time = 0 job_name = sys.argv[0].split('.')[0] save_files = '/scratch/li.baol/checkpoint_max_param/' + job_name + '*' total_epochs = 87 starting_epoch = 0 # first step is to update the PID pid_dict = {} with open('pid_lock.json', 'r') as fp: pid_dict = json.load(fp) pid_dict[job_name] = os.getpid() json_file = json.dumps(pid_dict) with open('pid_lock.json', 'w') as fp: fp.write(json_file) os.rename('pid_lock.json', 'pid.json') if args.resume: save_file = glob.glob(save_files)[0] # epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0]) starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1]) data_augmentation = True num_classes = 10 # Subtracting pixel mean improves accuracy subtract_pixel_mean = True n = 3 # Model name, depth and version model_type = args.tc #'P100_resnet50_he_256_1' # Load the CIFAR10 data. (x_train, y_train), (x_test, y_test) = cifar10.load_data() # Normalize data. x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255 # If subtract pixel mean is enabled if subtract_pixel_mean: x_train_mean = np.mean(x_train, axis=0) x_train -= x_train_mean x_test -= x_train_mean print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') print('y_train shape:', y_train.shape) # Convert class vectors to binary class matrices. y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) if args.resume: print('resume from checkpoint') model = keras.models.load_model(save_file) else: print('train from start') model = models.Sequential() base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None) #base_model.summary() #pdb.set_trace() model.add(base_model) model.add(layers.Flatten()) #model.add(layers.BatchNormalization()) #model.add(layers.Dense(128, activation='relu')) #model.add(layers.Dropout(0.5)) #model.add(layers.BatchNormalization()) #model.add(layers.Dense(64, activation='relu')) #model.add(layers.Dropout(0.5)) #model.add(layers.BatchNormalization()) model.add(layers.Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=args_lr), metrics=['accuracy']) #model.summary() print(model_type) #pdb.set_trace() current_epoch = 0 ################### connects interrupt signal to the process ##################### def terminateProcess(signalNumber, frame): # first record the wasted epoch time global epoch_begin_time epoch_waste_time = int(time.time() - epoch_begin_time) epoch_waste_dict = {} with open('epoch_waste.json', 'r') as fp: epoch_waste_dict = json.load(fp) epoch_waste_dict[job_name] += epoch_waste_time json_file3 = json.dumps(epoch_waste_dict) with open('epoch_waste.json', 'w') as fp: fp.write(json_file3) print('checkpointing the model triggered by kill -15 signal') # delete whatever checkpoint that already exists for f in glob.glob(save_files): os.remove(f) model.save('/scratch/li.baol/checkpoint_max_param/' + job_name + '_' + str(current_epoch) + '.h5') print ('(SIGTERM) terminating the process') checkpoint_dict = {} with open('checkpoint.json', 'r') as fp: checkpoint_dict = json.load(fp) checkpoint_dict[job_name] = 1 json_file3 = json.dumps(checkpoint_dict) with open('checkpoint.json', 'w') as fp: fp.write(json_file3) sys.exit() signal.signal(signal.SIGTERM, terminateProcess) ################################################################################# logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch') class PrintEpoch(keras.callbacks.Callback): def on_epoch_begin(self, epoch, logs=None): global current_epoch #remaining_epochs = epochs - epoch current_epoch = epoch print('current epoch ' + str(current_epoch)) global epoch_begin_time epoch_begin_time = time.time() my_callback = PrintEpoch() callbacks = [tensorboard_callback, my_callback] #[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback] # Run training if not args.resume: trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)])) param_dict = {} modify = False with open('param_lock.json', 'r') as fp: param_dict = json.load(fp) if job_name not in param_dict: param_dict[job_name] = trainable_count modify = True elif param_dict[job_name] != trainable_count: param_dict[job_name] = trainable_count modify = True if modify: json_file = json.dumps(param_dict) with open('param_lock.json', 'w') as fp: fp.write(json_file) os.rename('param_lock.json', 'param.json') # creates an file if job qualified for checkpoint open('ckpt_qual/' + job_name + '.txt', 'a').close() model.fit(x_train, y_train, batch_size=batch_size, epochs=round(total_epochs/2), validation_data=(x_test, y_test), shuffle=True, callbacks=callbacks, initial_epoch=starting_epoch, verbose=1 ) # Score trained model. scores = model.evaluate(x_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) finish_dict = {} while True: if os.path.exists('finish.json'): try: os.rename('finish.json', 'finish_lock.json') break except Exception: pass else: time.sleep(1) with open('finish_lock.json', 'r') as fp: finish_dict = json.load(fp) finish_dict[job_name] = 1 json_file2 = json.dumps(finish_dict) with open('finish_lock.json', 'w') as fp: fp.write(json_file2) os.rename('finish_lock.json', 'finish.json')
[]
[]
[ "CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
python
2
0
functional_tests/tests.py
import os from django.test import LiveServerTestCase from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException import time MAX_WAIT = 10 class NewVisitorTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() staging_server = os.environ.get('STAGING_SERVER') if staging_server: self.live_server_url = 'http://' + staging_server def tearDown(self): self.browser.quit() def wait_for_row_in_list_table(self, row_text): start_time = time.time() while True: try: table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) return except (AssertionError, WebDriverException) as e: if time.time() - start_time > MAX_WAIT: raise e time.sleep(0.5) def check_for_rows_in_list_table(self, row_text): table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get(self.live_server_url) self.assertIn('To-Do', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('To-Do', header_text) input_box = self.browser.find_element_by_id('id_new_item') self.assertEqual(input_box.get_attribute('placeholder'), 'Enter a to-do item') input_box.send_keys('Buy peacock feathers') input_box.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy peacock feathers') input_box = self.browser.find_element_by_id('id_new_item') input_box.send_keys('Use peacock feathers to make a fly') input_box.send_keys(Keys.ENTER) time.sleep(1) self.wait_for_row_in_list_table('1: Buy peacock feathers') self.wait_for_row_in_list_table('2: Use peacock feathers to make a fly') # self.fail('Finish the test') def test_multiple_users_can_start_lists_at_different_urls(self): self.browser.get(self.live_server_url) input_box = self.browser.find_element_by_id('id_new_item') input_box.send_keys('Buy peacock feathers') input_box.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy peacock feathers') edith_list_url = self.browser.current_url self.assertRegex(edith_list_url, '/lists/.+') self.browser.quit() self.browser = webdriver.Firefox() self.browser.get(self.live_server_url) page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertNotIn('make a fly', page_text) input_box = self.browser.find_element_by_id('id_new_item') input_box.send_keys('Buy milk') input_box.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy milk') francis_list_url = self.browser.current_url self.assertRegex(francis_list_url, '/lists/.+') self.assertNotEqual(francis_list_url, edith_list_url) page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertIn('Buy milk', page_text) def test_layout_and_styling(self): self.browser.get(self.live_server_url) self.browser.set_window_size(1024, 768) input_box = self.browser.find_element_by_id('id_new_item') self.assertAlmostEqual( input_box.location['x'] + input_box.size['width'] / 2, 512, delta=10) input_box.send_keys('testing') input_box.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: testing') input_box = self.browser.find_element_by_id('id_new_item') self.assertAlmostEqual( input_box.location['x'] + input_box.size['width'] / 2, 512, delta=10 )
[]
[]
[ "STAGING_SERVER" ]
[]
["STAGING_SERVER"]
python
1
0
go/internal/initutil/node.go
package initutil import ( "context" "crypto/ed25519" "encoding/base64" "flag" "fmt" "os" "os/user" "strings" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth" grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap" grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags" grpcgw "github.com/grpc-ecosystem/grpc-gateway/runtime" datastore "github.com/ipfs/go-datastore" "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "gorm.io/gorm" "berty.tech/berty/v2/go/internal/accountutils" "berty.tech/berty/v2/go/internal/cryptoutil" "berty.tech/berty/v2/go/internal/datastoreutil" "berty.tech/berty/v2/go/internal/grpcutil" "berty.tech/berty/v2/go/internal/ipfsutil" "berty.tech/berty/v2/go/internal/lifecycle" "berty.tech/berty/v2/go/pkg/authtypes" "berty.tech/berty/v2/go/pkg/bertyauth" "berty.tech/berty/v2/go/pkg/bertymessenger" "berty.tech/berty/v2/go/pkg/bertyprotocol" "berty.tech/berty/v2/go/pkg/errcode" "berty.tech/berty/v2/go/pkg/messengertypes" "berty.tech/berty/v2/go/pkg/protocoltypes" ) const ( PerformancePreset = "performance" AnonymityPreset = "anonymity" VolatilePreset = "volatile" TorDisabled = "disabled" TorOptional = "optional" TorRequired = "required" ) func (m *Manager) SetupLocalProtocolServerFlags(fs *flag.FlagSet) { m.Node.Protocol.requiredByClient = true fs.StringVar(&m.Node.Protocol.PushPlatformToken, "node.default-push-token", "", "base 64 encoded default platform push token") fs.BoolVar(&m.Node.Protocol.ServiceInsecureMode, "node.service-insecure", false, "use insecure connection on services") m.SetupDatastoreFlags(fs) m.SetupLocalIPFSFlags(fs) // p2p.remote-ipfs } func (m *Manager) SetupProtocolAuth(fs *flag.FlagSet) { fs.StringVar(&m.Node.Protocol.AuthSecret, "node.auth-secret", "", "Protocol API Authentication Secret (base64 encoded)") fs.StringVar(&m.Node.Protocol.AuthPublicKey, "node.auth-pk", "", "Protocol API Authentication Public Key (base64 encoded)") } func (m *Manager) SetupEmptyGRPCListenersFlags(fs *flag.FlagSet) { fs.StringVar(&m.Node.GRPC.Listeners, "node.listeners", "", "gRPC API listeners") } func (m *Manager) SetupDefaultGRPCListenersFlags(fs *flag.FlagSet) { fs.StringVar(&m.Node.GRPC.Listeners, "node.listeners", "/ip4/127.0.0.1/tcp/9091/grpc", "gRPC API listeners") } func (m *Manager) SetupPresetFlags(fs *flag.FlagSet) { fs.StringVar(&m.Node.Preset, "preset", "", "applies various default values, see ADVANCED section below") m.longHelp = append(m.longHelp, [2]string{ "-preset=" + PerformancePreset, "better performance: current development defaults", }, [2]string{ "-preset=" + AnonymityPreset, "better privacy: -tor.mode=" + TorRequired + " -p2p.mdns=false -p2p.multipeer-connectivity=false -p2p.ble=false -p2p.nearby=false", }, [2]string{ "-preset=" + VolatilePreset, "similar to " + PerformancePreset + ` but optimize for a quick throwable node: -store.inmem=true -p2p.ipfs-api-listeners="" -p2p.swarm-listeners="" -p2p.webui-listener=""`, }) } func (m *Manager) DisableIPFSNetwork() { if m.Node.Protocol.ipfsNode != nil { panic("calling DisableIPFSNetwork, but IPFS is already initialized") } m.Node.Protocol.DisableIPFSNetwork = true } func (m *Manager) SetupRemoteNodeFlags(fs *flag.FlagSet) { fs.StringVar(&m.Node.GRPC.RemoteAddr, "node.remote-addr", "", "remote Berty gRPC API address") } func (m *Manager) SetupLocalMessengerServerFlags(fs *flag.FlagSet) { m.Node.Messenger.requiredByClient = true m.SetupLocalProtocolServerFlags(fs) m.SetupNotificationManagerFlags(fs) fs.StringVar(&m.Node.Messenger.ExportPathToRestore, "node.restore-export-path", "", "inits node from a specified export path") fs.BoolVar(&m.Node.Messenger.RebuildSqlite, "node.rebuild-db", false, "reconstruct messenger DB from OrbitDB logs") fs.BoolVar(&m.Node.Messenger.DisableGroupMonitor, "node.disable-group-monitor", false, "disable group monitoring") fs.StringVar(&m.Node.Messenger.DisplayName, "node.display-name", safeDefaultDisplayName(), "display name") // node.db-opts // see https://github.com/mattn/go-sqlite3#connection-string } func (m *Manager) applyPreset() error { switch m.Node.Preset { case "": // noop case PerformancePreset: // will do later case AnonymityPreset: // Force tor in this mode m.Node.Protocol.Tor.Mode = TorRequired // FIXME: raise an error if tor is not available on the node // Disable proximity communications m.Node.Protocol.MDNS = false m.Node.Protocol.MultipeerConnectivity = false m.Node.Protocol.Ble.Enable = false m.Node.Protocol.Nearby.Enable = false case VolatilePreset: m.Datastore.InMemory = true m.Node.Protocol.SwarmListeners = "" m.Node.Protocol.IPFSAPIListeners = "" m.Node.Protocol.IPFSWebUIListener = "" default: return fmt.Errorf("unknown preset: %q", m.Node.Preset) } return nil } func (m *Manager) GetLocalProtocolServer() (bertyprotocol.Service, error) { defer m.prepareForGetter()() if m.getContext().Err() != nil { return nil, m.getContext().Err() } return m.getLocalProtocolServer() } func (m *Manager) getPushSecretKey() (*[cryptoutil.KeySize]byte, error) { pushKey := &[cryptoutil.KeySize]byte{} if m.Node.Protocol.DevicePushKeyPath != "" { var err error _, pushKey, err = accountutils.GetDevicePushKeyForPath(m.Node.Protocol.DevicePushKeyPath, true) if err != nil { return nil, errcode.ErrInternal.Wrap(err) } } return pushKey, nil } func (m *Manager) getLocalProtocolServer() (bertyprotocol.Service, error) { if m.Node.Protocol.server != nil { return m.Node.Protocol.server, nil } logger, err := m.getLogger() if err != nil { return nil, errcode.TODO.Wrap(err) } rootDS, err := m.getRootDatastore() if err != nil { return nil, errcode.TODO.Wrap(err) } grpcServer, gatewayMux, err := m.getGRPCServer() if err != nil { return nil, errcode.TODO.Wrap(err) } _, _, err = m.getLocalIPFS() if err != nil { return nil, errcode.TODO.Wrap(err) } odb, err := m.getOrbitDB() if err != nil { return nil, errcode.TODO.Wrap(err) } // protocol service { var ( deviceDS = ipfsutil.NewDatastoreKeystore(datastoreutil.NewNamespacedDatastore(rootDS, datastore.NewKey(bertyprotocol.NamespaceDeviceKeystore))) deviceKS = cryptoutil.NewDeviceKeystore(deviceDS) ) pushKey, err := m.getPushSecretKey() if err != nil { return nil, errcode.TODO.Wrap(err) } // initialize new protocol client opts := bertyprotocol.Opts{ Host: m.Node.Protocol.ipfsNode.PeerHost, PubSub: m.Node.Protocol.pubsub, TinderDriver: m.Node.Protocol.discovery, IpfsCoreAPI: m.Node.Protocol.ipfsAPI, Logger: logger, RootDatastore: rootDS, DeviceKeystore: deviceKS, OrbitDB: odb, PushKey: pushKey, GRPCInsecureMode: m.Node.Protocol.ServiceInsecureMode, } m.Node.Protocol.server, err = bertyprotocol.New(m.getContext(), opts) if err != nil { return nil, errcode.TODO.Wrap(err) } // register grpc service protocoltypes.RegisterProtocolServiceServer(grpcServer, m.Node.Protocol.server) if err := protocoltypes.RegisterProtocolServiceHandlerServer(m.getContext(), gatewayMux, m.Node.Protocol.server); err != nil { return nil, errcode.TODO.Wrap(err) } } m.initLogger.Debug("protocol server initialized and cached") return m.Node.Protocol.server, nil } func (m *Manager) GetGRPCClientConn() (*grpc.ClientConn, error) { defer m.prepareForGetter()() return m.getGRPCClientConn() } func (m *Manager) getGRPCClientConn() (*grpc.ClientConn, error) { m.applyDefaults() if m.Node.GRPC.clientConn != nil { return m.Node.GRPC.clientConn, nil } clientOpts := []grpc.DialOption(nil) if m.Node.GRPC.RemoteAddr != "" { clientOpts = append(clientOpts, grpc.WithInsecure()) // make a flag for this? cc, err := grpc.Dial(m.Node.GRPC.RemoteAddr, clientOpts...) if err != nil { return nil, errcode.TODO.Wrap(err) } m.Node.GRPC.clientConn = cc } else { // ensure protocol and messenger are initialized { // restore store if provided if err := m.restoreMessengerDataFromExport(); err != nil { return nil, errcode.TODO.Wrap(err) } if m.Node.Protocol.requiredByClient { _, err := m.getLocalProtocolServer() if err != nil { return nil, errcode.TODO.Wrap(err) } } if m.Node.Messenger.requiredByClient { _, err := m.getLocalMessengerServer() if err != nil { return nil, errcode.TODO.Wrap(err) } } } // gRPC server serverOpts := []grpc.ServerOption{} // FIXME: tracing grpcServer := grpc.NewServer(serverOpts...) // buffer-based client conn bl := grpcutil.NewBufListener(m.getContext(), 256*1024) cc, err := bl.NewClientConn(clientOpts...) if err != nil { return nil, errcode.TODO.Wrap(err) } if m.Node.Protocol.server != nil { protocoltypes.RegisterProtocolServiceServer(grpcServer, m.Node.Protocol.server) } if m.Node.Messenger.server != nil { messengertypes.RegisterMessengerServiceServer(grpcServer, m.Node.Messenger.server) } m.Node.GRPC.bufServerListener = bl m.Node.GRPC.bufServer = grpcServer m.Node.GRPC.clientConn = cc go func() { err := m.Node.GRPC.bufServer.Serve(bl) if err != nil && !(err == grpc.ErrServerStopped || err.Error() == "closed") { panic(err) } }() } m.initLogger.Debug("gRPC client conn initialized and cached") return m.Node.GRPC.clientConn, nil } func (m *Manager) GetMessengerClient() (messengertypes.MessengerServiceClient, error) { defer m.prepareForGetter()() return m.getMessengerClient() } func (m *Manager) GetStorageKey() ([]byte, error) { defer m.prepareForGetter()() return m.getStorageKey() } func (m *Manager) getStorageKey() ([]byte, error) { if m.storageKey != nil { return m.storageKey, nil } if m.nativeKeystore == nil { return nil, nil } key, err := accountutils.GetOrCreateStorageKey(m.nativeKeystore) if err != nil { return nil, err } m.storageKey = key return m.storageKey, nil } func (m *Manager) SetLifecycleManager(manager *lifecycle.Manager) { m.mutex.Lock() defer m.mutex.Unlock() // the following check is here to help developers avoid having // strange states by using multiple instances of the lifecycle manager if m.Node.Messenger.lcmanager != nil { panic("initutil.SetLifecycleManager was called but there was already an existing value") } m.Node.Messenger.lcmanager = manager } func (m *Manager) GetLifecycleManager() *lifecycle.Manager { defer m.prepareForGetter()() return m.getLifecycleManager() } func (m *Manager) getLifecycleManager() *lifecycle.Manager { if m.Node.Messenger.lcmanager != nil { return m.Node.Messenger.lcmanager } m.Node.Messenger.lcmanager = lifecycle.NewManager(bertymessenger.StateActive) return m.Node.Messenger.lcmanager } func (m *Manager) getMessengerClient() (messengertypes.MessengerServiceClient, error) { if m.Node.Messenger.client != nil { return m.Node.Messenger.client, nil } grpcClient, err := m.getGRPCClientConn() if err != nil { return nil, errcode.TODO.Wrap(err) } m.Node.Messenger.client = messengertypes.NewMessengerServiceClient(grpcClient) m.initLogger.Debug("messenger client initialized and cached") return m.Node.Messenger.client, nil } func (m *Manager) GetProtocolClient() (protocoltypes.ProtocolServiceClient, error) { defer m.prepareForGetter()() return m.getProtocolClient() } func (m *Manager) getProtocolClient() (protocoltypes.ProtocolServiceClient, error) { if m.Node.Protocol.client != nil { return m.Node.Protocol.client, nil } grpcClient, err := m.getGRPCClientConn() if err != nil { return nil, errcode.TODO.Wrap(err) } m.Node.Protocol.client = protocoltypes.NewProtocolServiceClient(grpcClient) m.initLogger.Debug("protocol client initialized and cached") return m.Node.Protocol.client, nil } func (m *Manager) GetGRPCServer() (*grpc.Server, *grpcgw.ServeMux, error) { defer m.prepareForGetter()() return m.getGRPCServer() } func (m *Manager) getGRPCServer() (*grpc.Server, *grpcgw.ServeMux, error) { m.applyDefaults() if m.Node.GRPC.server != nil { return m.Node.GRPC.server, m.Node.GRPC.gatewayMux, nil } logger, err := m.getLogger() if err != nil { return nil, nil, err } grpcLogger := logger.Named("grpc") // Define customfunc to handle panic panicHandler := func(p interface{}) (err error) { return status.Errorf(codes.Unknown, "panic recover: %v", p) } // Shared options for the logger, with a custom gRPC code to log level function. recoverOpts := []grpc_recovery.Option{ grpc_recovery.WithRecoveryHandler(panicHandler), } zapOpts := []grpc_zap.Option{} // override grpc logger ReplaceGRPCLogger(grpcLogger) // noop auth func authFunc := func(ctx context.Context) (context.Context, error) { return ctx, nil } if m.Node.Protocol.AuthSecret != "" || m.Node.Protocol.AuthPublicKey != "" { man, err := getAuthTokenVerifier(m.Node.Protocol.AuthSecret, m.Node.Protocol.AuthPublicKey) if err != nil { return nil, nil, errcode.TODO.Wrap(err) } serviceID := m.Node.Protocol.ServiceID switch serviceID { case authtypes.ServiceReplicationID: authFunc = man.GRPCAuthInterceptor(serviceID) case "": logger.Warn("GRPCAuth: Internal field ServiceID should not be empty", zap.String("serviceID", serviceID)) default: } } grpcOpts := []grpc.ServerOption{ grpc_middleware.WithUnaryServerChain( grpc_recovery.UnaryServerInterceptor(recoverOpts...), grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)), grpc_zap.UnaryServerInterceptor(grpcLogger, zapOpts...), grpc_auth.UnaryServerInterceptor(authFunc), ), grpc_middleware.WithStreamServerChain( grpc_recovery.StreamServerInterceptor(recoverOpts...), grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)), grpc_zap.StreamServerInterceptor(grpcLogger, zapOpts...), grpc_auth.StreamServerInterceptor(authFunc), ), } grpcServer := grpc.NewServer(grpcOpts...) grpcGatewayMux := grpcgw.NewServeMux() if m.Node.GRPC.Listeners != "" { addrs := strings.Split(m.Node.GRPC.Listeners, ",") maddrs, err := ipfsutil.ParseAddrs(addrs...) if err != nil { return nil, nil, err } m.Node.GRPC.listeners = make([]grpcutil.Listener, len(maddrs)) server := grpcutil.Server{ GRPCServer: grpcServer, GatewayMux: grpcGatewayMux, } for idx, maddr := range maddrs { maddrStr := maddr.String() l, err := grpcutil.Listen(maddr) if err != nil { return nil, nil, errcode.TODO.Wrap(err) } m.Node.GRPC.listeners[idx] = l m.workers.Add(func() error { m.initLogger.Info("serving", zap.String("maddr", maddrStr)) return server.Serve(l) }, func(error) { l.Close() m.initLogger.Debug("closing done", zap.String("maddr", maddrStr)) }) } } m.initLogger.Debug("gRPC server initialized and cached") m.Node.GRPC.server = grpcServer m.Node.GRPC.gatewayMux = grpcGatewayMux return m.Node.GRPC.server, m.Node.GRPC.gatewayMux, nil } func (m *Manager) GetGRPCListeners() []grpcutil.Listener { m.mutex.Lock() defer m.mutex.Unlock() return m.Node.GRPC.listeners } func (m *Manager) GetMessengerDB() (*gorm.DB, error) { defer m.prepareForGetter()() return m.getMessengerDB() } func (m *Manager) getMessengerDB() (*gorm.DB, error) { if m.Node.Messenger.db != nil { return m.Node.Messenger.db, nil } logger, err := m.getLogger() if err != nil { return nil, errcode.TODO.Wrap(err) } dir, err := m.getDatastoreDir() if err != nil { return nil, errcode.TODO.Wrap(err) } key, err := m.getStorageKey() if err != nil { return nil, errcode.TODO.Wrap(err) } m.Node.Messenger.db, m.Node.Messenger.dbCleanup, err = accountutils.GetMessengerDBForPath(dir, key, logger) if err != nil { return nil, errcode.TODO.Wrap(err) } return m.Node.Messenger.db, nil } func (m *Manager) GetReplicationDB() (*gorm.DB, error) { defer m.prepareForGetter()() return m.getReplicationDB() } func (m *Manager) getReplicationDB() (*gorm.DB, error) { if m.Node.Replication.db != nil { return m.Node.Replication.db, nil } logger, err := m.getLogger() if err != nil { return nil, errcode.TODO.Wrap(err) } dir, err := m.getDatastoreDir() if err != nil { return nil, errcode.TODO.Wrap(err) } m.Node.Replication.db, m.Node.Replication.dbCleanup, err = accountutils.GetReplicationDBForPath(dir, logger) if err != nil { return nil, errcode.TODO.Wrap(err) } return m.Node.Replication.db, nil } func (m *Manager) restoreMessengerDataFromExport() error { if m.Node.Messenger.ExportPathToRestore == "" { return nil } f, err := os.Open(m.Node.Messenger.ExportPathToRestore) if err != nil { return err } defer func() { _ = f.Close() }() m.Node.Messenger.ExportPathToRestore = "" logger, err := m.getLogger() if err != nil { return errcode.ErrInternal.Wrap(err) } coreAPI, _, err := m.getLocalIPFS() if err != nil { return errcode.ErrInternal.Wrap(err) } odb, err := m.getOrbitDB() if err != nil { return errcode.ErrInternal.Wrap(err) } m.Node.Messenger.localDBState = &messengertypes.LocalDatabaseState{} if err := bertymessenger.RestoreFromAccountExport(m.ctx, f, coreAPI, odb, m.Node.Messenger.localDBState, logger); err != nil { return errcode.ErrInternal.Wrap(err) } return nil } func (m *Manager) GetLocalMessengerServer() (messengertypes.MessengerServiceServer, error) { defer m.prepareForGetter()() return m.getLocalMessengerServer() } func (m *Manager) getLocalMessengerServer() (messengertypes.MessengerServiceServer, error) { if m.Node.Messenger.server != nil { return m.Node.Messenger.server, nil } // restore store if provided if err := m.restoreMessengerDataFromExport(); err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to restore messenger data from export: %w", err)) } // logger logger, err := m.getLogger() if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init logger: %w", err)) } // messenger db db, err := m.getMessengerDB() if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init messenger db: %w", err)) } // grpc server grpcServer, gatewayMux, err := m.getGRPCServer() if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to grpc server: %w", err)) } // configure notifications notifmanager, err := m.getNotificationManager() if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init notification manager: %w", err)) } // local protocol server protocolServer, err := m.getLocalProtocolServer() if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init local protocol server: %w", err)) } // protocol client protocolClient, err := bertyprotocol.NewClient(m.getContext(), protocolServer, nil, nil) // FIXME: setup tracing if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init protocol client: %w", err)) } m.Node.Messenger.protocolClient = protocolClient lcmanager := m.getLifecycleManager() pushPlatformToken := (*protocoltypes.PushServiceReceiver)(nil) if m.Node.Protocol.PushPlatformToken != "" { pushPlatformToken = &protocoltypes.PushServiceReceiver{} data, err := base64.RawURLEncoding.DecodeString(m.Node.Protocol.PushPlatformToken) if err != nil { return nil, errcode.ErrDeserialization.Wrap(err) } if err := pushPlatformToken.Unmarshal(data); err != nil { return nil, errcode.ErrDeserialization.Wrap(err) } } // messenger server opts := bertymessenger.Opts{ EnableGroupMonitor: !m.Node.Messenger.DisableGroupMonitor, DB: db, Logger: logger, NotificationManager: notifmanager, LifeCycleManager: lcmanager, StateBackup: m.Node.Messenger.localDBState, Ring: m.Logging.ring, PlatformPushToken: pushPlatformToken, } messengerServer, err := bertymessenger.New(protocolClient, &opts) if err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to init messenger server: %w", err)) } // register grpc service messengertypes.RegisterMessengerServiceServer(grpcServer, messengerServer) if err := messengertypes.RegisterMessengerServiceHandlerServer(m.getContext(), gatewayMux, messengerServer); err != nil { return nil, errcode.TODO.Wrap(fmt.Errorf("unable to register messenger service handler: %w", err)) } m.Node.Messenger.lcmanager = lcmanager m.Node.Messenger.server = messengerServer m.initLogger.Debug("messenger server initialized and cached") return m.Node.Messenger.server, nil } func getAuthTokenVerifier(secret, pk string) (*bertyauth.AuthTokenVerifier, error) { rawSecret, err := base64.RawStdEncoding.DecodeString(secret) if err != nil { return nil, err } rawPK, err := base64.RawStdEncoding.DecodeString(pk) if err != nil { return nil, err } if len(rawPK) != ed25519.PublicKeySize { return nil, fmt.Errorf("empty or invalid pk size") } return bertyauth.NewAuthTokenVerifier(rawSecret, rawPK) } func safeDefaultDisplayName() string { var name string current, err := user.Current() if err == nil { name = current.Username } if name == "" { name = os.Getenv("USER") } if name == "" { name = "Anonymous4242" } return fmt.Sprintf("%s (cli)", name) }
[ "\"USER\"" ]
[]
[ "USER" ]
[]
["USER"]
go
1
0
cli/export.py
import argparse import os from typing import List def api_to_dict(): """Convert Jina API to a dict :return: dict """ from jina import __version__ from jina.parsers import get_main_parser parsers = get_main_parser()._actions[-1].choices all_d = { 'name': 'Jina', 'description': 'Jina is the cloud-native neural search solution powered by state-of-the-art AI and deep ' 'learning technology', 'license': 'Apache 2.0', 'vendor': 'Jina AI Limited', 'source': 'https://github.com/jina-ai/jina/tree/' + os.environ.get('JINA_VCS_VERSION', 'master'), 'url': 'https://jina.ai', 'docs': 'https://docs.jina.ai', 'authors': '[email protected]', 'version': __version__, 'methods': [], 'revision': os.environ.get('JINA_VCS_VERSION'), } for p_name in parsers.keys(): d = {'name': p_name, 'options': []} for ddd in _export_parser_args( lambda *x: get_main_parser()._actions[-1].choices[p_name], type_as_str=True ): d['options'].append(ddd) all_d['methods'].append(d) return all_d def _export_parser_args(parser_fn, type_as_str: bool = False, **kwargs): from jina.enums import BetterEnum from argparse import _StoreAction, _StoreTrueAction from jina.parsers.helper import KVAppendAction, _SHOW_ALL_ARGS port_attr = ('help', 'choices', 'default', 'required', 'option_strings', 'dest') parser = parser_fn(**kwargs) parser2 = parser_fn(**kwargs) random_dest = set() for a, b in zip(parser._actions, parser2._actions): if a.default != b.default: random_dest.add(a.dest) for a in parser._actions: if isinstance(a, (_StoreAction, _StoreTrueAction, KVAppendAction)): if not _SHOW_ALL_ARGS and a.help == argparse.SUPPRESS: continue ddd = {p: getattr(a, p) for p in port_attr} if isinstance(a, _StoreTrueAction): ddd['type'] = bool elif isinstance(a, KVAppendAction): ddd['type'] = dict else: ddd['type'] = a.type if ddd['choices']: ddd['choices'] = [ str(k) if isinstance(k, BetterEnum) else k for k in ddd['choices'] ] ddd['type'] = str if isinstance(ddd['default'], BetterEnum): ddd['default'] = str(ddd['default']) ddd['type'] = str if ddd['type'] == str and (a.nargs == '*' or a.nargs == '+'): ddd['type'] = List[str] else: continue if a.dest in random_dest: ddd['default_random'] = True from jina.helper import random_identity, random_port if isinstance(a.default, str): ddd['default_factory'] = random_identity.__name__ elif isinstance(a.default, int): ddd['default_factory'] = random_port.__name__ else: ddd['default_random'] = False if type_as_str: ddd['type'] = getattr(ddd['type'], '__name__', str(ddd['type'])) ddd['name'] = ddd.pop('dest') yield ddd
[]
[]
[ "JINA_VCS_VERSION" ]
[]
["JINA_VCS_VERSION"]
python
1
0
examples/bipedal_walk.py
import os import sys import numpy as np import crocoddyl import example_robot_data import pinocchio from crocoddyl.utils.biped import SimpleBipedGaitProblem, plotSolution WITHDISPLAY = 'display' in sys.argv or 'CROCODDYL_DISPLAY' in os.environ WITHPLOT = 'plot' in sys.argv or 'CROCODDYL_PLOT' in os.environ # Creating the lower-body part of Talos talos_legs = example_robot_data.load('talos_legs') # Defining the initial state of the robot q0 = talos_legs.model.referenceConfigurations['half_sitting'].copy() v0 = pinocchio.utils.zero(talos_legs.model.nv) x0 = np.concatenate([q0, v0]) # Setting up the 3d walking problem rightFoot = 'right_sole_link' leftFoot = 'left_sole_link' gait = SimpleBipedGaitProblem(talos_legs.model, rightFoot, leftFoot) # Setting up all tasks GAITPHASES = \ [{'walking': {'stepLength': 0.6, 'stepHeight': 0.1, 'timeStep': 0.03, 'stepKnots': 35, 'supportKnots': 10}}, {'walking': {'stepLength': 0.6, 'stepHeight': 0.1, 'timeStep': 0.03, 'stepKnots': 35, 'supportKnots': 10}}, {'walking': {'stepLength': 0.6, 'stepHeight': 0.1, 'timeStep': 0.03, 'stepKnots': 35, 'supportKnots': 10}}, {'walking': {'stepLength': 0.6, 'stepHeight': 0.1, 'timeStep': 0.03, 'stepKnots': 35, 'supportKnots': 10}}] cameraTF = [3., 3.68, 0.84, 0.2, 0.62, 0.72, 0.22] solver = [None] * len(GAITPHASES) for i, phase in enumerate(GAITPHASES): for key, value in phase.items(): if key == 'walking': # Creating a walking problem solver[i] = crocoddyl.SolverDDP( gait.createWalkingProblem(x0, value['stepLength'], value['stepHeight'], value['timeStep'], value['stepKnots'], value['supportKnots'])) solver[i].th_stop = 1e-7 # Added the callback functions print('*** SOLVE ' + key + ' ***') if WITHDISPLAY and WITHPLOT: display = crocoddyl.GepettoDisplay(talos_legs, 4, 4, cameraTF, frameNames=[rightFoot, leftFoot]) solver[i].setCallbacks( [crocoddyl.CallbackLogger(), crocoddyl.CallbackVerbose(), crocoddyl.CallbackDisplay(display)]) elif WITHDISPLAY: display = crocoddyl.GepettoDisplay(talos_legs, 4, 4, cameraTF, frameNames=[rightFoot, leftFoot]) solver[i].setCallbacks([crocoddyl.CallbackVerbose(), crocoddyl.CallbackDisplay(display)]) elif WITHPLOT: solver[i].setCallbacks([ crocoddyl.CallbackLogger(), crocoddyl.CallbackVerbose(), ]) else: solver[i].setCallbacks([crocoddyl.CallbackVerbose()]) # Solving the problem with the DDP solver xs = [x0] * (solver[i].problem.T + 1) us = solver[i].problem.quasiStatic([x0] * solver[i].problem.T) solver[i].solve(xs, us, 100, False) # Defining the final state as initial one for the next phase x0 = solver[i].xs[-1] # Display the entire motion if WITHDISPLAY: display = crocoddyl.GepettoDisplay(talos_legs, frameNames=[rightFoot, leftFoot]) for i, phase in enumerate(GAITPHASES): display.displayFromSolver(solver[i]) # Plotting the entire motion if WITHPLOT: plotSolution(solver, bounds=False, figIndex=1, show=False) for i, phase in enumerate(GAITPHASES): title = list(phase.keys())[0] + " (phase " + str(i) + ")" log = solver[i].getCallbacks()[0] crocoddyl.plotConvergence(log.costs, log.u_regs, log.x_regs, log.grads, log.stops, log.steps, figTitle=title, figIndex=i + 3, show=True if i == len(GAITPHASES) - 1 else False)
[]
[]
[]
[]
[]
python
0
0
.github/automation/main.py
import os import json import requests import sys import semver import github3 from jinja2 import Environment, FileSystemLoader LATEST_RELEASES_PATH_TF = 'https://api.github.com/repos/hashicorp/terraform/releases/latest' LATEST_RELEASES_PATH_DNX_TF = 'https://api.github.com/repos/DNXLabs/docker-terraform/releases/latest' GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') GITHUB_REPOSITORY_ID = '143522585' DEFAULT_BRANCH = os.getenv('DEFAULT_BRANCH', 'master') # Terraform upstream response_release_tf = requests.get( LATEST_RELEASES_PATH_TF, headers={'Authorization': 'token ' + GITHUB_TOKEN}) release_tf_json_obj = json.loads(response_release_tf.text) tag_name_tf = release_tf_json_obj.get('tag_name').replace('v', '') draft_tf = release_tf_json_obj.get('draft') prerelease_tf = release_tf_json_obj.get('prerelease') # DNX docker terraform response_release_docker_tf = requests.get( LATEST_RELEASES_PATH_DNX_TF, headers={'Authorization': 'token ' + GITHUB_TOKEN}) release_docker_tf_json_obj = json.loads(response_release_docker_tf.text) tag_name_docker_tf = release_docker_tf_json_obj.get('tag_name').replace('v', '').split('-')[0] if draft_tf or prerelease_tf: print('The release is a draft of prelease.') sys.exit() print('Upstream version: %s' % tag_name_tf) print('DNX docker-terraform version: %s' % tag_name_docker_tf) if semver.compare(tag_name_tf, tag_name_docker_tf) != 1: print('Nothing to do, the upstream is in the same version or lower version.') sys.exit() # Generate Dockerfile template with new upstream version root = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(root, 'templates') env = Environment( loader = FileSystemLoader(templates_dir) ) template = env.get_template('Dockerfile.j2') filename = os.path.join(root, 'Dockerfile') with open(filename, 'w') as fh: fh.write(template.render( tag_name_tf = tag_name_tf )) # Add and push changes to github repo with open('Dockerfile') as f: docker_file = f.read() # Connect to GitHub API and push the changes. github = github3.login(token=GITHUB_TOKEN) repository = github.repository_with_id(GITHUB_REPOSITORY_ID) github_dockerfile = repository.file_contents('/Dockerfile', ref=DEFAULT_BRANCH) pushed_index_change = github_dockerfile.update( 'Bump Terraform version to v%s' % tag_name_tf, docker_file.encode('utf-8'), branch=DEFAULT_BRANCH ) print('Pushed commit {} to {} branch:\n {}'.format( pushed_index_change['commit'].sha, DEFAULT_BRANCH, pushed_index_change['commit'].message, )) #Create new release data = { 'name': '%s-dnx1' % tag_name_tf, 'tag_name': '%s-dnx1' % tag_name_tf, 'body': '- Bump Terraform version to v%s.' % tag_name_tf } headers = { 'Authorization': 'token %s' % GITHUB_TOKEN, 'Accept': 'application/vnd.github.v3+json' } response_new_release = requests.post( 'https://api.github.com/repos/DNXLabs/docker-terraform/releases', data=json.dumps(data), headers=headers )
[]
[]
[ "GITHUB_TOKEN", "DEFAULT_BRANCH" ]
[]
["GITHUB_TOKEN", "DEFAULT_BRANCH"]
python
2
0
controllers/main.go
package controllers import ( "context" "crypto/tls" "fmt" "net/http" "os" "time" as "github.com/aerospike/aerospike-client-go/v5" log "github.com/sirupsen/logrus" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/aerospike-community/amc/common" "github.com/aerospike-community/amc/controllers/middleware/sessions" "github.com/aerospike-community/amc/models" ) var ( _observer *models.ObserverT _defaultClientPolicy = as.NewClientPolicy() registerEnterpriseAPI func(*echo.Echo) _server *echo.Echo ) func postSessionTerminate(c echo.Context) error { invalidateSession(c) return c.JSONBlob(http.StatusOK, []byte(`{"status": "success"}`)) } func getDebug(c echo.Context) error { res := _observer.DebugStatus() if res.On { return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "debugging": "ON", "initiator": res.Initiator, "isOriginInitiator": res.Initiator == c.Request().RemoteAddr, "start_time": res.StartTime.UnixNano() / 1e6, //1484923724160, }) } return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "debugging": "OFF", "initiator": nil, }) } func postDebug(c echo.Context) error { form := struct { Service string `form:"service"` DurationMins int `form:"duration"` Username string `form:"username"` }{} c.Bind(&form) var res models.DebugStatus switch form.Service { case "start": res = _observer.StartDebug(c.Request().RemoteAddr, time.Duration(form.DurationMins)*time.Minute) case "restart": res = _observer.StartDebug(c.Request().RemoteAddr, time.Duration(form.DurationMins)*time.Minute) case "stop": res = _observer.StopDebug() default: return c.JSON(http.StatusOK, errorMap("Cluster not found")) } if res.On { return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "debugging": "ON", "initiator": res.Initiator, "start_time": res.StartTime.UnixNano() / 1e6, //1484923724160, "service": form.Service, }) } return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "debugging": "OFF", "initiator": nil, "service": form.Service, }) } func getAMCVersion(c echo.Context) error { return c.JSONBlob(http.StatusOK, []byte(fmt.Sprintf(`{"amc_version": "%s", "amc_type": "%s"}`, common.AMCVersion, common.AMCEdition))) } // ShutdownServer - shutdown server func ShutdownServer() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := _server.Shutdown(ctx); err != nil { log.Fatal(err) } } // Server - init server using config func Server(config *common.Config) { _observer = models.New(config) _defaultClientPolicy.Timeout = time.Duration(config.AMC.Timeout) * time.Second if _defaultClientPolicy.Timeout <= 0 { _defaultClientPolicy.Timeout = 30 * time.Second } _defaultClientPolicy.LimitConnectionsToQueueSize = true _defaultClientPolicy.ConnectionQueueSize = 1 e := echo.New() e.Use(middleware.SecureWithConfig(middleware.SecureConfig{ XSSProtection: "1; mode=block", ContentTypeNosniff: "nosniff", XFrameOptions: "SAMEORIGIN", HSTSMaxAge: 3600, HSTSExcludeSubdomains: false, // ContentSecurityPolicy: "default-src 'self';script-src 'self' 'unsafe-eval'; object-src 'self'", // does not work with underscore.js })) // Avoid stale connections e.Server.ReadTimeout = 30 * time.Second e.Server.WriteTimeout = 30 * time.Second store := sessions.NewCookieStore([]byte("amc-secret-key")) e.Use(sessions.Sessions("amc_session", store)) if config.AMC.StaticPath == "" { log.Fatalln("No static dir has been set in the config file. Quiting...") } log.Infoln("Static files path is being set to:" + config.AMC.StaticPath) e.Static("/", config.AMC.StaticPath) e.Static("/static", config.AMC.StaticPath) // Middleware if !common.AMCIsProd() { // e.Logger.SetOutput(log.StandardLogger().Writer()) // e.Use(middleware.Logger()) } else { e.Use(middleware.Recover()) } // Basic Authentication Middleware Setup basicAuthUser := os.Getenv("AMC_AUTH_USER") if basicAuthUser == "" { basicAuthUser = config.BasicAuth.User } basicAuthPassword := os.Getenv("AMC_AUTH_PASSWORD") if basicAuthPassword == "" { basicAuthPassword = config.BasicAuth.Password } if basicAuthUser != "" { e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) { if username == basicAuthUser && password == basicAuthPassword { return true, nil } return false, nil })) } e.Use(middleware.GzipWithConfig(middleware.DefaultGzipConfig)) // e.Use(middleware.CSRFWithConfig(middleware.DefaultCSRFConfig)) e.Use(middleware.SecureWithConfig(middleware.DefaultSecureConfig)) // Routes e.POST("/session-terminate", postSessionTerminate) e.GET("/aerospike/service/debug", getDebug) e.POST("/aerospike/service/clusters/:clusterUUID/debug", postDebug) // cluster does not matter here e.GET("/get_amc_version", getAMCVersion) e.GET("/get_current_monitoring_clusters", getCurrentMonitoringClusters) e.POST("/set-update-interval/:clusterUUID", sessionValidator(setClusterUpdateInterval)) e.GET("/aerospike/service/clusters/:clusterUUID", sessionValidator(getCluster)) e.POST("/aerospike/service/clusters/:clusterUUID/logout", postRemoveClusterFromSession) e.GET("/aerospike/service/clusters/:clusterUUID/udfs", sessionValidator(getClusterUDFs)) e.POST("/aerospike/service/clusters/:clusterUUID/drop_udf", sessionValidator(postClusterDropUDF)) e.POST("/aerospike/service/clusters/:clusterUUID/add_udf", sessionValidator(postClusterAddUDF)) e.GET("/aerospike/service/clusters/:clusterUUID/throughput", sessionValidator(getClusterThroughput)) e.GET("/aerospike/service/clusters/:clusterUUID/throughput_history", sessionValidator(getClusterThroughputHistory)) e.GET("/aerospike/service/clusters/:clusterUUID/basic", sessionValidator(getClusterBasic)) e.POST("/aerospike/service/clusters/:clusterUUID/add_node", sessionValidator(postAddClusterNodes)) e.GET("/aerospike/service/clusters/:clusterUUID/nodes/:nodes", sessionValidator(getClusterNodes)) e.GET("/aerospike/service/clusters/:clusterUUID/nodes/:node/allconfig", sessionValidator(getClusterNodeAllConfig)) e.POST("/aerospike/service/clusters/:clusterUUID/nodes/:nodes/setconfig", sessionValidator(setClusterNodesConfig)) e.POST("/aerospike/service/clusters/:clusterUUID/nodes/:node/switch_off", sessionValidator(postSwitchNodeOff)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespaces", sessionValidator(getClusterNamespaces)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/nodes/:nodes", sessionValidator(getClusterNamespaceNodes)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/nodes/:node/allconfig", sessionValidator(getClusterNamespaceAllConfig)) e.POST("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/nodes/:node/setconfig", sessionValidator(setClusterNamespaceConfig)) e.GET("/aerospike/service/clusters/:clusterUUID/nodes/:node/allstats", sessionValidator(getClusterNodeAllStats)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/nodes/:node/allstats", sessionValidator(getClusterNamespaceNodeAllStats)) e.GET("/aerospike/service/clusters/:clusterUUID/xdr/:port/nodes/:node/allstats", sessionValidator(getClusterXdrNodeAllStats)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/sindexes/:sindex/nodes/:node/allstats", sessionValidator(getClusterNamespaceSindexNodeAllStats)) e.POST("/aerospike/service/clusters/:clusterUUID/namespace/:namespace/add_index", sessionValidator(postClusterAddIndex)) e.POST("/aerospike/service/clusters/:clusterUUID/namespace/:namespace/drop_index", sessionValidator(postClusterDropIndex)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/sindexes", sessionValidator(getClusterNamespaceSindexes)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/sets", sessionValidator(getClusterNamespaceSets)) e.GET("/aerospike/service/clusters/:clusterUUID/namespaces/:namespace/storage", sessionValidator(getClusterNamespaceStorage)) e.GET("/aerospike/service/clusters/:clusterUUID/nodes/:nodes/jobs", getClusterNodesJobs) e.GET("/aerospike/service/clusters/:clusterUUID/jobs/nodes/:node", getClusterJobsNode) e.POST("/aerospike/service/clusters/get-cluster-id", postGetClusterID) if registerEnterpriseAPI != nil { registerEnterpriseAPI(e) } log.Infof("Starting AMC server, version: %s %s", common.AMCVersion, common.AMCEdition) _server = e // Start server if config.AMC.CertFile != "" { log.Infof("In HTTPS (secure) Mode") tlsConfig := new(tls.Config) tlsConfig.Certificates = make([]tls.Certificate, 1) var err error tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(config.AMC.CertFile, config.AMC.KeyFile) if err != nil { log.Fatalln("Error reading the certificate files from disk: " + err.Error()) } if config.AMC.ForceTLS12 || config.AMC.MaxTLSSecurity { log.Infof("Forcing TLS v1.2") tlsConfig.MinVersion = tls.VersionTLS12 } if config.AMC.MaxTLSSecurity { log.Infof("Forcing Maximum security mode for TLS (Uses >=256 bit curves, ciphersuites and prefers server cypher suites)") tlsConfig.CurvePreferences = []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256} tlsConfig.PreferServerCipherSuites = true tlsConfig.CipherSuites = []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_256_CBC_SHA, } } e.TLSServer.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) e.TLSServer.TLSConfig = tlsConfig e.TLSServer.Addr = config.AMC.Bind // redirect all http requests to https e.Pre(middleware.HTTPSRedirect()) // starts a listener for normal http port to support http -> https redirect log.Errorln(e.StartServer(e.TLSServer)) } else { log.Infof("In HTTP (insecure) Mode.") log.Errorln(e.Start(config.AMC.Bind)) } }
[ "\"AMC_AUTH_USER\"", "\"AMC_AUTH_PASSWORD\"" ]
[]
[ "AMC_AUTH_PASSWORD", "AMC_AUTH_USER" ]
[]
["AMC_AUTH_PASSWORD", "AMC_AUTH_USER"]
go
2
0
plugin/converter/jsonnet/jsonnet.go
package jsonnet import ( "bytes" "fmt" "strconv" "github.com/drone/drone/core" "github.com/google/go-jsonnet" ) const repo = "repo." const build = "build." const param = "param." func Parse(req *core.ConvertArgs, template *core.Template, templateData map[string]interface{}) (string, error) { vm := jsonnet.MakeVM() vm.MaxStack = 500 vm.StringOutput = false vm.ErrorFormatter.SetMaxStackTraceSize(20) //map build/repo parameters if req.Build != nil { mapBuild(req.Build, vm) } if req.Repo != nil { mapRepo(req.Repo, vm) } var jsonnetFile string var jsonentFileName string if template != nil { jsonnetFile = template.Data jsonentFileName = template.Name } else { jsonnetFile = req.Config.Data jsonentFileName = req.Repo.Config } // map external inputs if len(templateData) != 0 { for k, v := range templateData { key := fmt.Sprintf("input." + k) val := fmt.Sprint(v) vm.ExtVar(key, val) } } // convert the jsonnet file to yaml buf := new(bytes.Buffer) docs, err := vm.EvaluateSnippetStream(jsonentFileName, jsonnetFile) if err != nil { doc, err2 := vm.EvaluateSnippet(jsonentFileName, jsonnetFile) if err2 != nil { return "", err } docs = append(docs, doc) } // the jsonnet vm returns a stream of yaml documents // that need to be combined into a single yaml file. for _, doc := range docs { buf.WriteString("---") buf.WriteString("\n") buf.WriteString(doc) } return buf.String(), nil } func mapBuild(v *core.Build, vm *jsonnet.VM) { vm.ExtVar(build+"event", v.Event) vm.ExtVar(build+"action", v.Action) vm.ExtVar(build+"environment", v.Deploy) vm.ExtVar(build+"link", v.Link) vm.ExtVar(build+"branch", v.Target) vm.ExtVar(build+"source", v.Source) vm.ExtVar(build+"before", v.Before) vm.ExtVar(build+"after", v.After) vm.ExtVar(build+"target", v.Target) vm.ExtVar(build+"ref", v.Ref) vm.ExtVar(build+"commit", v.After) vm.ExtVar(build+"ref", v.Ref) vm.ExtVar(build+"title", v.Title) vm.ExtVar(build+"message", v.Message) vm.ExtVar(build+"source_repo", v.Fork) vm.ExtVar(build+"author_login", v.Author) vm.ExtVar(build+"author_name", v.AuthorName) vm.ExtVar(build+"author_email", v.AuthorEmail) vm.ExtVar(build+"author_avatar", v.AuthorAvatar) vm.ExtVar(build+"sender", v.Sender) fromMap(v.Params, vm) } func mapRepo(v *core.Repository, vm *jsonnet.VM) { vm.ExtVar(repo+"uid", v.UID) vm.ExtVar(repo+"name", v.Name) vm.ExtVar(repo+"namespace", v.Namespace) vm.ExtVar(repo+"slug", v.Slug) vm.ExtVar(repo+"git_http_url", v.HTTPURL) vm.ExtVar(repo+"git_ssh_url", v.SSHURL) vm.ExtVar(repo+"link", v.Link) vm.ExtVar(repo+"branch", v.Branch) vm.ExtVar(repo+"config", v.Config) vm.ExtVar(repo+"private", strconv.FormatBool(v.Private)) vm.ExtVar(repo+"visibility", v.Visibility) vm.ExtVar(repo+"active", strconv.FormatBool(v.Active)) vm.ExtVar(repo+"trusted", strconv.FormatBool(v.Trusted)) vm.ExtVar(repo+"protected", strconv.FormatBool(v.Protected)) vm.ExtVar(repo+"ignore_forks", strconv.FormatBool(v.IgnoreForks)) vm.ExtVar(repo+"ignore_pull_requests", strconv.FormatBool(v.IgnorePulls)) } func fromMap(m map[string]string, vm *jsonnet.VM) { for k, v := range m { vm.ExtVar(build+param+k, v) } }
[]
[]
[]
[]
[]
go
null
null
null
dep/dep.go
// Package dep provides a Dependency struct, a DependencyMap from nicknames (strings) to Dependencies, // and functions to read and write a DependencyMap to a deps.json file package dep // Copyright 2013-2014 Vubeology, Inc. import ( "bytes" "encoding/json" "errors" "io/ioutil" "os" "path/filepath" "strings" "github.com/vube/depman/colors" "github.com/vube/depman/util" ) // Dependency Types const ( TypeGit = "git" TypeHg = "hg" TypeBzr = "bzr" TypeGitClone = "git-clone" ) var ( // ErrUnknownType indicates that an unknown dependency type was found ErrUnknownType = errors.New("unknown dependency type") // ErrMissingAlias indicates that a git-clone dependency requires an alias field ErrMissingAlias = errors.New("dependency type git-clone requires alias field") ) // DepsFile is the name of the dependency file const DepsFile string = "deps.json" // Dependency defines a single dependency type Dependency struct { Repo string `json:"repo"` Version string `json:"version"` Type string `json:"type"` Alias string `json:"alias,omitempty"` SkipCache bool `json:"skip-cache,omitempty"` VCS VersionControl `json:"-"` } // VersionControl is an interface that define a standard set of operations that can be completed by a version control system type VersionControl interface { Clone(d *Dependency) (err error) // Get changes from the server Fetch(d *Dependency) (err error) // Pull/Merge/Update this branch Update(d *Dependency) (err error) Checkout(d *Dependency) (err error) LastCommit(d *Dependency, branch string) (hash string, err error) GetHead(d *Dependency) (to_return string, err error) Clean(d *Dependency) } // DependencyMap defines a set of dependencies type DependencyMap struct { Map map[string]*Dependency Path string } // New returns a newly constructed DependencyMap func New() (d DependencyMap) { d.Map = make(map[string]*Dependency) return } // Read reads filename and parses the content into a DependencyMap func Read(filename string) (deps DependencyMap, err error) { deps.Map = make(map[string]*Dependency) data, err := ioutil.ReadFile(filename) if err != nil { return } err = json.Unmarshal(data, &deps.Map) if err != nil { return } // traverse map and look for empty version fields - provide a default if such found for key := range deps.Map { val := deps.Map[key] if val.Version == "" { switch val.Type { case TypeGit, TypeGitClone: val.Version = "master" case TypeHg: val.Version = "tip" case TypeBzr: val.Version = "trunk" default: val.Version = "" } deps.Map[key] = val } } for name, d := range deps.Map { err := d.SetupVCS(name) if err != nil { delete(deps.Map, name) } } deps.Path = filename return } // Write the dependencyMap back into to the file it was read from func (d *DependencyMap) Write() (err error) { var buf bytes.Buffer str, err := json.Marshal(d.Map) json.Indent(&buf, str, "", " ") if err == nil { data := []byte(buf.String() + "\n") ioutil.WriteFile(d.Path, data, 0644) } return } // SetupVCS configures the VCS depending on the type func (d *Dependency) SetupVCS(name string) (err error) { switch d.Type { case TypeGitClone: if d.Alias == "" { util.PrintIndent(colors.Red("Error: Dependency " + name + ": Repo '" + d.Repo + "' Type '" + d.Type + "' requires 'alias' field")) err = ErrMissingAlias return } d.VCS = new(Git) case TypeGit: d.VCS = new(Git) case TypeBzr: d.VCS = new(Bzr) case TypeHg: d.VCS = new(Hg) default: util.PrintIndent(colors.Red(d.Repo + ": Unknown repository type (" + d.Type + "), skipping...")) util.PrintIndent(colors.Red("Valid Repository types: " + TypeGit + ", " + TypeHg + ", " + TypeBzr + ", " + TypeGitClone)) err = ErrUnknownType } if d.Type != TypeGitClone && d.Alias != "" { util.Print(colors.Yellow("Warning: " + d.Repo + ": 'alias' field only allowed in dependencies with type 'git-clone', skipping...")) d.Alias = "" } return } // Path returns the path for this dependency // searches for the appropriate directory in each part of the GOPATH (delimited by ':') // if not found return the path using the first port of GOPATH func (d *Dependency) Path() (p string) { parts := strings.Split(os.Getenv("GOPATH"), ":") for _, path := range parts { p = filepath.Join(path, "src") if d.Alias == "" { p = filepath.Join(p, d.Repo) } else { p = filepath.Join(p, d.Alias) } if util.Exists(p) { return } } // didn't find a directory, use the first part of gopath p = filepath.Join(parts[0], "src") if d.Alias == "" { p = filepath.Join(p, d.Repo) } else { p = filepath.Join(p, d.Alias) } return } //GetPath processes p and returns a clean path ending in deps.json func GetPath(p string) (result string) { if !strings.HasSuffix(p, DepsFile) { result = p + "/" + DepsFile } result = filepath.Clean(result) return }
[ "\"GOPATH\"" ]
[]
[ "GOPATH" ]
[]
["GOPATH"]
go
1
0
winners/nontargeted-attack/teaflow/attack_iter.py
"""Implementation of sample attack.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from cleverhans.attacks import MultiModelIterativeMethod import numpy as np from PIL import Image import tensorflow as tf from tensorflow.contrib.slim.nets import inception import inception_resnet_v2 slim = tf.contrib.slim tf.flags.DEFINE_string( 'master', '', 'The address of the TensorFlow master to use.') tf.flags.DEFINE_string( 'checkpoint_path1', '', 'Path to checkpoint for inception network.') tf.flags.DEFINE_string( 'checkpoint_path2', '', 'Path to checkpoint for adversarial trained inception network.') tf.flags.DEFINE_string( 'checkpoint_path3', '', 'Path to checkpoint for adversarial trained inception-resnet network.') tf.flags.DEFINE_string( 'input_dir', '', 'Input directory with images.') tf.flags.DEFINE_string( 'output_dir', '', 'Output directory with images.') tf.flags.DEFINE_float( 'max_epsilon', 16.0, 'Maximum size of adversarial perturbation.') tf.flags.DEFINE_integer( 'image_width', 299, 'Width of each input images.') tf.flags.DEFINE_integer( 'image_height', 299, 'Height of each input images.') tf.flags.DEFINE_integer( 'batch_size', 10, 'How many images process at one time.') FLAGS = tf.flags.FLAGS def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be less than batch_size, in this case only first few images of the result are elements of the minibatch. images: array with all images from this batch """ images = np.zeros(batch_shape) filenames = [] idx = 0 batch_size = batch_shape[0] filepaths = tf.gfile.Glob(os.path.join(input_dir, '*.png')) for count, filepath in enumerate(filepaths): with tf.gfile.Open(filepath) as f: image = np.array(Image.open(f).convert('RGB')).astype(np.float) / 255.0 # Images for inception classifier are normalized to be in [-1, 1] interval. images[idx, :, :, :] = image * 2.0 - 1.0 filenames.append(os.path.basename(filepath)) idx += 1 if idx == batch_size: yield filenames, images filenames = [] images = np.zeros(batch_shape) idx = 0 if idx > 0: yield filenames, images def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images will be saved. output_dir: directory where to save images """ for i, filename in enumerate(filenames): # Images for inception classifier are normalized to be in [-1, 1] interval, # so rescale them back to [0, 1]. with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f: # img = (((images[i, :, :, :] + 1.0) * 0.5) * 255.0).astype(np.uint8) img = np.round(255.0 * (images[i, :, :, :] + 1.0) * 0.5).astype(np.uint8) Image.fromarray(img).save(f, format='PNG') class InceptionModel(object): """Model class for CleverHans library.""" def __init__(self, num_classes, scope=''): self.num_classes = num_classes self.built = False self.scope = scope def __call__(self, x_input): """Constructs model and return probabilities for given input.""" reuse = True if self.built else None with slim.arg_scope(inception.inception_v3_arg_scope()): _, end_points = inception.inception_v3( x_input, num_classes=self.num_classes, is_training=False, reuse=reuse, scope=self.scope) self.built = True output = end_points['Predictions'] # Strip off the extra reshape op at the output probs = output.op.inputs[0] return probs class IrNetModel(object): """Model class for CleverHans library.""" def __init__(self, num_classes, scope=''): self.num_classes = num_classes self.built = False self.scope = scope def __call__(self, x_input): """Constructs model and return probabilities for given input.""" reuse = True if self.built else None with slim.arg_scope(inception_resnet_v2.inception_resnet_v2_arg_scope()): _, end_points = inception_resnet_v2.inception_resnet_v2(x_input, num_classes=self.num_classes, reuse=reuse, is_training=False, scope=self.scope) self.built = True output = end_points['Predictions'] # Strip off the extra reshape op at the output probs = output.op.inputs[0] return probs def main(_): start_time = time.time() # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] num_classes = 1001 tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default(): # --------------------------------- # define graph x_input = tf.placeholder(tf.float32, shape=batch_shape) model1 = InceptionModel(num_classes, scope='sc1') model2 = InceptionModel(num_classes, scope='sc2') model3 = IrNetModel(num_classes, scope='sc3') method = MultiModelIterativeMethod([model1, model2, model3]) x_adv = method.generate(x_input, eps=eps, clip_min=-1., clip_max=1., nb_iter=17) # --------------------------------- # set input all_vars = tf.global_variables() # print(all_vars) unique_name_headers = set([k.name.split('/')[0] for k in all_vars]) model1_vars = [k for k in all_vars if k.name.startswith('sc1')] model2_vars = [k for k in all_vars if k.name.startswith('sc2')] model3_vars = [k for k in all_vars if k.name.startswith('sc3')] # name of variable `my_var:0` corresponds `my_var` for loader model1_keys = [s.name.replace('sc1', 'InceptionV3')[:-2] for s in model1_vars] model2_keys = [s.name.replace('sc2', 'InceptionV3')[:-2] for s in model2_vars] model3_keys = [s.name.replace('sc3', 'InceptionResnetV2')[:-2] for s in model3_vars] saver1 = tf.train.Saver(dict(zip(model1_keys, model1_vars))) saver2 = tf.train.Saver(dict(zip(model2_keys, model2_vars))) saver3 = tf.train.Saver(dict(zip(model3_keys, model3_vars))) session_creator = tf.train.ChiefSessionCreator(master=FLAGS.master) with tf.train.MonitoredSession(session_creator=session_creator) as sess: saver1.restore(sess, FLAGS.checkpoint_path1) saver2.restore(sess, FLAGS.checkpoint_path2) saver3.restore(sess, FLAGS.checkpoint_path3) for filenames, images in load_images(FLAGS.input_dir, batch_shape): adv_images = sess.run(x_adv, feed_dict={x_input: images}) save_images(adv_images, filenames, FLAGS.output_dir) elapsed_time = time.time() - start_time print('elapsed time: {0:.0f} [s]'.format(elapsed_time)) if __name__ == '__main__': tf.app.run()
[]
[]
[]
[]
[]
python
null
null
null
pkg/util/utils.go
package util import ( "encoding/json" "fmt" "os" "os/user" "path/filepath" "regexp" "strconv" "strings" "sync" "syscall" "time" "github.com/BurntSushi/toml" "github.com/containers/common/pkg/config" "github.com/containers/image/v5/types" "github.com/containers/podman/v3/pkg/errorhandling" "github.com/containers/podman/v3/pkg/namespaces" "github.com/containers/podman/v3/pkg/rootless" "github.com/containers/podman/v3/pkg/signal" "github.com/containers/storage/pkg/idtools" stypes "github.com/containers/storage/types" v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh/terminal" ) var containerConfig *config.Config func init() { var err error containerConfig, err = config.Default() if err != nil { logrus.Error(err) os.Exit(1) } } // Helper function to determine the username/password passed // in the creds string. It could be either or both. func parseCreds(creds string) (string, string) { if creds == "" { return "", "" } up := strings.SplitN(creds, ":", 2) if len(up) == 1 { return up[0], "" } return up[0], up[1] } // ParseRegistryCreds takes a credentials string in the form USERNAME:PASSWORD // and returns a DockerAuthConfig func ParseRegistryCreds(creds string) (*types.DockerAuthConfig, error) { username, password := parseCreds(creds) if username == "" { fmt.Print("Username: ") fmt.Scanln(&username) } if password == "" { fmt.Print("Password: ") termPassword, err := terminal.ReadPassword(0) if err != nil { return nil, errors.Wrapf(err, "could not read password from terminal") } password = string(termPassword) } return &types.DockerAuthConfig{ Username: username, Password: password, }, nil } // StringInSlice determines if a string is in a string slice, returns bool func StringInSlice(s string, sl []string) bool { for _, i := range sl { if i == s { return true } } return false } // StringMatchRegexSlice determines if a given string matches one of the given regexes, returns bool func StringMatchRegexSlice(s string, re []string) bool { for _, r := range re { m, err := regexp.MatchString(r, s) if err == nil && m { return true } } return false } // ImageConfig is a wrapper around the OCIv1 Image Configuration struct exported // by containers/image, but containing additional fields that are not supported // by OCIv1 (but are by Docker v2) - notably OnBuild. type ImageConfig struct { v1.ImageConfig OnBuild []string } // GetImageConfig produces a v1.ImageConfig from the --change flag that is // accepted by several Podman commands. It accepts a (limited subset) of // Dockerfile instructions. func GetImageConfig(changes []string) (ImageConfig, error) { // Valid changes: // USER // EXPOSE // ENV // ENTRYPOINT // CMD // VOLUME // WORKDIR // LABEL // STOPSIGNAL // ONBUILD config := ImageConfig{} for _, change := range changes { // First, let's assume proper Dockerfile format - space // separator between instruction and value split := strings.SplitN(change, " ", 2) if len(split) != 2 { split = strings.SplitN(change, "=", 2) if len(split) != 2 { return ImageConfig{}, errors.Errorf("invalid change %q - must be formatted as KEY VALUE", change) } } outerKey := strings.ToUpper(strings.TrimSpace(split[0])) value := strings.TrimSpace(split[1]) switch outerKey { case "USER": // Assume literal contents are the user. if value == "" { return ImageConfig{}, errors.Errorf("invalid change %q - must provide a value to USER", change) } config.User = value case "EXPOSE": // EXPOSE is either [portnum] or // [portnum]/[proto] // Protocol must be "tcp" or "udp" splitPort := strings.Split(value, "/") if len(splitPort) > 2 { return ImageConfig{}, errors.Errorf("invalid change %q - EXPOSE port must be formatted as PORT[/PROTO]", change) } portNum, err := strconv.Atoi(splitPort[0]) if err != nil { return ImageConfig{}, errors.Wrapf(err, "invalid change %q - EXPOSE port must be an integer", change) } if portNum > 65535 || portNum <= 0 { return ImageConfig{}, errors.Errorf("invalid change %q - EXPOSE port must be a valid port number", change) } proto := "tcp" if len(splitPort) > 1 { testProto := strings.ToLower(splitPort[1]) switch testProto { case "tcp", "udp": proto = testProto default: return ImageConfig{}, errors.Errorf("invalid change %q - EXPOSE protocol must be TCP or UDP", change) } } if config.ExposedPorts == nil { config.ExposedPorts = make(map[string]struct{}) } config.ExposedPorts[fmt.Sprintf("%d/%s", portNum, proto)] = struct{}{} case "ENV": // Format is either: // ENV key=value // ENV key=value key=value ... // ENV key value // Both keys and values can be surrounded by quotes to group them. // For now: we only support key=value // We will attempt to strip quotation marks if present. var ( key, val string ) splitEnv := strings.SplitN(value, "=", 2) key = splitEnv[0] // We do need a key if key == "" { return ImageConfig{}, errors.Errorf("invalid change %q - ENV must have at least one argument", change) } // Perfectly valid to not have a value if len(splitEnv) == 2 { val = splitEnv[1] } if strings.HasPrefix(key, `"`) && strings.HasSuffix(key, `"`) { key = strings.TrimPrefix(strings.TrimSuffix(key, `"`), `"`) } if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { val = strings.TrimPrefix(strings.TrimSuffix(val, `"`), `"`) } config.Env = append(config.Env, fmt.Sprintf("%s=%s", key, val)) case "ENTRYPOINT": // Two valid forms. // First, JSON array. // Second, not a JSON array - we interpret this as an // argument to `sh -c`, unless empty, in which case we // just use a blank entrypoint. testUnmarshal := []string{} if err := json.Unmarshal([]byte(value), &testUnmarshal); err != nil { // It ain't valid JSON, so assume it's an // argument to sh -c if not empty. if value != "" { config.Entrypoint = []string{"/bin/sh", "-c", value} } else { config.Entrypoint = []string{} } } else { // Valid JSON config.Entrypoint = testUnmarshal } case "CMD": // Same valid forms as entrypoint. // However, where ENTRYPOINT assumes that 'ENTRYPOINT ' // means no entrypoint, CMD assumes it is 'sh -c' with // no third argument. testUnmarshal := []string{} if err := json.Unmarshal([]byte(value), &testUnmarshal); err != nil { // It ain't valid JSON, so assume it's an // argument to sh -c. // Only include volume if it's not "" config.Cmd = []string{"/bin/sh", "-c"} if value != "" { config.Cmd = append(config.Cmd, value) } } else { // Valid JSON config.Cmd = testUnmarshal } case "VOLUME": // Either a JSON array or a set of space-separated // paths. // Acts rather similar to ENTRYPOINT and CMD, but always // appends rather than replacing, and no sh -c prepend. testUnmarshal := []string{} if err := json.Unmarshal([]byte(value), &testUnmarshal); err != nil { // Not valid JSON, so split on spaces testUnmarshal = strings.Split(value, " ") } if len(testUnmarshal) == 0 { return ImageConfig{}, errors.Errorf("invalid change %q - must provide at least one argument to VOLUME", change) } for _, vol := range testUnmarshal { if vol == "" { return ImageConfig{}, errors.Errorf("invalid change %q - VOLUME paths must not be empty", change) } if config.Volumes == nil { config.Volumes = make(map[string]struct{}) } config.Volumes[vol] = struct{}{} } case "WORKDIR": // This can be passed multiple times. // Each successive invocation is treated as relative to // the previous one - so WORKDIR /A, WORKDIR b, // WORKDIR c results in /A/b/c // Just need to check it's not empty... if value == "" { return ImageConfig{}, errors.Errorf("invalid change %q - must provide a non-empty WORKDIR", change) } config.WorkingDir = filepath.Join(config.WorkingDir, value) case "LABEL": // Same general idea as ENV, but we no longer allow " " // as a separator. // We didn't do that for ENV either, so nice and easy. // Potentially problematic: LABEL might theoretically // allow an = in the key? If people really do this, we // may need to investigate more advanced parsing. var ( key, val string ) splitLabel := strings.SplitN(value, "=", 2) // Unlike ENV, LABEL must have a value if len(splitLabel) != 2 { return ImageConfig{}, errors.Errorf("invalid change %q - LABEL must be formatted key=value", change) } key = splitLabel[0] val = splitLabel[1] if strings.HasPrefix(key, `"`) && strings.HasSuffix(key, `"`) { key = strings.TrimPrefix(strings.TrimSuffix(key, `"`), `"`) } if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { val = strings.TrimPrefix(strings.TrimSuffix(val, `"`), `"`) } // Check key after we strip quotations if key == "" { return ImageConfig{}, errors.Errorf("invalid change %q - LABEL must have a non-empty key", change) } if config.Labels == nil { config.Labels = make(map[string]string) } config.Labels[key] = val case "STOPSIGNAL": // Check the provided signal for validity. killSignal, err := ParseSignal(value) if err != nil { return ImageConfig{}, errors.Wrapf(err, "invalid change %q - KILLSIGNAL must be given a valid signal", change) } config.StopSignal = fmt.Sprintf("%d", killSignal) case "ONBUILD": // Onbuild always appends. if value == "" { return ImageConfig{}, errors.Errorf("invalid change %q - ONBUILD must be given an argument", change) } config.OnBuild = append(config.OnBuild, value) default: return ImageConfig{}, errors.Errorf("invalid change %q - invalid instruction %s", change, outerKey) } } return config, nil } // ParseSignal parses and validates a signal name or number. func ParseSignal(rawSignal string) (syscall.Signal, error) { // Strip off leading dash, to allow -1 or -HUP basename := strings.TrimPrefix(rawSignal, "-") sig, err := signal.ParseSignal(basename) if err != nil { return -1, err } // 64 is SIGRTMAX; wish we could get this from a standard Go library if sig < 1 || sig > 64 { return -1, errors.Errorf("valid signals are 1 through 64") } return sig, nil } // GetKeepIDMapping returns the mappings and the user to use when keep-id is used func GetKeepIDMapping() (*stypes.IDMappingOptions, int, int, error) { options := stypes.IDMappingOptions{ HostUIDMapping: true, HostGIDMapping: true, } uid, gid := 0, 0 if rootless.IsRootless() { min := func(a, b int) int { if a < b { return a } return b } uid = rootless.GetRootlessUID() gid = rootless.GetRootlessGID() uids, gids, err := rootless.GetConfiguredMappings() if err != nil { return nil, -1, -1, errors.Wrapf(err, "cannot read mappings") } maxUID, maxGID := 0, 0 for _, u := range uids { maxUID += u.Size } for _, g := range gids { maxGID += g.Size } options.UIDMap, options.GIDMap = nil, nil options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: 0, HostID: 1, Size: min(uid, maxUID)}) options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: uid, HostID: 0, Size: 1}) if maxUID > uid { options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: uid + 1, HostID: uid + 1, Size: maxUID - uid}) } options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: 0, HostID: 1, Size: min(gid, maxGID)}) options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: gid, HostID: 0, Size: 1}) if maxGID > gid { options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: gid + 1, HostID: gid + 1, Size: maxGID - gid}) } options.HostUIDMapping = false options.HostGIDMapping = false } // Simply ignore the setting and do not setup an inner namespace for root as it is a no-op return &options, uid, gid, nil } // ParseIDMapping takes idmappings and subuid and subgid maps and returns a storage mapping func ParseIDMapping(mode namespaces.UsernsMode, uidMapSlice, gidMapSlice []string, subUIDMap, subGIDMap string) (*stypes.IDMappingOptions, error) { options := stypes.IDMappingOptions{ HostUIDMapping: true, HostGIDMapping: true, } if mode.IsAuto() { var err error options.HostUIDMapping = false options.HostGIDMapping = false options.AutoUserNs = true opts, err := mode.GetAutoOptions() if err != nil { return nil, err } options.AutoUserNsOpts = *opts return &options, nil } if mode.IsKeepID() { options.HostUIDMapping = false options.HostGIDMapping = false return &options, nil } if subGIDMap == "" && subUIDMap != "" { subGIDMap = subUIDMap } if subUIDMap == "" && subGIDMap != "" { subUIDMap = subGIDMap } if len(gidMapSlice) == 0 && len(uidMapSlice) != 0 { gidMapSlice = uidMapSlice } if len(uidMapSlice) == 0 && len(gidMapSlice) != 0 { uidMapSlice = gidMapSlice } if subUIDMap != "" && subGIDMap != "" { mappings, err := idtools.NewIDMappings(subUIDMap, subGIDMap) if err != nil { return nil, err } options.UIDMap = mappings.UIDs() options.GIDMap = mappings.GIDs() } parsedUIDMap, err := idtools.ParseIDMap(uidMapSlice, "UID") if err != nil { return nil, err } parsedGIDMap, err := idtools.ParseIDMap(gidMapSlice, "GID") if err != nil { return nil, err } options.UIDMap = append(options.UIDMap, parsedUIDMap...) options.GIDMap = append(options.GIDMap, parsedGIDMap...) if len(options.UIDMap) > 0 { options.HostUIDMapping = false } if len(options.GIDMap) > 0 { options.HostGIDMapping = false } return &options, nil } var ( rootlessConfigHomeDirOnce sync.Once rootlessConfigHomeDir string rootlessRuntimeDirOnce sync.Once rootlessRuntimeDir string ) type tomlOptionsConfig struct { MountProgram string `toml:"mount_program"` } type tomlConfig struct { Storage struct { Driver string `toml:"driver"` RunRoot string `toml:"runroot"` GraphRoot string `toml:"graphroot"` Options struct{ tomlOptionsConfig } `toml:"options"` } `toml:"storage"` } func getTomlStorage(storeOptions *stypes.StoreOptions) *tomlConfig { config := new(tomlConfig) config.Storage.Driver = storeOptions.GraphDriverName config.Storage.RunRoot = storeOptions.RunRoot config.Storage.GraphRoot = storeOptions.GraphRoot for _, i := range storeOptions.GraphDriverOptions { s := strings.SplitN(i, "=", 2) if s[0] == "overlay.mount_program" && len(s) == 2 { config.Storage.Options.MountProgram = s[1] } } return config } // WriteStorageConfigFile writes the configuration to a file func WriteStorageConfigFile(storageOpts *stypes.StoreOptions, storageConf string) error { if err := os.MkdirAll(filepath.Dir(storageConf), 0755); err != nil { return err } storageFile, err := os.OpenFile(storageConf, os.O_RDWR|os.O_TRUNC, 0600) if err != nil { return err } tomlConfiguration := getTomlStorage(storageOpts) defer errorhandling.CloseQuiet(storageFile) enc := toml.NewEncoder(storageFile) if err := enc.Encode(tomlConfiguration); err != nil { if err := os.Remove(storageConf); err != nil { logrus.Error(err) } return err } return nil } // ParseInputTime takes the users input and to determine if it is valid and // returns a time format and error. The input is compared to known time formats // or a duration which implies no-duration func ParseInputTime(inputTime string) (time.Time, error) { timeFormats := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05", "2006-01-02T15:04:05.999999999", "2006-01-02Z07:00", "2006-01-02"} // iterate the supported time formats for _, tf := range timeFormats { t, err := time.Parse(tf, inputTime) if err == nil { return t, nil } } unixTimestamp, err := strconv.ParseInt(inputTime, 10, 64) if err == nil { return time.Unix(unixTimestamp, 0), nil } // input might be a duration duration, err := time.ParseDuration(inputTime) if err != nil { return time.Time{}, errors.Errorf("unable to interpret time value") } return time.Now().Add(-duration), nil } // OpenExclusiveFile opens a file for writing and ensure it doesn't already exist func OpenExclusiveFile(path string) (*os.File, error) { baseDir := filepath.Dir(path) if baseDir != "" { if _, err := os.Stat(baseDir); err != nil { return nil, err } } return os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) } type PullType = config.PullPolicy var ( // PullImageAlways always try to pull new image when create or run PullImageAlways = config.PullImageAlways // PullImageMissing pulls image if it is not locally PullImageMissing = config.PullImageMissing // PullImageNever will never pull new image PullImageNever = config.PullImageNever ) // ValidatePullType check if the pullType from CLI is valid and returns the valid enum type // if the value from CLI is invalid returns the error func ValidatePullType(pullType string) (PullType, error) { return config.ValidatePullPolicy(pullType) } // ExitCode reads the error message when failing to executing container process // and then returns 0 if no error, 126 if command does not exist, or 127 for // all other errors func ExitCode(err error) int { if err == nil { return 0 } e := strings.ToLower(err.Error()) if strings.Contains(e, "file not found") || strings.Contains(e, "no such file or directory") { return 127 } return 126 } // HomeDir returns the home directory for the current user. func HomeDir() (string, error) { home := os.Getenv("HOME") if home == "" { usr, err := user.LookupId(fmt.Sprintf("%d", rootless.GetRootlessUID())) if err != nil { return "", errors.Wrapf(err, "unable to resolve HOME directory") } home = usr.HomeDir } return home, nil } func Tmpdir() string { tmpdir := os.Getenv("TMPDIR") if tmpdir == "" { tmpdir = "/var/tmp" } return tmpdir } // ValidateSysctls validates a list of sysctl and returns it. func ValidateSysctls(strSlice []string) (map[string]string, error) { sysctl := make(map[string]string) validSysctlMap := map[string]bool{ "kernel.msgmax": true, "kernel.msgmnb": true, "kernel.msgmni": true, "kernel.sem": true, "kernel.shmall": true, "kernel.shmmax": true, "kernel.shmmni": true, "kernel.shm_rmid_forced": true, } validSysctlPrefixes := []string{ "net.", "fs.mqueue.", } for _, val := range strSlice { foundMatch := false arr := strings.Split(val, "=") if len(arr) < 2 { return nil, errors.Errorf("%s is invalid, sysctl values must be in the form of KEY=VALUE", val) } if validSysctlMap[arr[0]] { sysctl[arr[0]] = arr[1] continue } for _, prefix := range validSysctlPrefixes { if strings.HasPrefix(arr[0], prefix) { sysctl[arr[0]] = arr[1] foundMatch = true break } } if !foundMatch { return nil, errors.Errorf("sysctl '%s' is not allowed", arr[0]) } } return sysctl, nil } func DefaultContainerConfig() *config.Config { return containerConfig } func CreateCidFile(cidfile string, id string) error { cidFile, err := OpenExclusiveFile(cidfile) if err != nil { if os.IsExist(err) { return errors.Errorf("container id file exists. Ensure another container is not using it or delete %s", cidfile) } return errors.Errorf("error opening cidfile %s", cidfile) } if _, err = cidFile.WriteString(id); err != nil { logrus.Error(err) } cidFile.Close() return nil } // DefaultCPUPeriod is the default CPU period is 100us, which is the same default // as Kubernetes. const DefaultCPUPeriod uint64 = 100000 // CoresToPeriodAndQuota converts a fraction of cores to the equivalent // Completely Fair Scheduler (CFS) parameters period and quota. // // Cores is a fraction of the CFS period that a container may use. Period and // Quota are in microseconds. func CoresToPeriodAndQuota(cores float64) (uint64, int64) { return DefaultCPUPeriod, int64(cores * float64(DefaultCPUPeriod)) } // PeriodAndQuotaToCores takes the CFS parameters period and quota and returns // a fraction that represents the limit to the number of cores that can be // utilized over the scheduling period. // // Cores is a fraction of the CFS period that a container may use. Period and // Quota are in microseconds. func PeriodAndQuotaToCores(period uint64, quota int64) float64 { return float64(quota) / float64(period) } // IDtoolsToRuntimeSpec converts idtools ID mapping to the one of the runtime spec. func IDtoolsToRuntimeSpec(idMaps []idtools.IDMap) (convertedIDMap []specs.LinuxIDMapping) { for _, idmap := range idMaps { tempIDMap := specs.LinuxIDMapping{ ContainerID: uint32(idmap.ContainerID), HostID: uint32(idmap.HostID), Size: uint32(idmap.Size), } convertedIDMap = append(convertedIDMap, tempIDMap) } return convertedIDMap } var socketPath string func SetSocketPath(path string) { socketPath = path } func SocketPath() (string, error) { if socketPath != "" { return socketPath, nil } xdg, err := GetRuntimeDir() if err != nil { return "", err } if len(xdg) == 0 { // If no xdg is returned, assume root socket xdg = "/run" } // Glue the socket path together return filepath.Join(xdg, "podman", "podman.sock"), nil }
[ "\"HOME\"", "\"TMPDIR\"" ]
[]
[ "HOME", "TMPDIR" ]
[]
["HOME", "TMPDIR"]
go
2
0
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "palautebot.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
[]
[]
[]
[]
[]
python
0
0
pkg/controller/operands/vmImport.go
package operands import ( "errors" "os" "reflect" vmimportv1beta1 "github.com/kubevirt/vm-import-operator/pkg/apis/v2v/v1beta1" conditionsv1 "github.com/openshift/custom-resource-status/conditions/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client" hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/pkg/apis/hco/v1beta1" "github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/common" "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util" hcoutil "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util" ) // *********** VM Import Handler *********** type vmImportHandler genericOperand func newVmImportHandler(Client client.Client, Scheme *runtime.Scheme) *vmImportHandler { return &vmImportHandler{ Client: Client, Scheme: Scheme, crType: "vmImport", // Previous versions used to have HCO-operator (scope namespace) // as the owner of VMImportConfig (scope cluster). // It's not legal, so remove that. removeExistingOwner: true, hooks: &vmImportHooks{}, } } type vmImportHooks struct { cache *vmimportv1beta1.VMImportConfig } func (h *vmImportHooks) getFullCr(hc *hcov1beta1.HyperConverged) (client.Object, error) { if h.cache == nil { h.cache = NewVMImportForCR(hc) } return h.cache, nil } func (h vmImportHooks) getEmptyCr() client.Object { return &vmimportv1beta1.VMImportConfig{} } func (h vmImportHooks) postFound(_ *common.HcoRequest, _ runtime.Object) error { return nil } func (h vmImportHooks) getConditions(cr runtime.Object) []conditionsv1.Condition { return cr.(*vmimportv1beta1.VMImportConfig).Status.Conditions } func (h vmImportHooks) checkComponentVersion(cr runtime.Object) bool { found := cr.(*vmimportv1beta1.VMImportConfig) return checkComponentVersion(hcoutil.VMImportEnvV, found.Status.ObservedVersion) } func (h vmImportHooks) getObjectMeta(cr runtime.Object) *metav1.ObjectMeta { return &cr.(*vmimportv1beta1.VMImportConfig).ObjectMeta } func (h *vmImportHooks) reset() { h.cache = nil } func (h *vmImportHooks) updateCr(req *common.HcoRequest, Client client.Client, exists runtime.Object, required runtime.Object) (bool, bool, error) { vmImport, ok1 := required.(*vmimportv1beta1.VMImportConfig) found, ok2 := exists.(*vmimportv1beta1.VMImportConfig) if !ok1 || !ok2 { return false, false, errors.New("can't convert to vmImport") } if !reflect.DeepEqual(found.Spec, vmImport.Spec) || !reflect.DeepEqual(found.Labels, vmImport.Labels) { if req.HCOTriggered { req.Logger.Info("Updating existing vmImport's Spec to new opinionated values") } else { req.Logger.Info("Reconciling an externally updated vmImport's Spec to its opinionated values") } util.DeepCopyLabels(&vmImport.ObjectMeta, &found.ObjectMeta) vmImport.Spec.DeepCopyInto(&found.Spec) err := Client.Update(req.Ctx, found) if err != nil { return false, false, err } return true, !req.HCOTriggered, nil } return false, false, nil } // NewVMImportForCR returns a VM import CR func NewVMImportForCR(cr *hcov1beta1.HyperConverged) *vmimportv1beta1.VMImportConfig { spec := vmimportv1beta1.VMImportConfigSpec{} if cr.Spec.Infra.NodePlacement != nil { cr.Spec.Infra.NodePlacement.DeepCopyInto(&spec.Infra) } return &vmimportv1beta1.VMImportConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "vmimport-" + cr.Name, Labels: getLabels(cr, hcoutil.AppComponentImport), }, Spec: spec, } } // ************** IMS Config Handler ************** type imsConfigHandler genericOperand func newImsConfigHandler(Client client.Client, Scheme *runtime.Scheme) *imsConfigHandler { return &imsConfigHandler{ Client: Client, Scheme: Scheme, crType: "IMSConfigmap", removeExistingOwner: false, setControllerReference: true, hooks: &imsConfigHooks{}, } } type imsConfigHooks struct{} func (h imsConfigHooks) getFullCr(hc *hcov1beta1.HyperConverged) (client.Object, error) { return NewIMSConfigForCR(hc, hc.Namespace) } func (h imsConfigHooks) getEmptyCr() client.Object { return &corev1.ConfigMap{} } func (h imsConfigHooks) postFound(_ *common.HcoRequest, _ runtime.Object) error { return nil } func (h imsConfigHooks) getObjectMeta(cr runtime.Object) *metav1.ObjectMeta { return &cr.(*corev1.ConfigMap).ObjectMeta } func (h *imsConfigHooks) updateCr(req *common.HcoRequest, Client client.Client, exists runtime.Object, required runtime.Object) (bool, bool, error) { imsConfig, ok1 := required.(*corev1.ConfigMap) found, ok2 := exists.(*corev1.ConfigMap) if !ok1 || !ok2 { return false, false, errors.New("can't convert to a ConfigMap") } needsUpdate := false if !reflect.DeepEqual(found.Data, imsConfig.Data) { imsConfig.DeepCopyInto(found) needsUpdate = true } if !reflect.DeepEqual(found.Labels, imsConfig.Labels) { util.DeepCopyLabels(&imsConfig.ObjectMeta, &found.ObjectMeta) needsUpdate = true } if needsUpdate { req.Logger.Info("Updating existing IMS Configmap to its default values") if req.HCOTriggered { req.Logger.Info("Updating existing IMS Configmap to new opinionated values") } else { req.Logger.Info("Reconciling an externally updated IMS Configmap to its opinionated values") } err := Client.Update(req.Ctx, found) if err != nil { return false, false, err } return true, !req.HCOTriggered, nil } return false, false, nil } func NewIMSConfigForCR(cr *hcov1beta1.HyperConverged, namespace string) (*corev1.ConfigMap, error) { conversionContainer := os.Getenv("CONVERSION_CONTAINER") if conversionContainer == "" { return nil, errors.New("ims-conversion-container not specified") } vmwareContainer := os.Getenv("VMWARE_CONTAINER") if vmwareContainer == "" { return nil, errors.New("ims-vmware-container not specified") } virtiowinContainer := os.Getenv("VIRTIOWIN_CONTAINER") if virtiowinContainer == "" { return nil, errors.New("kv-virtiowin-image-name not specified") } imscm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "v2v-vmware", Labels: getLabels(cr, hcoutil.AppComponentImport), Namespace: namespace, }, Data: map[string]string{ "v2v-conversion-image": conversionContainer, "kubevirt-vmware-image": vmwareContainer, "virtio-win-image": virtiowinContainer, "kubevirt-vmware-image-pull-policy": "IfNotPresent", }, } if cr.Spec.VddkInitImage != nil { imscm.Data["vddk-init-image"] = *cr.Spec.VddkInitImage } return imscm, nil }
[ "\"CONVERSION_CONTAINER\"", "\"VMWARE_CONTAINER\"", "\"VIRTIOWIN_CONTAINER\"" ]
[]
[ "CONVERSION_CONTAINER", "VMWARE_CONTAINER", "VIRTIOWIN_CONTAINER" ]
[]
["CONVERSION_CONTAINER", "VMWARE_CONTAINER", "VIRTIOWIN_CONTAINER"]
go
3
0
examples/ilr/toy/evaluate_ard.py
import os import argparse os.environ["OMP_NUM_THREADS"] = "1" import numpy as np import numpy.random as npr import mimo from mimo.distributions import NormalGamma from mimo.distributions import MatrixNormalWishart from mimo.distributions import GaussianWithNormalGamma from mimo.distributions import LinearGaussianWithMatrixNormalWishartAndAutomaticRelevance from mimo.distributions import Gamma from mimo.distributions import TruncatedStickBreaking from mimo.distributions import Dirichlet from mimo.distributions import CategoricalWithDirichlet from mimo.distributions import CategoricalWithStickBreaking from mimo.mixtures import BayesianMixtureOfLinearGaussians import matplotlib.pyplot as plt from tqdm import tqdm import pathos from pathos.pools import _ProcessPool as Pool nb_cores = pathos.multiprocessing.cpu_count() def _job(kwargs): args = kwargs.pop('arguments') seed = kwargs.pop('seed') input = kwargs.pop('train_input') target = kwargs.pop('train_target') input_dim = input.shape[-1] target_dim = target.shape[-1] # set random seed np.random.seed(seed) nb_params = input_dim if args.affine: nb_params += 1 basis_prior = [] models_prior = [] models_hypprior = [] # initialize Normal alpha_ng = 1. beta_ng = 1. / (2. * 1e2) kappas = 1e-2 # initialize Matrix-Normal psi_mnw = 1e0 K = 1e0 # initialize ard-Gamma alphas_ard = 1. betas_ard = 1. / (2. * 1e2) for n in range(args.nb_models): basis_hypparams = dict(mu=np.zeros((input_dim,)), alphas=np.ones(input_dim) * alpha_ng, betas=np.ones(input_dim) * beta_ng, kappas=np.ones(input_dim) * kappas) aux = NormalGamma(**basis_hypparams) basis_prior.append(aux) models_hypparams = dict(M=np.zeros((target_dim, nb_params)), K=np.eye(nb_params) * K, nu=target_dim + 1, psi=np.eye(target_dim) * psi_mnw) aux = MatrixNormalWishart(**models_hypparams) models_prior.append(aux) models_hyphypparams = dict(alphas=alphas_ard * np.ones(nb_params), betas=betas_ard * np.ones(nb_params)) aux = Gamma(**models_hyphypparams) models_hypprior.append(aux) # define gating if args.prior == 'stick-breaking': gating_hypparams = dict(K=args.nb_models, gammas=np.ones((args.nb_models,)), deltas=np.ones((args.nb_models,)) * args.alpha) gating_prior = TruncatedStickBreaking(**gating_hypparams) ilr = BayesianMixtureOfLinearGaussians(gating=CategoricalWithStickBreaking(gating_prior), basis=[GaussianWithNormalGamma(basis_prior[i]) for i in range(args.nb_models)], models=[LinearGaussianWithMatrixNormalWishartAndAutomaticRelevance(models_prior[i], models_hypprior[i], affine=args.affine) for i in range(args.nb_models)]) else: gating_hypparams = dict(K=args.nb_models, alphas=np.ones((args.nb_models,)) * args.alpha) gating_prior = Dirichlet(**gating_hypparams) ilr = BayesianMixtureOfLinearGaussians(gating=CategoricalWithDirichlet(gating_prior), basis=[GaussianWithNormalGamma(basis_prior[i]) for i in range(args.nb_models)], models=[LinearGaussianWithMatrixNormalWishartAndAutomaticRelevance(models_prior[i], models_hypprior[i], affine=args.affine) for i in range(args.nb_models)]) ilr.add_data(target, input, whiten=False, labels_from_prior=True) # Gibbs sampling ilr.resample(maxiter=args.gibbs_iters, progprint=args.verbose) for _ in range(args.super_iters): if args.stochastic: # Stochastic meanfield VI ilr.meanfield_stochastic_descent(maxiter=args.svi_iters, stepsize=args.svi_stepsize, batchsize=args.svi_batchsize) if args.deterministic: # Meanfield VI ilr.meanfield_coordinate_descent(tol=args.earlystop, maxiter=args.meanfield_iters, progprint=args.verbose) ilr.gating.prior = ilr.gating.posterior for i in range(ilr.likelihood.size): ilr.basis[i].prior = ilr.basis[i].posterior ilr.models[i].prior = ilr.models[i].posterior return ilr def parallel_ilr_inference(nb_jobs=50, **kwargs): kwargs_list = [] for n in range(nb_jobs): kwargs['seed'] = n kwargs_list.append(kwargs.copy()) with Pool(processes=min(nb_jobs, nb_cores), initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),)) as p: res = p.map(_job, kwargs_list) return res if __name__ == "__main__": parser = argparse.ArgumentParser(description='Evaluate ilr with a Stick-breaking prior') parser.add_argument('--datapath', help='path to dataset', default=os.path.abspath(mimo.__file__ + '/../../datasets')) parser.add_argument('--evalpath', help='path to evaluation', default=os.path.abspath(mimo.__file__ + '/../../evaluation/toy')) parser.add_argument('--nb_seeds', help='number of seeds', default=1, type=int) parser.add_argument('--prior', help='prior type', default='stick-breaking') parser.add_argument('--alpha', help='concentration parameter', default=25, type=float) parser.add_argument('--nb_models', help='max number of models', default=50, type=int) parser.add_argument('--affine', help='affine functions', action='store_true', default=True) parser.add_argument('--no_affine', help='non-affine functions', dest='affine', action='store_false') parser.add_argument('--super_iters', help='interleaving Gibbs/VI iterations', default=1, type=int) parser.add_argument('--gibbs_iters', help='Gibbs iterations', default=1, type=int) parser.add_argument('--stochastic', help='use stochastic VI', action='store_true', default=False) parser.add_argument('--no_stochastic', help='do not use stochastic VI', dest='stochastic', action='store_false') parser.add_argument('--deterministic', help='use deterministic VI', action='store_true', default=True) parser.add_argument('--no_deterministic', help='do not use deterministic VI', dest='deterministic', action='store_false') parser.add_argument('--meanfield_iters', help='max VI iterations', default=100, type=int) parser.add_argument('--svi_iters', help='SVI iterations', default=500, type=int) parser.add_argument('--svi_stepsize', help='SVI step size', default=5e-4, type=float) parser.add_argument('--svi_batchsize', help='SVI batch size', default=256, type=int) parser.add_argument('--prediction', help='prediction w/ mode or average', default='average') parser.add_argument('--earlystop', help='stopping criterion for VI', default=1e-2, type=float) parser.add_argument('--verbose', help='show learning progress', action='store_true', default=True) parser.add_argument('--mute', help='show no output', dest='verbose', action='store_false') parser.add_argument('--nb_train', help='size of train dataset', default=2000, type=int) parser.add_argument('--seed', help='choose seed', default=1337, type=int) args = parser.parse_args() # np.random.seed(args.seed) # load Cosmic Microwave Background (CMB) training_data from Hannah (2011) data = np.loadtxt(args.datapath + '/cmb.csv', delimiter=",", skiprows=1) # shuffle data from sklearn.utils import shuffle data = shuffle(data) # training data nb_train = args.nb_train input, target = data[:nb_train, :1], data[:nb_train, 1:] noise = npr.randn(len(input), 2) * 1e3 input = np.hstack((input, noise)) ilr = parallel_ilr_inference(nb_jobs=args.nb_seeds, train_input=input, train_target=target, arguments=args)[0] # predict on training mu, var, std, nlpd = \ ilr.meanfield_prediction(input, target, prediction=args.prediction) # metrics from sklearn.metrics import explained_variance_score, mean_squared_error, r2_score mse = mean_squared_error(target, mu) evar = explained_variance_score(target, mu, multioutput='variance_weighted') smse = 1. - r2_score(target, mu, multioutput='variance_weighted') print('TRAIN - EVAR:', evar, 'MSE:', mse, 'SMSE:', smse, 'NLPD:', nlpd.mean(), 'Compnents:', len(ilr.used_labels)) fig, axes = plt.subplots(1, 1) # # plot prediction sorter = np.argsort(input[:, 0], axis=0).flatten() sorted_input, sorted_target = input[sorter, 0], target[sorter, 0] sorted_mu, sorted_std = mu[sorter, 0], std[sorter, 0] axes.scatter(sorted_input, sorted_target, s=0.75, color='k') axes.plot(sorted_input, sorted_mu, color='crimson') for c in [1., 2., 3.]: axes.fill_between(sorted_input, sorted_mu - c * sorted_std, sorted_mu + c * sorted_std, edgecolor=(0, 0, 1, 0.1), facecolor=(0, 0, 1, 0.1)) axes.set_ylabel('y') plt.show()
[]
[]
[ "OMP_NUM_THREADS" ]
[]
["OMP_NUM_THREADS"]
python
1
0
mne/viz/backends/_pyvista.py
""" Core visualization operations based on PyVista. Actual implementation of _Renderer and _Projection classes. """ # Authors: Alexandre Gramfort <[email protected]> # Eric Larson <[email protected]> # Guillaume Favelier <[email protected]> # Joan Massich <[email protected]> # # License: Simplified BSD from contextlib import contextmanager import os import re import sys import warnings import numpy as np import vtk from ._abstract import _AbstractRenderer, Figure3D from ._utils import (_get_colormap_from_array, _alpha_blend_background, ALLOWED_QUIVER_MODES, _init_mne_qtapp) from ...fixes import _get_args, _point_data, _cell_data, _compare_version from ...transforms import apply_trans from ...utils import (copy_base_doc_to_subclass_doc, _check_option, _require_version) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) import pyvista from pyvista import Plotter, PolyData, Line, close_all, UnstructuredGrid try: from pyvistaqt import BackgroundPlotter # noqa except ImportError: from pyvista import BackgroundPlotter from pyvista.plotting.plotting import _ALL_PLOTTERS VTK9 = _compare_version(getattr(vtk, 'VTK_VERSION', '9.0'), '>=', '9.0') _FIGURES = dict() class PyVistaFigure(Figure3D): """PyVista-based 3D Figure. This class is not meant to be instantiated directly, use :func:`mne.viz.create_3d_figure` instead. """ def __init__(self): pass def _init(self, plotter=None, show=False, title='PyVista Scene', size=(600, 600), shape=(1, 1), background_color='black', smooth_shading=True, off_screen=False, notebook=False, splash=False): self._plotter = plotter self.display = None self.background_color = background_color self.smooth_shading = smooth_shading self.notebook = notebook self.title = title self.splash = splash self.store = dict() self.store['window_size'] = size self.store['shape'] = shape self.store['off_screen'] = off_screen self.store['border'] = False # multi_samples > 1 is broken on macOS + Intel Iris + volume rendering self.store['multi_samples'] = 1 if sys.platform == 'darwin' else 4 if not self.notebook: self.store['show'] = show self.store['title'] = title self.store['auto_update'] = False self.store['menu_bar'] = False self.store['toolbar'] = False self.store['update_app_icon'] = False self._nrows, self._ncols = self.store['shape'] self._azimuth = self._elevation = None def _build(self): if self.notebook: plotter_class = Plotter else: plotter_class = BackgroundPlotter if self.plotter is None: if not self.notebook: out = _init_mne_qtapp( enable_icon=hasattr(plotter_class, 'set_icon'), splash=self.splash) # replace it with the Qt object if self.splash: self.splash = out[1] app = out[0] else: app = out self.store['app'] = app plotter = plotter_class(**self.store) plotter.background_color = self.background_color self._plotter = plotter if self.plotter.iren is not None: self.plotter.iren.initialize() _process_events(self.plotter) _process_events(self.plotter) return self.plotter def _is_active(self): if self.plotter is None: return False return hasattr(self.plotter, 'ren_win') class _Projection(object): """Class storing projection information. Attributes ---------- xy : array Result of 2d projection of 3d data. pts : None Scene sensors handle. """ def __init__(self, *, xy, pts, plotter): """Store input projection information into attributes.""" self.xy = xy self.pts = pts self.plotter = plotter def visible(self, state): """Modify visibility attribute of the sensors.""" self.pts.SetVisibility(state) self.plotter.render() @copy_base_doc_to_subclass_doc class _PyVistaRenderer(_AbstractRenderer): """Class managing rendering scene. Attributes ---------- plotter: Plotter Main PyVista access point. name: str Name of the window. """ def __init__(self, fig=None, size=(600, 600), bgcolor='black', name="PyVista Scene", show=False, shape=(1, 1), notebook=None, smooth_shading=True, splash=False): from .._3d import _get_3d_option _require_version('pyvista', 'use 3D rendering', '0.32') figure = PyVistaFigure() figure._init( show=show, title=name, size=size, shape=shape, background_color=bgcolor, notebook=notebook, smooth_shading=smooth_shading, splash=splash) self.font_family = "arial" self.tube_n_sides = 20 self.antialias = _get_3d_option('antialias') self.depth_peeling = _get_3d_option('depth_peeling') # smooth_shading=True fails on MacOS CIs self.smooth_shading = _get_3d_option('smooth_shading') if isinstance(fig, int): saved_fig = _FIGURES.get(fig) # Restore only active plotter if saved_fig is not None and saved_fig._is_active(): self.figure = saved_fig else: self.figure = figure _FIGURES[fig] = self.figure elif fig is None: self.figure = figure else: self.figure = fig # Enable off_screen if sphinx-gallery or testing if pyvista.OFF_SCREEN: self.figure.store['off_screen'] = True with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) # pyvista theme may enable depth peeling by default so # we disable it initially to better control the value afterwards with _disabled_depth_peeling(): self.plotter = self.figure._build() self._hide_axes() self._enable_antialias() self._enable_depth_peeling() # FIX: https://github.com/pyvista/pyvistaqt/pull/68 if not hasattr(self.plotter, "iren"): self.plotter.iren = None self.update_lighting() @property def _all_plotters(self): if self.figure.plotter is not None: return [self.figure.plotter] else: return list() @property def _all_renderers(self): if self.figure.plotter is not None: return self.figure.plotter.renderers else: return list() def _hide_axes(self): for renderer in self._all_renderers: renderer.hide_axes() def _update(self): for plotter in self._all_plotters: plotter.update() def _index_to_loc(self, idx): _ncols = self.figure._ncols row = idx // _ncols col = idx % _ncols return (row, col) def _loc_to_index(self, loc): _ncols = self.figure._ncols return loc[0] * _ncols + loc[1] def subplot(self, x, y): x = np.max([0, np.min([x, self.figure._nrows - 1])]) y = np.max([0, np.min([y, self.figure._ncols - 1])]) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) self.plotter.subplot(x, y) def scene(self): return self.figure def update_lighting(self): # Inspired from Mayavi's version of Raymond Maple 3-lights illumination for renderer in self._all_renderers: lights = list(renderer.GetLights()) headlight = lights.pop(0) headlight.SetSwitch(False) # below and centered, left and above, right and above az_el_in = ((0, -45, 0.7), (-60, 30, 0.7), (60, 30, 0.7)) for li, light in enumerate(lights): if li < len(az_el_in): light.SetSwitch(True) light.SetPosition(_to_pos(*az_el_in[li][:2])) light.SetIntensity(az_el_in[li][2]) else: light.SetSwitch(False) light.SetPosition(_to_pos(0.0, 0.0)) light.SetIntensity(0.0) light.SetColor(1.0, 1.0, 1.0) def set_interaction(self, interaction): if not hasattr(self.plotter, "iren") or self.plotter.iren is None: return if interaction == "rubber_band_2d": for renderer in self._all_renderers: renderer.enable_parallel_projection() if hasattr(self.plotter, 'enable_rubber_band_2d_style'): self.plotter.enable_rubber_band_2d_style() else: style = vtk.vtkInteractorStyleRubberBand2D() self.plotter.interactor.SetInteractorStyle(style) else: for renderer in self._all_renderers: renderer.disable_parallel_projection() getattr(self.plotter, f'enable_{interaction}_style')() def legend(self, labels, border=False, size=0.1, face='triangle', loc='upper left'): return self.plotter.add_legend( labels, size=(size, size), face=face, loc=loc) def polydata(self, mesh, color=None, opacity=1.0, normals=None, backface_culling=False, scalars=None, colormap=None, vmin=None, vmax=None, interpolate_before_map=True, representation='surface', line_width=1., polygon_offset=None, **kwargs): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) rgba = False if color is not None and len(color) == mesh.n_points: if color.shape[1] == 3: scalars = np.c_[color, np.ones(mesh.n_points)] else: scalars = color scalars = (scalars * 255).astype('ubyte') color = None rgba = True if isinstance(colormap, np.ndarray): if colormap.dtype == np.uint8: colormap = colormap.astype(np.float64) / 255. from matplotlib.colors import ListedColormap colormap = ListedColormap(colormap) if normals is not None: _point_data(mesh)["Normals"] = normals mesh.GetPointData().SetActiveNormals("Normals") else: _compute_normals(mesh) if 'rgba' in kwargs: rgba = kwargs["rgba"] kwargs.pop('rgba') actor = _add_mesh( plotter=self.plotter, mesh=mesh, color=color, scalars=scalars, rgba=rgba, opacity=opacity, cmap=colormap, backface_culling=backface_culling, rng=[vmin, vmax], show_scalar_bar=False, smooth_shading=self.smooth_shading, interpolate_before_map=interpolate_before_map, style=representation, line_width=line_width, **kwargs, ) if polygon_offset is not None: mapper = actor.GetMapper() mapper.SetResolveCoincidentTopologyToPolygonOffset() mapper.SetRelativeCoincidentTopologyPolygonOffsetParameters( polygon_offset, polygon_offset) return actor, mesh def mesh(self, x, y, z, triangles, color, opacity=1.0, shading=False, backface_culling=False, scalars=None, colormap=None, vmin=None, vmax=None, interpolate_before_map=True, representation='surface', line_width=1., normals=None, polygon_offset=None, **kwargs): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) vertices = np.c_[x, y, z].astype(float) triangles = np.c_[np.full(len(triangles), 3), triangles] mesh = PolyData(vertices, triangles) return self.polydata( mesh=mesh, color=color, opacity=opacity, normals=normals, backface_culling=backface_culling, scalars=scalars, colormap=colormap, vmin=vmin, vmax=vmax, interpolate_before_map=interpolate_before_map, representation=representation, line_width=line_width, polygon_offset=polygon_offset, **kwargs, ) def contour(self, surface, scalars, contours, width=1.0, opacity=1.0, vmin=None, vmax=None, colormap=None, normalized_colormap=False, kind='line', color=None): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) if colormap is not None: colormap = _get_colormap_from_array(colormap, normalized_colormap) vertices = np.array(surface['rr']) triangles = np.array(surface['tris']) n_triangles = len(triangles) triangles = np.c_[np.full(n_triangles, 3), triangles] mesh = PolyData(vertices, triangles) _point_data(mesh)['scalars'] = scalars contour = mesh.contour(isosurfaces=contours) line_width = width if kind == 'tube': contour = contour.tube(radius=width, n_sides=self.tube_n_sides) line_width = 1.0 actor = _add_mesh( plotter=self.plotter, mesh=contour, show_scalar_bar=False, line_width=line_width, color=color, rng=[vmin, vmax], cmap=colormap, opacity=opacity, smooth_shading=self.smooth_shading ) return actor, contour def surface(self, surface, color=None, opacity=1.0, vmin=None, vmax=None, colormap=None, normalized_colormap=False, scalars=None, backface_culling=False, polygon_offset=None): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) normals = surface.get('nn', None) vertices = np.array(surface['rr']) triangles = np.array(surface['tris']) triangles = np.c_[np.full(len(triangles), 3), triangles] mesh = PolyData(vertices, triangles) colormap = _get_colormap_from_array(colormap, normalized_colormap) if scalars is not None: _point_data(mesh)['scalars'] = scalars return self.polydata( mesh=mesh, color=color, opacity=opacity, normals=normals, backface_culling=backface_culling, scalars=scalars, colormap=colormap, vmin=vmin, vmax=vmax, polygon_offset=polygon_offset, ) def sphere(self, center, color, scale, opacity=1.0, resolution=8, backface_culling=False, radius=None): factor = 1.0 if radius is not None else scale center = np.array(center, dtype=float) if len(center) == 0: return None, None _check_option('center.ndim', center.ndim, (1, 2)) _check_option('center.shape[-1]', center.shape[-1], (3,)) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(resolution) sphere.SetPhiResolution(resolution) if radius is not None: sphere.SetRadius(radius) sphere.Update() geom = sphere.GetOutput() mesh = PolyData(center) glyph = mesh.glyph(orient=False, scale=False, factor=factor, geom=geom) actor = _add_mesh( self.plotter, mesh=glyph, color=color, opacity=opacity, backface_culling=backface_culling, smooth_shading=self.smooth_shading ) return actor, glyph def tube(self, origin, destination, radius=0.001, color='white', scalars=None, vmin=None, vmax=None, colormap='RdBu', normalized_colormap=False, reverse_lut=False): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) cmap = _get_colormap_from_array(colormap, normalized_colormap) for (pointa, pointb) in zip(origin, destination): line = Line(pointa, pointb) if scalars is not None: _point_data(line)['scalars'] = scalars[0, :] scalars = 'scalars' color = None else: scalars = None tube = line.tube(radius, n_sides=self.tube_n_sides) actor = _add_mesh( plotter=self.plotter, mesh=tube, scalars=scalars, flip_scalars=reverse_lut, rng=[vmin, vmax], color=color, show_scalar_bar=False, cmap=cmap, smooth_shading=self.smooth_shading, ) return actor, tube def quiver3d(self, x, y, z, u, v, w, color, scale, mode, resolution=8, glyph_height=None, glyph_center=None, glyph_resolution=None, opacity=1.0, scale_mode='none', scalars=None, colormap=None, backface_culling=False, line_width=2., name=None, glyph_width=None, glyph_depth=None, glyph_radius=0.15, solid_transform=None, *, clim=None): _check_option('mode', mode, ALLOWED_QUIVER_MODES) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) factor = scale vectors = np.c_[u, v, w] points = np.vstack(np.c_[x, y, z]) n_points = len(points) cell_type = np.full(n_points, vtk.VTK_VERTEX) cells = np.c_[np.full(n_points, 1), range(n_points)] args = (cells, cell_type, points) if not VTK9: args = (np.arange(n_points) * 3,) + args grid = UnstructuredGrid(*args) if scalars is not None: _point_data(grid)['scalars'] = np.array(scalars) scalars = 'scalars' _point_data(grid)['vec'] = vectors if scale_mode == 'scalar': scale = scalars scalars = None elif scale_mode == 'vector': scale = True else: scale = False if mode == '2darrow': return _arrow_glyph(grid, factor), grid elif mode == 'arrow': alg = _glyph( grid, orient='vec', scalars=scale, factor=factor ) mesh = pyvista.wrap(alg.GetOutput()) else: tr = None if mode == 'cone': glyph = vtk.vtkConeSource() glyph.SetCenter(0.5, 0, 0) if glyph_radius is not None: glyph.SetRadius(glyph_radius) elif mode == 'cylinder': glyph = vtk.vtkCylinderSource() if glyph_radius is not None: glyph.SetRadius(glyph_radius) elif mode == 'oct': glyph = vtk.vtkPlatonicSolidSource() glyph.SetSolidTypeToOctahedron() else: assert mode == 'sphere', mode # guaranteed above glyph = vtk.vtkSphereSource() if mode == 'cylinder': if glyph_height is not None: glyph.SetHeight(glyph_height) if glyph_center is not None: glyph.SetCenter(glyph_center) if glyph_resolution is not None: glyph.SetResolution(glyph_resolution) tr = vtk.vtkTransform() tr.RotateWXYZ(90, 0, 0, 1) elif mode == 'oct': if solid_transform is not None: assert solid_transform.shape == (4, 4) tr = vtk.vtkTransform() tr.SetMatrix( solid_transform.astype(np.float64).ravel()) if tr is not None: # fix orientation glyph.Update() trp = vtk.vtkTransformPolyDataFilter() trp.SetInputData(glyph.GetOutput()) trp.SetTransform(tr) glyph = trp glyph.Update() geom = glyph.GetOutput() mesh = grid.glyph(orient='vec', scale=scale, factor=factor, geom=geom) actor = _add_mesh( self.plotter, mesh=mesh, color=color, opacity=opacity, scalars=scalars, colormap=colormap, show_scalar_bar=False, backface_culling=backface_culling, clim=clim, ) return actor, mesh def text2d(self, x_window, y_window, text, size=14, color='white', justification=None): size = 14 if size is None else size position = (x_window, y_window) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) actor = self.plotter.add_text(text, position=position, font_size=size, color=color, viewport=True) if isinstance(justification, str): if justification == 'left': actor.GetTextProperty().SetJustificationToLeft() elif justification == 'center': actor.GetTextProperty().SetJustificationToCentered() elif justification == 'right': actor.GetTextProperty().SetJustificationToRight() else: raise ValueError('Expected values for `justification`' 'are `left`, `center` or `right` but ' 'got {} instead.'.format(justification)) _hide_testing_actor(actor) return actor def text3d(self, x, y, z, text, scale, color='white'): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) kwargs = dict( points=np.array([x, y, z]).astype(float), labels=[text], point_size=scale, text_color=color, font_family=self.font_family, name=text, shape_opacity=0, ) if 'always_visible' in _get_args(self.plotter.add_point_labels): kwargs['always_visible'] = True actor = self.plotter.add_point_labels(**kwargs) _hide_testing_actor(actor) return actor def scalarbar(self, source, color="white", title=None, n_labels=4, bgcolor=None, **extra_kwargs): if isinstance(source, vtk.vtkMapper): mapper = source elif isinstance(source, vtk.vtkActor): mapper = source.GetMapper() else: mapper = None with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) kwargs = dict(color=color, title=title, n_labels=n_labels, use_opacity=False, n_colors=256, position_x=0.15, position_y=0.05, width=0.7, shadow=False, bold=True, label_font_size=22, font_family=self.font_family, background_color=bgcolor, mapper=mapper) kwargs.update(extra_kwargs) actor = self.plotter.add_scalar_bar(**kwargs) _hide_testing_actor(actor) return actor def show(self): self.plotter.show() def close(self): _close_3d_figure(figure=self.figure) def set_camera(self, azimuth=None, elevation=None, distance=None, focalpoint='auto', roll=None, reset_camera=True, rigid=None, update=True): _set_3d_view(self.figure, azimuth=azimuth, elevation=elevation, distance=distance, focalpoint=focalpoint, roll=roll, reset_camera=reset_camera, rigid=rigid, update=update) def reset_camera(self): self.plotter.reset_camera() def screenshot(self, mode='rgb', filename=None): return _take_3d_screenshot(figure=self.figure, mode=mode, filename=filename) def project(self, xyz, ch_names): xy = _3d_to_2d(self.plotter, xyz) xy = dict(zip(ch_names, xy)) # pts = self.fig.children[-1] pts = self.plotter.renderer.GetActors().GetLastItem() return _Projection(xy=xy, pts=pts, plotter=self.plotter) def _enable_depth_peeling(self): if not self.depth_peeling: return if not self.figure.store['off_screen']: for renderer in self._all_renderers: renderer.enable_depth_peeling() def _enable_antialias(self): """Enable it everywhere except Azure.""" if not self.antialias: return # XXX for some reason doing this on Azure causes access violations: # ##[error]Cmd.exe exited with code '-1073741819' # So for now don't use it there. Maybe has to do with setting these # before the window has actually been made "active"...? # For Mayavi we have an "on activated" event or so, we should look into # using this for Azure at some point, too. if self.figure._is_active(): # macOS, Azure bad_system = ( sys.platform == 'darwin' or os.getenv('AZURE_CI_WINDOWS', 'false').lower() == 'true') # MESA (could use GPUInfo / _get_gpu_info here, but it takes # > 700 ms to make a new window + report capabilities!) # CircleCI's is: "Mesa 20.0.8 via llvmpipe (LLVM 10.0.0, 256 bits)" gpu_info = self.plotter.ren_win.ReportCapabilities() gpu_info = re.findall("OpenGL renderer string:(.+)\n", gpu_info) bad_system |= 'mesa' in ' '.join(gpu_info).lower().split() if not bad_system: for renderer in self._all_renderers: renderer.enable_anti_aliasing() for plotter in self._all_plotters: plotter.ren_win.LineSmoothingOn() def remove_mesh(self, mesh_data): actor, _ = mesh_data self.plotter.remove_actor(actor) @contextmanager def _disabled_interaction(self): if not self.plotter.renderer.GetInteractive(): yield else: self.plotter.disable() try: yield finally: self.plotter.enable() def _actor(self, mapper=None): actor = vtk.vtkActor() if mapper is not None: actor.SetMapper(mapper) _hide_testing_actor(actor) return actor def _process_events(self): for plotter in self._all_plotters: _process_events(plotter) def _update_picking_callback(self, on_mouse_move, on_button_press, on_button_release, on_pick): add_obs = self.plotter.iren.add_observer add_obs(vtk.vtkCommand.RenderEvent, on_mouse_move) add_obs(vtk.vtkCommand.LeftButtonPressEvent, on_button_press) add_obs(vtk.vtkCommand.EndInteractionEvent, on_button_release) self.plotter.picker = vtk.vtkCellPicker() self.plotter.picker.AddObserver( vtk.vtkCommand.EndPickEvent, on_pick ) self.plotter.picker.SetVolumeOpacityIsovalue(0.) def _set_mesh_scalars(self, mesh, scalars, name): # Catch: FutureWarning: Conversion of the second argument of # issubdtype from `complex` to `np.complexfloating` is deprecated. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) _point_data(mesh)[name] = scalars def _set_colormap_range(self, actor, ctable, scalar_bar, rng=None, background_color=None): from vtk.util.numpy_support import numpy_to_vtk if rng is not None: mapper = actor.GetMapper() mapper.SetScalarRange(*rng) lut = mapper.GetLookupTable() lut.SetTable(numpy_to_vtk(ctable)) if scalar_bar is not None: lut = scalar_bar.GetLookupTable() if background_color is not None: background_color = np.array(background_color) * 255 ctable = _alpha_blend_background(ctable, background_color) lut.SetTable(numpy_to_vtk(ctable, array_type=vtk.VTK_UNSIGNED_CHAR)) lut.SetRange(*rng) def _set_volume_range(self, volume, ctable, alpha, scalar_bar, rng): import vtk from vtk.util.numpy_support import numpy_to_vtk color_tf = vtk.vtkColorTransferFunction() opacity_tf = vtk.vtkPiecewiseFunction() for loc, color in zip(np.linspace(*rng, num=len(ctable)), ctable): color_tf.AddRGBPoint(loc, *(color[:-1] / 255.)) opacity_tf.AddPoint(loc, color[-1] * alpha / 255.) color_tf.ClampingOn() opacity_tf.ClampingOn() prop = volume.GetProperty() prop.SetColor(color_tf) prop.SetScalarOpacity(opacity_tf) prop.ShadeOn() prop.SetInterpolationTypeToLinear() if scalar_bar is not None: lut = vtk.vtkLookupTable() lut.SetRange(*rng) lut.SetTable(numpy_to_vtk(ctable)) scalar_bar.SetLookupTable(lut) def _sphere(self, center, color, radius): sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(8) sphere.SetPhiResolution(8) sphere.SetRadius(radius) sphere.SetCenter(center) sphere.Update() mesh = pyvista.wrap(sphere.GetOutput()) actor = _add_mesh( self.plotter, mesh=mesh, color=color ) return actor, mesh def _volume(self, dimensions, origin, spacing, scalars, surface_alpha, resolution, blending, center): # Now we can actually construct the visualization grid = pyvista.UniformGrid() grid.dimensions = dimensions + 1 # inject data on the cells grid.origin = origin grid.spacing = spacing _cell_data(grid)['values'] = scalars # Add contour of enclosed volume (use GetOutput instead of # GetOutputPort below to avoid updating) if surface_alpha > 0 or resolution is not None: grid_alg = vtk.vtkCellDataToPointData() grid_alg.SetInputDataObject(grid) grid_alg.SetPassCellData(False) grid_alg.Update() else: grid_alg = None if surface_alpha > 0: grid_surface = vtk.vtkMarchingContourFilter() grid_surface.ComputeNormalsOn() grid_surface.ComputeScalarsOff() grid_surface.SetInputData(grid_alg.GetOutput()) grid_surface.SetValue(0, 0.1) grid_surface.Update() grid_mesh = vtk.vtkPolyDataMapper() grid_mesh.SetInputData(grid_surface.GetOutput()) else: grid_mesh = None mapper = vtk.vtkSmartVolumeMapper() if resolution is None: # native mapper.SetScalarModeToUseCellData() mapper.SetInputDataObject(grid) else: upsampler = vtk.vtkImageReslice() upsampler.SetInterpolationModeToLinear() # default anyway upsampler.SetOutputSpacing(*([resolution] * 3)) upsampler.SetInputConnection(grid_alg.GetOutputPort()) mapper.SetInputConnection(upsampler.GetOutputPort()) # Additive, AverageIntensity, and Composite might also be reasonable remap = dict(composite='Composite', mip='MaximumIntensity') getattr(mapper, f'SetBlendModeTo{remap[blending]}')() volume_pos = vtk.vtkVolume() volume_pos.SetMapper(mapper) dist = grid.length / (np.mean(grid.dimensions) - 1) volume_pos.GetProperty().SetScalarOpacityUnitDistance(dist) if center is not None and blending == 'mip': # We need to create a minimum intensity projection for the neg half mapper_neg = vtk.vtkSmartVolumeMapper() if resolution is None: # native mapper_neg.SetScalarModeToUseCellData() mapper_neg.SetInputDataObject(grid) else: mapper_neg.SetInputConnection(upsampler.GetOutputPort()) mapper_neg.SetBlendModeToMinimumIntensity() volume_neg = vtk.vtkVolume() volume_neg.SetMapper(mapper_neg) volume_neg.GetProperty().SetScalarOpacityUnitDistance(dist) else: volume_neg = None return grid, grid_mesh, volume_pos, volume_neg def _silhouette(self, mesh, color=None, line_width=None, alpha=None, decimate=None): mesh = mesh.decimate(decimate) if decimate is not None else mesh silhouette_filter = vtk.vtkPolyDataSilhouette() silhouette_filter.SetInputData(mesh) silhouette_filter.SetCamera(self.plotter.renderer.GetActiveCamera()) silhouette_filter.SetEnableFeatureAngle(0) silhouette_mapper = vtk.vtkPolyDataMapper() silhouette_mapper.SetInputConnection( silhouette_filter.GetOutputPort()) actor, prop = self.plotter.add_actor( silhouette_mapper, reset_camera=False, name=None, culling=False, pickable=False, render=False) if color is not None: prop.SetColor(*color) if alpha is not None: prop.SetOpacity(alpha) if line_width is not None: prop.SetLineWidth(line_width) _hide_testing_actor(actor) return actor def _compute_normals(mesh): """Patch PyVista compute_normals.""" if 'Normals' not in _point_data(mesh): mesh.compute_normals( cell_normals=False, consistent_normals=False, non_manifold_traversal=False, inplace=True, ) def _add_mesh(plotter, *args, **kwargs): """Patch PyVista add_mesh.""" mesh = kwargs.get('mesh') if 'smooth_shading' in kwargs: smooth_shading = kwargs.pop('smooth_shading') else: smooth_shading = True # disable rendering pass for add_mesh, render() # is called in show() if 'render' not in kwargs: kwargs['render'] = False actor = plotter.add_mesh(*args, **kwargs) if smooth_shading and 'Normals' in _point_data(mesh): prop = actor.GetProperty() prop.SetInterpolationToPhong() _hide_testing_actor(actor) return actor def _hide_testing_actor(actor): from . import renderer if renderer.MNE_3D_BACKEND_TESTING: actor.SetVisibility(False) def _deg2rad(deg): return deg * np.pi / 180. def _rad2deg(rad): return rad * 180. / np.pi def _to_pos(azimuth, elevation): theta = azimuth * np.pi / 180.0 phi = (90.0 - elevation) * np.pi / 180.0 x = np.sin(theta) * np.sin(phi) y = np.cos(phi) z = np.cos(theta) * np.sin(phi) return x, y, z def _mat_to_array(vtk_mat): e = [vtk_mat.GetElement(i, j) for i in range(4) for j in range(4)] arr = np.array(e, dtype=float) arr.shape = (4, 4) return arr def _3d_to_2d(plotter, xyz): # https://vtk.org/Wiki/VTK/Examples/Cxx/Utilities/Coordinate import vtk coordinate = vtk.vtkCoordinate() coordinate.SetCoordinateSystemToWorld() xy = list() for coord in xyz: coordinate.SetValue(*coord) xy.append(coordinate.GetComputedLocalDisplayValue(plotter.renderer)) xy = np.array(xy, float).reshape(-1, 2) # in case it's empty return xy def _close_all(): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) close_all() _FIGURES.clear() def _get_camera_direction(focalpoint, position): x, y, z = position - focalpoint r = np.sqrt(x * x + y * y + z * z) theta = np.arccos(z / r) phi = np.arctan2(y, x) return r, theta, phi def _set_3d_view(figure, azimuth=None, elevation=None, focalpoint='auto', distance=None, roll=None, reset_camera=True, rigid=None, update=True): rigid = np.eye(4) if rigid is None else rigid position = np.array(figure.plotter.camera_position[0]) bounds = np.array(figure.plotter.renderer.ComputeVisiblePropBounds()) if reset_camera: figure.plotter.reset_camera() # focalpoint: if 'auto', we use the center of mass of the visible # bounds, if None, we use the existing camera focal point otherwise # we use the values given by the user if isinstance(focalpoint, str): _check_option('focalpoint', focalpoint, ('auto',), extra='when a string') focalpoint = (bounds[1::2] + bounds[::2]) * 0.5 elif focalpoint is None: focalpoint = np.array(figure.plotter.camera_position[1]) else: focalpoint = np.asarray(focalpoint) # work in the transformed space position = apply_trans(rigid, position) focalpoint = apply_trans(rigid, focalpoint) _, theta, phi = _get_camera_direction(focalpoint, position) if azimuth is not None: phi = _deg2rad(azimuth) if elevation is not None: theta = _deg2rad(elevation) # set the distance if distance is None: distance = max(bounds[1::2] - bounds[::2]) * 2.0 # Now calculate the view_up vector of the camera. If the view up is # close to the 'z' axis, the view plane normal is parallel to the # camera which is unacceptable, so we use a different view up. if elevation is None or 5. <= abs(elevation) <= 175.: view_up = [0, 0, 1] else: view_up = [0, 1, 0] position = [ distance * np.cos(phi) * np.sin(theta), distance * np.sin(phi) * np.sin(theta), distance * np.cos(theta)] figure._azimuth = _rad2deg(phi) figure._elevation = _rad2deg(theta) # restore to the original frame rigid = np.linalg.inv(rigid) position = apply_trans(rigid, position) focalpoint = apply_trans(rigid, focalpoint) view_up = apply_trans(rigid, view_up, move=False) figure.plotter.camera_position = [ position, focalpoint, view_up] # We need to add the requested roll to the roll dictated by the # transformed view_up if roll is not None: figure.plotter.camera.SetRoll(figure.plotter.camera.GetRoll() + roll) if update: figure.plotter.update() _process_events(figure.plotter) def _set_3d_title(figure, title, size=16): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) figure.plotter.add_text(title, font_size=size, color='white', name='title') figure.plotter.update() _process_events(figure.plotter) def _check_3d_figure(figure): if not isinstance(figure, PyVistaFigure): raise TypeError('figure must be an instance of PyVistaFigure.') def _close_3d_figure(figure): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) # copy the plotter locally because figure.plotter is modified plotter = figure.plotter # close the window plotter.close() # additional cleaning following signal_close _process_events(plotter) # free memory and deregister from the scraper plotter.deep_clean() # remove internal references del _ALL_PLOTTERS[plotter._id_name] _process_events(plotter) def _take_3d_screenshot(figure, mode='rgb', filename=None): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) _process_events(figure.plotter) return figure.plotter.screenshot( transparent_background=(mode == 'rgba'), filename=filename) def _process_events(plotter): if hasattr(plotter, 'app'): with warnings.catch_warnings(record=True): warnings.filterwarnings('ignore', 'constrained_layout') plotter.app.processEvents() def _add_camera_callback(camera, callback): camera.AddObserver(vtk.vtkCommand.ModifiedEvent, callback) def _arrow_glyph(grid, factor): glyph = vtk.vtkGlyphSource2D() glyph.SetGlyphTypeToArrow() glyph.FilledOff() glyph.Update() # fix position tr = vtk.vtkTransform() tr.Translate(0.5, 0., 0.) trp = vtk.vtkTransformPolyDataFilter() trp.SetInputConnection(glyph.GetOutputPort()) trp.SetTransform(tr) trp.Update() alg = _glyph( grid, scale_mode='vector', scalars=False, orient='vec', factor=factor, geom=trp.GetOutputPort(), ) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(alg.GetOutputPort()) return mapper def _glyph(dataset, scale_mode='scalar', orient=True, scalars=True, factor=1.0, geom=None, tolerance=0.0, absolute=False, clamping=False, rng=None): if geom is None: arrow = vtk.vtkArrowSource() arrow.Update() geom = arrow.GetOutputPort() alg = vtk.vtkGlyph3D() alg.SetSourceConnection(geom) if isinstance(scalars, str): dataset.active_scalars_name = scalars if isinstance(orient, str): dataset.active_vectors_name = orient orient = True if scale_mode == 'scalar': alg.SetScaleModeToScaleByScalar() elif scale_mode == 'vector': alg.SetScaleModeToScaleByVector() else: alg.SetScaleModeToDataScalingOff() if rng is not None: alg.SetRange(rng) alg.SetOrient(orient) alg.SetInputData(dataset) alg.SetScaleFactor(factor) alg.SetClamping(clamping) alg.Update() return alg @contextmanager def _disabled_depth_peeling(): try: from pyvista import global_theme except Exception: # workaround for older PyVista from pyvista import rcParams depth_peeling = rcParams['depth_peeling'] else: depth_peeling = global_theme.depth_peeling depth_peeling_enabled = depth_peeling["enabled"] depth_peeling["enabled"] = False try: yield finally: depth_peeling["enabled"] = depth_peeling_enabled
[]
[]
[ "AZURE_CI_WINDOWS" ]
[]
["AZURE_CI_WINDOWS"]
python
1
0
pkg/helm/render_test.go
package helm import ( "bytes" "context" "fmt" "io" "io/ioutil" "log" "net/http" "net/http/httptest" "os" "path/filepath" "sort" "testing" "time" helmyaml "github.com/ghodss/yaml" "github.com/mgoltzsche/khelm/pkg/config" "github.com/stretchr/testify/require" "k8s.io/helm/pkg/getter" cli "k8s.io/helm/pkg/helm/environment" "k8s.io/helm/pkg/helm/helmpath" "k8s.io/helm/pkg/proto/hapi/chart" "k8s.io/helm/pkg/repo" "sigs.k8s.io/kustomize/kyaml/yaml" ) var rootDir = func() string { wd, err := os.Getwd() if err != nil { panic(err) } return filepath.Join(wd, "..", "..") }() func TestRender(t *testing.T) { expectedJenkinsContained := "- host: \"jenkins.example.org\"\n" for _, c := range []struct { name string file string expectedNamespaces []string expectedContained string expectedResourceNames []string }{ {"jenkins", "example/jenkins/generator.yaml", []string{"jenkins"}, expectedJenkinsContained, nil}, {"values-external", "pkg/helm/generatorwithextvalues.yaml", []string{"jenkins"}, expectedJenkinsContained, nil}, {"rook-ceph-version-range", "example/rook-ceph/operator/generator.yaml", []string{}, "rook-ceph-v0.9.3", nil}, {"cert-manager", "example/cert-manager/generator.yaml", []string{"cert-manager", "kube-system"}, " name: cert-manager-webhook", nil}, {"apiversions-condition", "example/apiversions-condition/generator.yaml", []string{}, " config: fancy-config", nil}, {"expand-list", "example/expand-list/generator.yaml", []string{"ns1", "ns2", "ns3"}, "\n name: myserviceaccount2\n", nil}, {"namespace", "example/namespace/generator.yaml", []string{"default-namespace", "cluster-role-binding-ns"}, " key: b", nil}, {"force-namespace", "example/force-namespace/generator.yaml", []string{"forced-namespace"}, " key: b", nil}, {"kubeVersion", "example/release-name/generator.yaml", []string{}, " k8sVersion: v1.17.0", nil}, {"release-name", "example/release-name/generator.yaml", []string{}, " name: my-release-name-config", nil}, {"exclude", "example/exclude/generator.yaml", []string{"cluster-role-binding-ns"}, " key: b", nil}, {"include", "example/include/generator.yaml", []string{}, " key: b", nil}, {"local-chart-with-local-dependency-and-transitive-remote", "example/localrefref/generator.yaml", []string{}, "rook-ceph-v0.9.3", nil}, {"local-chart-with-remote-dependency", "example/localref/generator.yaml", []string{}, "rook-ceph-v0.9.3", nil}, {"values-inheritance", "example/values-inheritance/generator.yaml", []string{}, " inherited: inherited value\n fileoverwrite: overwritten by file\n valueoverwrite: overwritten by generator config", nil}, {"cluster-scoped", "example/cluster-scoped/generator.yaml", []string{}, "myrolebinding", nil}, {"chart-hooks", "example/chart-hooks/generator.yaml", []string{"default"}, " key: myvalue", []string{ "chart-hooks-myconfig", "chart-hooks-post-delete", "chart-hooks-post-install", "chart-hooks-post-upgrade", "chart-hooks-pre-delete", "chart-hooks-pre-install", "chart-hooks-pre-rollback", "chart-hooks-pre-upgrade", "chart-hooks-test", }}, {"chart-hooks-disabled", "example/chart-hooks-disabled/generator.yaml", []string{"default"}, " key: myvalue", []string{"chart-hooks-disabled-myconfig"}}, } { t.Run(c.name, func(t *testing.T) { for _, cached := range []string{"", "cached "} { var rendered bytes.Buffer absFile := filepath.Join(rootDir, c.file) err := renderFile(t, absFile, true, rootDir, &rendered) require.NoError(t, err, "render %s%s", cached, absFile) b := rendered.Bytes() l, err := readYaml(b) require.NoError(t, err, "rendered %syaml:\n%s", cached, b) require.True(t, len(l) > 0, "%s: rendered result of %s is empty", cached, c.file) require.Contains(t, rendered.String(), c.expectedContained, "%syaml", cached) foundResourceNames := []string{} foundNamespaces := map[string]struct{}{} for i, o := range l { require.NotNilf(t, o["metadata"], "%s object %d metadata", cached, i) ns := "" meta := o["metadata"].(map[string]interface{}) foundResourceNames = append(foundResourceNames, meta["name"].(string)) nsVal, ok := meta["namespace"] if ok { if ns, ok = nsVal.(string); ok { foundNamespaces[ns] = struct{}{} } require.NotEmpty(t, ns, "%s%s: output resource declares empty namespace field", cached, c.file) } subjects, ok := o["subjects"].([]interface{}) if ok && len(subjects) > 0 { if subject, ok := subjects[0].(map[string]interface{}); ok { if ns, ok = subject["namespace"].(string); ok { require.NotEmpty(t, ns, "%s%s: output resource has empty subjects[0].namespace set explicitly", cached, c.file) foundNamespaces[ns] = struct{}{} } } } } foundNs := []string{} for k := range foundNamespaces { foundNs = append(foundNs, k) } sort.Strings(c.expectedNamespaces) sort.Strings(foundNs) require.Equal(t, c.expectedNamespaces, foundNs, "%s%s: namespaces of output resource", cached, c.file) if len(c.expectedResourceNames) > 0 { require.Equal(t, c.expectedResourceNames, foundResourceNames, "resource names") } } }) } } func TestRenderUntrustedRepositoryError(t *testing.T) { dir, err := ioutil.TempDir("", "khelm-test-untrusted-repo-") require.NoError(t, err) defer os.RemoveAll(dir) os.Setenv("HELM_HOME", dir) defer os.Unsetenv("HELM_HOME") file := filepath.Join(rootDir, "example/rook-ceph/operator/generator.yaml") err = renderFile(t, file, false, rootDir, &bytes.Buffer{}) require.Error(t, err, file) } func TestRenderInvalidRequirementsLockError(t *testing.T) { file := filepath.Join(rootDir, "example/invalid-requirements-lock/generator.yaml") err := renderFile(t, file, true, rootDir, &bytes.Buffer{}) require.Error(t, err, "render %s", file) } func TestRenderUnexpectedClusterScopedResourcesError(t *testing.T) { file := filepath.Join(rootDir, "example/cluster-scoped-forbidden/generator.yaml") err := renderFile(t, file, true, rootDir, &bytes.Buffer{}) require.Error(t, err, "render %s", file) } func TestRenderExclude(t *testing.T) { file := filepath.Join(rootDir, "example/exclude/generator.yaml") buf := bytes.Buffer{} err := renderFile(t, file, true, rootDir, &buf) require.NoError(t, err, "render %s", file) require.Contains(t, buf.String(), "myconfigb") require.NotContains(t, buf.String(), "myconfiga") } func TestRenderExclusionNoMatchError(t *testing.T) { file := filepath.Join(rootDir, "example/exclude-nomatch/generator.yaml") buf := bytes.Buffer{} err := renderFile(t, file, true, rootDir, &buf) require.Error(t, err, "render %s", file) } func TestRenderRebuildsLocalDependencies(t *testing.T) { tplDir := filepath.Join(rootDir, "example/localref/intermediate-chart/templates") tplFile := filepath.Join(tplDir, "changed.yaml") configFile := filepath.Join(rootDir, "example/localrefref/generator.yaml") os.RemoveAll(tplDir) // Render once to ensure the dependency has been built already err := renderFile(t, configFile, true, rootDir, &bytes.Buffer{}) require.NoError(t, err, "1st render") // Change the dependency err = os.Mkdir(tplDir, 0755) require.NoError(t, err) defer os.RemoveAll(tplDir) data := []byte("apiVersion: fancyapi/v1\nkind: FancyKind\nmetadata:\n name: sth\nchangedField: changed-value") err = ioutil.WriteFile(tplFile, data, 0600) require.NoError(t, err) // Render again and verify that the dependency is rebuilt var rendered bytes.Buffer err = renderFile(t, configFile, true, rootDir, &rendered) require.NoError(t, err, "render after dependency has changed") require.Contains(t, rendered.String(), "changedField: changed-value", "local dependency changes should be reflected within the rendered output") } func TestRenderUpdateRepositoryIndexIfChartNotFound(t *testing.T) { tmpDir, err := ioutil.TempDir("", "khelm-test-") require.NoError(t, err) defer os.RemoveAll(tmpDir) settings := cli.EnvSettings{Home: helmpath.Home(tmpDir)} repoURL := "https://charts.rook.io/stable" trust := true repos, err := reposForURLs(map[string]struct{}{repoURL: {}}, &trust, &settings, getter.All(settings)) require.NoError(t, err, "use repo") entry, err := repos.Get(repoURL) require.NoError(t, err, "repos.EntryByURL()") err = repos.Close() require.NoError(t, err, "repos.Close()") err = os.MkdirAll(settings.Home.Cache(), 0755) require.NoError(t, err) idxFile := indexFile(entry, settings.Home.Cache()) idx := repo.NewIndexFile() // write empty index file to cause not found error err = idx.WriteFile(idxFile, 0644) require.NoError(t, err, "write empty index file") file := filepath.Join(rootDir, "example/rook-ceph/operator/generator.yaml") err = renderFile(t, file, true, rootDir, &bytes.Buffer{}) require.NoError(t, err, "render %s with outdated index", file) } func TestRenderUpdateRepositoryIndexIfDependencyNotFound(t *testing.T) { tmpDir, err := ioutil.TempDir("", "khelm-test-") require.NoError(t, err) defer os.RemoveAll(tmpDir) settings := cli.EnvSettings{Home: helmpath.Home(tmpDir)} repoURL := "https://kubernetes-charts.storage.googleapis.com" trust := true repos, err := reposForURLs(map[string]struct{}{repoURL: {}}, &trust, &settings, getter.All(settings)) require.NoError(t, err, "use repo") entry, err := repos.Get(repoURL) require.NoError(t, err, "repos.Get()") err = repos.Close() require.NoError(t, err, "repos.Close()") err = os.MkdirAll(settings.Home.Cache(), 0755) require.NoError(t, err) idxFile := indexFile(entry, settings.Home.Cache()) idx := repo.NewIndexFile() // write empty index file to cause not found error err = idx.WriteFile(idxFile, 0644) require.NoError(t, err, "write empty index file") err = os.RemoveAll(filepath.Join(rootDir, "example/localref/rook-ceph/charts")) require.NoError(t, err, "remove charts") file := filepath.Join(rootDir, "example/localref/generator.yaml") err = renderFile(t, file, true, rootDir, &bytes.Buffer{}) require.NoError(t, err, "render %s with outdated index", file) } func TestRenderRepositoryCredentials(t *testing.T) { // Make sure a fake chart exists that the fake server can serve err := renderFile(t, filepath.Join(rootDir, "example/localrefref/generator.yaml"), true, rootDir, &bytes.Buffer{}) require.NoError(t, err) fakeChartTgz := filepath.Join(rootDir, "example/localrefref/charts/intermediate-chart-0.1.1.tgz") // Create input chart config and fake private chart server cfg := config.NewChartConfig() cfg.Chart = "private-chart" cfg.Name = "myrelease" cfg.Version = fmt.Sprintf("0.0.%d", time.Now().Unix()) cfg.BaseDir = rootDir repoEntry := &repo.Entry{ Name: "myprivaterepo", Username: "fakeuser", Password: "fakepassword", } srv := httptest.NewServer(&fakePrivateChartServerHandler{repoEntry, &cfg.LoaderConfig, fakeChartTgz}) defer srv.Close() repoEntry.URL = srv.URL // Generate temp repository configuration pointing to fake private server tmpHelmHome, err := ioutil.TempDir("", "khelm-test-home-") require.NoError(t, err) defer os.RemoveAll(tmpHelmHome) origHelmHome := os.Getenv("HELM_HOME") err = os.Setenv("HELM_HOME", tmpHelmHome) require.NoError(t, err) defer os.Setenv("HELM_HOME", origHelmHome) repos := repo.NewRepoFile() repos.Add(repoEntry) b, err := yaml.Marshal(repos) require.NoError(t, err) err = os.Mkdir(filepath.Join(tmpHelmHome, "repository"), 0755) require.NoError(t, err) err = ioutil.WriteFile(filepath.Join(tmpHelmHome, "repository", "repositories.yaml"), b, 0600) // #nosec require.NoError(t, err) for _, c := range []struct { name string repo string }{ {"url", repoEntry.URL}, {"alias", "@" + repoEntry.Name}, {"aliasScheme", "alias:" + repoEntry.Name}, } { t.Run(c.name, func(t *testing.T) { cfg.Repository = c.repo err = render(t, *cfg, false, &bytes.Buffer{}) require.NoError(t, err, "render chart with repository credentials") }) } } type fakePrivateChartServerHandler struct { repo *repo.Entry config *config.LoaderConfig fakeChartTgz string } func (f *fakePrivateChartServerHandler) ServeHTTP(writer http.ResponseWriter, req *http.Request) { usr, pwd, ok := req.BasicAuth() if !ok || usr != f.repo.Username || pwd != f.repo.Password { writer.WriteHeader(401) return } chartFilePath := fmt.Sprintf("/%s-%s.tgz", f.config.Chart, f.config.Version) switch req.RequestURI { case "/index.yaml": idx := repo.NewIndexFile() idx.APIVersion = "v1" idx.Entries = map[string]repo.ChartVersions{ f.config.Chart: {{ Metadata: &chart.Metadata{ ApiVersion: "v1", AppVersion: f.config.Version, Version: f.config.Version, Name: f.config.Chart, }, Digest: "0000000000000000", URLs: []string{f.repo.URL + chartFilePath}, }}, } b, err := helmyaml.Marshal(idx) if err != nil { log.Println("ERROR: fake server:", err) writer.WriteHeader(500) return } writer.WriteHeader(200) _, _ = writer.Write(b) return case chartFilePath: writer.WriteHeader(200) f, err := os.Open(f.fakeChartTgz) if err == nil { defer f.Close() _, err = io.Copy(writer, f) } if err != nil { log.Println("ERROR: fake server:", err) } return } log.Println("ERROR: fake server received unexpected request:", req.RequestURI) writer.WriteHeader(404) } func renderFile(t *testing.T, file string, trustAnyRepo bool, rootDir string, writer io.Writer) error { f, err := os.Open(file) require.NoError(t, err) defer f.Close() cfg, err := config.ReadGeneratorConfig(f) require.NoError(t, err, "ReadGeneratorConfig(%s)", file) cfg.BaseDir = filepath.Dir(file) return render(t, cfg.ChartConfig, trustAnyRepo, writer) } func render(t *testing.T, req config.ChartConfig, trustAnyRepo bool, writer io.Writer) error { log.SetFlags(0) h := NewHelm() h.TrustAnyRepository = &trustAnyRepo resources, err := h.Render(context.Background(), &req) if err != nil { return err } enc := yaml.NewEncoder(writer) enc.SetIndent(2) for _, r := range resources { err = enc.Encode(r.Document()) if err != nil { return err } } return enc.Close() } func readYaml(y []byte) (l []map[string]interface{}, err error) { dec := yaml.NewDecoder(bytes.NewReader(y)) o := map[string]interface{}{} i := 0 for ; err == nil; err = dec.Decode(o) { if len(o) > 0 { l = append(l, o) o = map[string]interface{}{} } i++ } if err == io.EOF { err = nil } if err != nil { err = fmt.Errorf("invalid yaml output at resource %d: %w", i, err) } return }
[ "\"HELM_HOME\"" ]
[]
[ "HELM_HOME" ]
[]
["HELM_HOME"]
go
1
0
bootloader/waflib/Configure.py
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os, re, shlex, shutil, sys, time, traceback from waflib import ConfigSet, Utils, Options, Logs, Context, Build, Errors WAF_CONFIG_LOG = 'config.log' autoconfig = False conf_template = '''# project %(app)s configured on %(now)s by # waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s) # using %(args)s #''' class ConfigurationContext(Context.Context): '''configures the project''' cmd = 'configure' error_handlers = [] def __init__(self, **kw): super(ConfigurationContext, self).__init__(**kw) self.environ = dict(os.environ) self.all_envs = {} self.top_dir = None self.out_dir = None self.tools = [] self.hash = 0 self.files = [] self.tool_cache = [] self.setenv('') def setenv(self, name, env=None): if name not in self.all_envs or env: if not env: env = ConfigSet.ConfigSet() self.prepare_env(env) else: env = env.derive() self.all_envs[name] = env self.variant = name def get_env(self): return self.all_envs[self.variant] def set_env(self, val): self.all_envs[self.variant] = val env = property(get_env, set_env) def init_dirs(self): top = self.top_dir if not top: top = Options.options.top if not top: top = getattr(Context.g_module, Context.TOP, None) if not top: top = self.path.abspath() top = os.path.abspath(top) self.srcnode = (os.path.isabs(top) and self.root or self.path).find_dir(top) assert (self.srcnode) out = self.out_dir if not out: out = Options.options.out if not out: out = getattr(Context.g_module, Context.OUT, None) if not out: out = Options.lockfile.replace('.lock-waf_%s_' % sys.platform, '').replace('.lock-waf', '') out = os.path.realpath(out) self.bldnode = (os.path.isabs(out) and self.root or self.path).make_node(out) self.bldnode.mkdir() if not os.path.isdir(self.bldnode.abspath()): self.fatal('Could not create the build directory %s' % self.bldnode.abspath()) def execute(self): self.init_dirs() self.cachedir = self.bldnode.make_node(Build.CACHE_DIR) self.cachedir.mkdir() path = os.path.join(self.bldnode.abspath(), WAF_CONFIG_LOG) self.logger = Logs.make_logger(path, 'cfg') app = getattr(Context.g_module, 'APPNAME', '') if app: ver = getattr(Context.g_module, 'VERSION', '') if ver: app = "%s (%s)" % (app, ver) params = { 'now': time.ctime(), 'pyver': sys.hexversion, 'systype': sys.platform, 'args': " ".join(sys.argv), 'wafver': Context.WAFVERSION, 'abi': Context.ABI, 'app': app } self.to_log(conf_template % params) self.msg('Setting top to', self.srcnode.abspath()) self.msg('Setting out to', self.bldnode.abspath()) if id(self.srcnode) == id(self.bldnode): Logs.warn('Setting top == out') elif id(self.path) != id(self.srcnode): if self.srcnode.is_child_of(self.path): Logs.warn('Are you certain that you do not want to set top="." ?') super(ConfigurationContext, self).execute() self.store() Context.top_dir = self.srcnode.abspath() Context.out_dir = self.bldnode.abspath() env = ConfigSet.ConfigSet() env.argv = sys.argv env.options = Options.options.__dict__ env.config_cmd = self.cmd env.run_dir = Context.run_dir env.top_dir = Context.top_dir env.out_dir = Context.out_dir env.hash = self.hash env.files = self.files env.environ = dict(self.environ) env.launch_dir = Context.launch_dir if not ( self.env.NO_LOCK_IN_RUN or env.environ.get('NO_LOCK_IN_RUN') or getattr(Options.options, 'no_lock_in_run') ): env.store(os.path.join(Context.run_dir, Options.lockfile)) if not ( self.env.NO_LOCK_IN_TOP or env.environ.get('NO_LOCK_IN_TOP') or getattr(Options.options, 'no_lock_in_top') ): env.store(os.path.join(Context.top_dir, Options.lockfile)) if not ( self.env.NO_LOCK_IN_OUT or env.environ.get('NO_LOCK_IN_OUT') or getattr(Options.options, 'no_lock_in_out') ): env.store(os.path.join(Context.out_dir, Options.lockfile)) def prepare_env(self, env): if not env.PREFIX: if Options.options.prefix or Utils.is_win32: env.PREFIX = Options.options.prefix else: env.PREFIX = '/' if not env.BINDIR: if Options.options.bindir: env.BINDIR = Options.options.bindir else: env.BINDIR = Utils.subst_vars('${PREFIX}/bin', env) if not env.LIBDIR: if Options.options.libdir: env.LIBDIR = Options.options.libdir else: env.LIBDIR = Utils.subst_vars('${PREFIX}/lib%s' % Utils.lib64(), env) def store(self): n = self.cachedir.make_node('build.config.py') n.write('version = 0x%x\ntools = %r\n' % (Context.HEXVERSION, self.tools)) if not self.all_envs: self.fatal('nothing to store in the configuration context!') for key in self.all_envs: tmpenv = self.all_envs[key] tmpenv.store(os.path.join(self.cachedir.abspath(), key + Build.CACHE_SUFFIX)) def load(self, tool_list, tooldir=None, funs=None, with_sys_path=True, cache=False): tools = Utils.to_list(tool_list) if tooldir: tooldir = Utils.to_list(tooldir) for tool in tools: if cache: mag = (tool, id(self.env), tooldir, funs) if mag in self.tool_cache: self.to_log('(tool %s is already loaded, skipping)' % tool) continue self.tool_cache.append(mag) module = None try: module = Context.load_tool(tool, tooldir, ctx=self, with_sys_path=with_sys_path) except ImportError as e: self.fatal( 'Could not load the Waf tool %r from %r\n%s' % (tool, getattr(e, 'waf_sys_path', sys.path), e) ) except Exception as e: self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs)) self.to_log(traceback.format_exc()) raise if funs is not None: self.eval_rules(funs) else: func = getattr(module, 'configure', None) if func: if type(func) is type(Utils.readf): func(self) else: self.eval_rules(func) self.tools.append({'tool': tool, 'tooldir': tooldir, 'funs': funs}) def post_recurse(self, node): super(ConfigurationContext, self).post_recurse(node) self.hash = Utils.h_list((self.hash, node.read('rb'))) self.files.append(node.abspath()) def eval_rules(self, rules): self.rules = Utils.to_list(rules) for x in self.rules: f = getattr(self, x) if not f: self.fatal('No such configuration function %r' % x) f() def conf(f): def fun(*k, **kw): mandatory = kw.pop('mandatory', True) try: return f(*k, **kw) except Errors.ConfigurationError: if mandatory: raise fun.__name__ = f.__name__ setattr(ConfigurationContext, f.__name__, fun) setattr(Build.BuildContext, f.__name__, fun) return f @conf def add_os_flags(self, var, dest=None, dup=False): try: flags = shlex.split(self.environ[var]) except KeyError: return if dup or ''.join(flags) not in ''.join(Utils.to_list(self.env[dest or var])): self.env.append_value(dest or var, flags) @conf def cmd_to_list(self, cmd): if isinstance(cmd, str): if os.path.isfile(cmd): return [cmd] if os.sep == '/': return shlex.split(cmd) else: try: return shlex.split(cmd, posix=False) except TypeError: return shlex.split(cmd) return cmd @conf def check_waf_version(self, mini='1.9.99', maxi='2.1.0', **kw): self.start_msg('Checking for waf version in %s-%s' % (str(mini), str(maxi)), **kw) ver = Context.HEXVERSION if Utils.num2ver(mini) > ver: self.fatal('waf version should be at least %r (%r found)' % (Utils.num2ver(mini), ver)) if Utils.num2ver(maxi) < ver: self.fatal('waf version should be at most %r (%r found)' % (Utils.num2ver(maxi), ver)) self.end_msg('ok', **kw) @conf def find_file(self, filename, path_list=[]): for n in Utils.to_list(filename): for d in Utils.to_list(path_list): p = os.path.expanduser(os.path.join(d, n)) if os.path.exists(p): return p self.fatal('Could not find %r' % filename) @conf def find_program(self, filename, **kw): exts = kw.get('exts', Utils.is_win32 and '.exe,.com,.bat,.cmd' or ',.sh,.pl,.py') environ = kw.get('environ', getattr(self, 'environ', os.environ)) ret = '' filename = Utils.to_list(filename) msg = kw.get('msg', ', '.join(filename)) var = kw.get('var', '') if not var: var = re.sub(r'[-.]', '_', filename[0].upper()) path_list = kw.get('path_list', '') if path_list: path_list = Utils.to_list(path_list) else: path_list = environ.get('PATH', '').split(os.pathsep) if kw.get('value'): ret = self.cmd_to_list(kw['value']) elif environ.get(var): ret = self.cmd_to_list(environ[var]) elif self.env[var]: ret = self.cmd_to_list(self.env[var]) else: if not ret: ret = self.find_binary(filename, exts.split(','), path_list) if not ret and Utils.winreg: ret = Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER, filename) if not ret and Utils.winreg: ret = Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE, filename) ret = self.cmd_to_list(ret) if ret: if len(ret) == 1: retmsg = ret[0] else: retmsg = ret else: retmsg = False self.msg('Checking for program %r' % msg, retmsg, **kw) if not kw.get('quiet'): self.to_log('find program=%r paths=%r var=%r -> %r' % (filename, path_list, var, ret)) if not ret: self.fatal(kw.get('errmsg', '') or 'Could not find the program %r' % filename) interpreter = kw.get('interpreter') if interpreter is None: if not Utils.check_exe(ret[0], env=environ): self.fatal('Program %r is not executable' % ret) self.env[var] = ret else: self.env[var] = self.env[interpreter] + ret return ret @conf def find_binary(self, filenames, exts, paths): for f in filenames: for ext in exts: exe_name = f + ext if os.path.isabs(exe_name): if os.path.isfile(exe_name): return exe_name else: for path in paths: x = os.path.expanduser(os.path.join(path, exe_name)) if os.path.isfile(x): return x return None @conf def run_build(self, *k, **kw): buf = [] for key in sorted(kw.keys()): v = kw[key] if isinstance(v, ConfigSet.ConfigSet): continue elif hasattr(v, '__call__'): buf.append(Utils.h_fun(v)) else: buf.append(str(v)) h = Utils.h_list(buf) dir = self.bldnode.abspath() + os.sep + (not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h) cachemode = kw.get('confcache', getattr(Options.options, 'confcache', None)) if not cachemode and os.path.exists(dir): shutil.rmtree(dir) try: os.makedirs(dir) except OSError: pass try: os.stat(dir) except OSError: self.fatal('cannot use the configuration test folder %r' % dir) if cachemode == 1: try: proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build')) except EnvironmentError: pass else: ret = proj['cache_run_build'] if isinstance(ret, str) and ret.startswith('Test does not build'): self.fatal(ret) return ret bdir = os.path.join(dir, 'testbuild') if not os.path.exists(bdir): os.makedirs(bdir) cls_name = kw.get('run_build_cls') or getattr(self, 'run_build_cls', 'build') self.test_bld = bld = Context.create_context(cls_name, top_dir=dir, out_dir=bdir) bld.init_dirs() bld.progress_bar = 0 bld.targets = '*' bld.logger = self.logger bld.all_envs.update(self.all_envs) bld.env = kw['env'] bld.kw = kw bld.conf = self kw['build_fun'](bld) ret = -1 try: try: bld.compile() except Errors.WafError: ret = 'Test does not build: %s' % traceback.format_exc() self.fatal(ret) else: ret = getattr(bld, 'retval', 0) finally: if cachemode: proj = ConfigSet.ConfigSet() proj['cache_run_build'] = ret proj.store(os.path.join(dir, 'cache_run_build')) else: shutil.rmtree(dir) return ret @conf def ret_msg(self, msg, args): if isinstance(msg, str): return msg return msg(args) @conf def test(self, *k, **kw): if not 'env' in kw: kw['env'] = self.env.derive() if kw.get('validate'): kw['validate'](kw) self.start_msg(kw['msg'], **kw) ret = None try: ret = self.run_build(*k, **kw) except self.errors.ConfigurationError: self.end_msg(kw['errmsg'], 'YELLOW', **kw) if Logs.verbose > 1: raise else: self.fatal('The configuration failed') else: kw['success'] = ret if kw.get('post_check'): ret = kw['post_check'](kw) if ret: self.end_msg(kw['errmsg'], 'YELLOW', **kw) self.fatal('The configuration failed %r' % ret) else: self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw) return ret
[]
[]
[]
[]
[]
python
0
0
spinup/run.py
import spinup from spinup.user_config import DEFAULT_BACKEND from spinup.utils.run_utils import ExperimentGrid from spinup.utils.serialization_utils import convert_json import argparse import gym import roboschool import json import os, subprocess, sys import os.path as osp import string import tensorflow as tf import torch from copy import deepcopy from textwrap import dedent # Command line args that will go to ExperimentGrid.run, and must possess unique # values (therefore must be treated separately). RUN_KEYS = ['num_cpu', 'data_dir', 'datestamp'] # Command line sweetener, allowing short-form flags for common, longer flags. SUBSTITUTIONS = {'env': 'env_name', 'hid': 'ac_kwargs:hidden_sizes', 'act': 'ac_kwargs:activation', 'cpu': 'num_cpu', 'dt': 'datestamp'} # Only some algorithms can be parallelized (have num_cpu > 1): MPI_COMPATIBLE_ALGOS = ['vpg', 'trpo', 'ppo'] # Algo names (used in a few places) BASE_ALGO_NAMES = ['vpg', 'trpo', 'ppo', 'dqn', 'ddpg', 'td3', 'sac'] def add_with_backends(algo_list): # helper function to build lists with backend-specific function names algo_list_with_backends = deepcopy(algo_list) for algo in algo_list: algo_list_with_backends += [algo + '_tf1', algo + '_pytorch'] return algo_list_with_backends def friendly_err(err_msg): # add whitespace to error message to make it more readable return '\n\n' + err_msg + '\n\n' def parse_and_execute_grid_search(cmd, args): """Interprets algorithm name and cmd line args into an ExperimentGrid.""" if cmd in BASE_ALGO_NAMES: backend = DEFAULT_BACKEND[cmd] print('\n\nUsing default backend (%s) for %s.\n'%(backend, cmd)) cmd = cmd + '_' + backend algo = eval('spinup.'+cmd) # Before all else, check to see if any of the flags is 'help'. valid_help = ['--help', '-h', 'help'] if any([arg in valid_help for arg in args]): print('\n\nShowing docstring for spinup.'+cmd+':\n') print(algo.__doc__) sys.exit() def process(arg): # Process an arg by eval-ing it, so users can specify more # than just strings at the command line (eg allows for # users to give functions as args). try: return eval(arg) except: return arg # Make first pass through args to build base arg_dict. Anything # with a '--' in front of it is an argument flag and everything after, # until the next flag, is a possible value. arg_dict = dict() for i, arg in enumerate(args): assert i > 0 or '--' in arg, \ friendly_err("You didn't specify a first flag.") if '--' in arg: arg_key = arg.lstrip('-') arg_dict[arg_key] = [] else: arg_dict[arg_key].append(process(arg)) # Make second pass through, to catch flags that have no vals. # Assume such flags indicate that a boolean parameter should have # value True. for k,v in arg_dict.items(): if len(v) == 0: v.append(True) # Third pass: check for user-supplied shorthands, where a key has # the form --keyname[kn]. The thing in brackets, 'kn', is the # shorthand. NOTE: modifying a dict while looping through its # contents is dangerous, and breaks in 3.6+. We loop over a fixed list # of keys to avoid this issue. given_shorthands = dict() fixed_keys = list(arg_dict.keys()) for k in fixed_keys: p1, p2 = k.find('['), k.find(']') if p1 >= 0 and p2 >= 0: # Both '[' and ']' found, so shorthand has been given k_new = k[:p1] shorthand = k[p1+1:p2] given_shorthands[k_new] = shorthand arg_dict[k_new] = arg_dict[k] del arg_dict[k] # Penultimate pass: sugar. Allow some special shortcuts in arg naming, # eg treat "env" the same as "env_name". This is super specific # to Spinning Up implementations, and may be hard to maintain. # These special shortcuts are described by SUBSTITUTIONS. for special_name, true_name in SUBSTITUTIONS.items(): if special_name in arg_dict: # swap it in arg dict arg_dict[true_name] = arg_dict[special_name] del arg_dict[special_name] if special_name in given_shorthands: # point the shortcut to the right name given_shorthands[true_name] = given_shorthands[special_name] del given_shorthands[special_name] # Final pass: check for the special args that go to the 'run' command # for an experiment grid, separate them from the arg dict, and make sure # that they have unique values. The special args are given by RUN_KEYS. run_kwargs = dict() for k in RUN_KEYS: if k in arg_dict: val = arg_dict[k] assert len(val) == 1, \ friendly_err("You can only provide one value for %s."%k) run_kwargs[k] = val[0] del arg_dict[k] # Determine experiment name. If not given by user, will be determined # by the algorithm name. if 'exp_name' in arg_dict: assert len(arg_dict['exp_name']) == 1, \ friendly_err("You can only provide one value for exp_name.") exp_name = arg_dict['exp_name'][0] del arg_dict['exp_name'] else: exp_name = 'cmd_' + cmd # Make sure that if num_cpu > 1, the algorithm being used is compatible # with MPI. if 'num_cpu' in run_kwargs and not(run_kwargs['num_cpu'] == 1): assert cmd in add_with_backends(MPI_COMPATIBLE_ALGOS), \ friendly_err("This algorithm can't be run with num_cpu > 1.") # Special handling for environment: make sure that env_name is a real, # registered gym environment. valid_envs = [e.id for e in list(gym.envs.registry.all())] assert 'env_name' in arg_dict, \ friendly_err("You did not give a value for --env_name! Add one and try again.") for env_name in arg_dict['env_name']: err_msg = dedent(""" %s is not registered with Gym. Recommendations: * Check for a typo (did you include the version tag?) * View the complete list of valid Gym environments at https://gym.openai.com/envs/ """%env_name) assert env_name in valid_envs, err_msg # Construct and execute the experiment grid. eg = ExperimentGrid(name=exp_name) for k,v in arg_dict.items(): eg.add(k, v, shorthand=given_shorthands.get(k)) eg.run(algo, **run_kwargs) if __name__ == '__main__': """ This is a wrapper allowing command-line interfaces to individual algorithms and the plot / test_policy utilities. For utilities, it only checks which thing to run, and calls the appropriate file, passing all arguments through. For algorithms, it sets up an ExperimentGrid object and uses the ExperimentGrid run routine to execute each possible experiment. """ cmd = sys.argv[1] if len(sys.argv) > 1 else 'help' valid_algos = add_with_backends(BASE_ALGO_NAMES) valid_utils = ['plot', 'test_policy'] valid_help = ['--help', '-h', 'help'] valid_cmds = valid_algos + valid_utils + valid_help assert cmd in valid_cmds, \ "Select an algorithm or utility which is implemented in Spinning Up." if cmd in valid_help: # Before all else, check to see if any of the flags is 'help'. # List commands that are available. str_valid_cmds = '\n\t' + '\n\t'.join(valid_algos+valid_utils) help_msg = dedent(""" Experiment in Spinning Up from the command line with \tpython -m spinup.run CMD [ARGS...] where CMD is a valid command. Current valid commands are: """) + str_valid_cmds print(help_msg) # Provide some useful details for algorithm running. subs_list = ['--' + k.ljust(10) + 'for'.ljust(10) + '--' + v \ for k,v in SUBSTITUTIONS.items()] str_valid_subs = '\n\t' + '\n\t'.join(subs_list) special_info = dedent(""" FYI: When running an algorithm, any keyword argument to the algorithm function can be used as a flag, eg \tpython -m spinup.run ppo --env HalfCheetah-v2 --clip_ratio 0.1 If you need a quick refresher on valid kwargs, get the docstring with \tpython -m spinup.run [algo] --help See the "Running Experiments" docs page for more details. Also: Some common but long flags can be substituted for shorter ones. Valid substitutions are: """) + str_valid_subs print(special_info) elif cmd in valid_utils: # Execute the correct utility file. runfile = osp.join(osp.abspath(osp.dirname(__file__)), 'utils', cmd +'.py') args = [sys.executable if sys.executable else 'python', runfile] + sys.argv[2:] subprocess.check_call(args, env=os.environ) else: # Assume that the user plans to execute an algorithm. Run custom # parsing on the arguments and build a grid search to execute. args = sys.argv[2:] parse_and_execute_grid_search(cmd, args)
[]
[]
[]
[]
[]
python
0
0
dynaconf/vendor/click/_unicodefun.py
import codecs,os def _verify_python_env(): M='.utf8';L='.utf-8';J=None;I='ascii' try:import locale as A;G=codecs.lookup(A.getpreferredencoding()).name except Exception:G=I if G!=I:return B='' if os.name=='posix': import subprocess as D try:C=D.Popen(['locale','-a'],stdout=D.PIPE,stderr=D.PIPE).communicate()[0] except OSError:C=b'' E=set();H=False if isinstance(C,bytes):C=C.decode(I,'replace') for K in C.splitlines(): A=K.strip() if A.lower().endswith((L,M)): E.add(A) if A.lower()in('c.utf8','c.utf-8'):H=True B+='\n\n' if not E:B+='Additional information: on this system no suitable UTF-8 locales were discovered. This most likely requires resolving by reconfiguring the locale system.' elif H:B+='This system supports the C.UTF-8 locale which is recommended. You might be able to resolve your issue by exporting the following environment variables:\n\n export LC_ALL=C.UTF-8\n export LANG=C.UTF-8' else:B+=f"This system lists some UTF-8 supporting locales that you can pick from. The following suitable locales were discovered: {', '.join(sorted(E))}" F=J for A in (os.environ.get('LC_ALL'),os.environ.get('LANG')): if A and A.lower().endswith((L,M)):F=A if A is not J:break if F is not J:B+=f"\n\nClick discovered that you exported a UTF-8 locale but the locale system could not pick up from it because it does not exist. The exported locale is {F!r} but it is not supported" raise RuntimeError(f"Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps.{B}")
[]
[]
[ "LC_ALL", "LANG" ]
[]
["LC_ALL", "LANG"]
python
2
0
beekeeper/settings.py
""" Django settings for beekeeper project on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['DJ_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DJ_DEBUG',False) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'beekeeper' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'beekeeper.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'beekeeper.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'US/Eastern' USE_I18N = True USE_L10N = True USE_TZ = True # Change 'default' database configuration with $DATABASE_URL. DATABASES['default'].update(dj_database_url.config(conn_max_age=500)) # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
[]
[]
[ "DJ_SECRET_KEY", "DJ_DEBUG" ]
[]
["DJ_SECRET_KEY", "DJ_DEBUG"]
python
2
0
airflow/providers/amazon/aws/example_dags/example_s3_bucket.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os from datetime import datetime from airflow.decorators import task from airflow.models.dag import DAG from airflow.providers.amazon.aws.hooks.s3 import S3Hook from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator BUCKET_NAME = os.environ.get('BUCKET_NAME', 'test-airflow-12345') @task(task_id="s3_bucket_dag_add_keys_to_bucket") def upload_keys(): """This is a python callback to add keys into the s3 bucket""" # add keys to bucket s3_hook = S3Hook() for i in range(0, 3): s3_hook.load_string( string_data="input", key=f"path/data{i}", bucket_name=BUCKET_NAME, ) # [START howto_operator_s3_bucket] with DAG( dag_id='s3_bucket_dag', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, default_args={"bucket_name": BUCKET_NAME}, max_active_runs=1, tags=['example'], ) as dag: create_bucket = S3CreateBucketOperator(task_id='s3_bucket_dag_create', region_name='us-east-1') # Using a task-decorated function to add keys add_keys_to_bucket = upload_keys() delete_bucket = S3DeleteBucketOperator(task_id='s3_bucket_dag_delete', force_delete=True) create_bucket >> add_keys_to_bucket >> delete_bucket # [END howto_operator_s3_bucket]
[]
[]
[ "BUCKET_NAME" ]
[]
["BUCKET_NAME"]
python
1
0
autoninja.py
#!/usr/bin/env vpython # Copyright (c) 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This script (intended to be invoked by autoninja or autoninja.bat) detects whether a build is accelerated using a service like goma. If so, it runs with a large -j value, and otherwise it chooses a small one. This auto-adjustment makes using remote build acceleration simpler and safer, and avoids errors that can cause slow goma builds or swap-storms on unaccelerated builds. """ # [VPYTHON:BEGIN] # wheel: < # name: "infra/python/wheels/psutil/${vpython_platform}" # version: "version:5.6.2" # > # [VPYTHON:END] from __future__ import print_function import os import psutil import re import sys SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) # The -t tools are incompatible with -j t_specified = False j_specified = False offline = False output_dir = '.' input_args = sys.argv # On Windows the autoninja.bat script passes along the arguments enclosed in # double quotes. This prevents multiple levels of parsing of the special '^' # characters needed when compiling a single file but means that this script gets # called with a single argument containing all of the actual arguments, # separated by spaces. When this case is detected we need to do argument # splitting ourselves. This means that arguments containing actual spaces are # not supported by autoninja, but that is not a real limitation. if (sys.platform.startswith('win') and len(sys.argv) == 2 and input_args[1].count(' ') > 0): input_args = sys.argv[:1] + sys.argv[1].split() # Ninja uses getopt_long, which allow to intermix non-option arguments. # To leave non supported parameters untouched, we do not use getopt. for index, arg in enumerate(input_args[1:]): if arg.startswith('-j'): j_specified = True if arg.startswith('-t'): t_specified = True if arg == '-C': # + 1 to get the next argument and +1 because we trimmed off input_args[0] output_dir = input_args[index + 2] elif arg.startswith('-C'): # Support -Cout/Default output_dir = arg[2:] elif arg == '-o' or arg == '--offline': offline = True elif arg == '-h': print('autoninja: Use -o/--offline to temporary disable goma.', file=sys.stderr) print(file=sys.stderr) # Strip -o/--offline so ninja doesn't see them. input_args = [ arg for arg in input_args if arg != '-o' and arg != '--offline'] use_goma = False use_rbe = False # Currently get reclient binary and config dirs relative to output_dir. If # they exist and using rbe, then automatically call bootstrap to start # reproxy. This works under the current assumption that the output # directory is two levels up from chromium/src. reclient_bin_dir = os.path.join(output_dir, "../../buildtools/reclient") reclient_cfg = os.path.join( output_dir, "../../buildtools/reclient_cfgs/reproxy.cfg") # Attempt to auto-detect remote build acceleration. We support gn-based # builds, where we look for args.gn in the build tree, and cmake-based builds # where we look for rules.ninja. if os.path.exists(os.path.join(output_dir, 'args.gn')): with open(os.path.join(output_dir, 'args.gn')) as file_handle: for line in file_handle: # Either use_goma or use_rbe activate build acceleration. # # This test can match multi-argument lines. Examples of this are: # is_debug=false use_goma=true is_official_build=false # use_goma=false# use_goma=true This comment is ignored # # Anything after a comment is not consider a valid argument. line_without_comment = line.split('#')[0] if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)', line_without_comment): use_goma = True continue if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)', line_without_comment): use_rbe = True continue else: for relative_path in [ '', # GN keeps them in the root of output_dir 'CMakeFiles' ]: path = os.path.join(output_dir, relative_path, 'rules.ninja') if os.path.exists(path): with open(path) as file_handle: for line in file_handle: if re.match(r'^\s*command\s*=\s*\S+gomacc', line): use_goma = True break # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1" (case-insensitive) # then gomacc will use the local compiler instead of doing a goma compile. This # is convenient if you want to briefly disable goma. It avoids having to rebuild # the world when transitioning between goma/non-goma builds. However, it is not # as fast as doing a "normal" non-goma build because an extra process is created # for each compile step. Checking this environment variable ensures that # autoninja uses an appropriate -j value in this situation. goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower() if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']: use_goma = False # Specify ninja.exe on Windows so that ninja.bat can call autoninja and not # be called back. ninja_exe = 'ninja.exe' if sys.platform.startswith('win') else 'ninja' ninja_exe_path = os.path.join(SCRIPT_DIR, ninja_exe) # A large build (with or without goma) tends to hog all system resources. # Launching the ninja process with 'nice' priorities improves this situation. prefix_args = [] if (sys.platform.startswith('linux') and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'): # nice -10 is process priority 10 lower than default 0 # ionice -c 3 is IO priority IDLE prefix_args = ['nice'] + ['-10'] # Use absolute path for ninja path, # or fail to execute ninja if depot_tools is not in PATH. args = prefix_args + [ninja_exe_path] + input_args[1:] num_cores = psutil.cpu_count() if not j_specified and not t_specified: if use_goma or use_rbe: args.append('-j') core_multiplier = int(os.environ.get('NINJA_CORE_MULTIPLIER', '40')) j_value = num_cores * core_multiplier if sys.platform.startswith('win'): # On windows, j value higher than 1000 does not improve build performance. j_value = min(j_value, 1000) elif sys.platform == 'darwin': # On Mac, j value higher than 500 causes 'Too many open files' error # (crbug.com/936864). j_value = min(j_value, 500) args.append('%d' % j_value) else: j_value = num_cores # Ninja defaults to |num_cores + 2| j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2')) args.append('-j') args.append('%d' % j_value) # On Windows, fully quote the path so that the command processor doesn't think # the whole output is the command. # On Linux and Mac, if people put depot_tools in directories with ' ', # shell would misunderstand ' ' as a path separation. # TODO(yyanagisawa): provide proper quoting for Windows. # see https://cs.chromium.org/chromium/src/tools/mb/mb.py for i in range(len(args)): if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]: args[i] = '"%s"' % args[i].replace('"', '\\"') if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1': args += ['-d', 'stats'] # If using rbe and the necessary environment variables are set, also start # reproxy (via bootstrap) before running ninja. if (not offline and use_rbe and os.path.exists(reclient_bin_dir) and os.path.exists(reclient_cfg)): setup_args = [ 'RBE_cfg=' + reclient_cfg, reclient_bin_dir + '/bootstrap', '--re_proxy=' + reclient_bin_dir + '/reproxy'] teardown_args = [reclient_bin_dir + '/bootstrap', '--shutdown'] args = setup_args + ['&&'] + args + ['&&'] + teardown_args if offline and not sys.platform.startswith('win'): # Tell goma or reclient to do local compiles. On Windows these environment # variables are set by the wrapper batch file. print('RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)) else: print(' '.join(args))
[]
[]
[ "NINJA_CORE_MULTIPLIER", "NINJA_SUMMARIZE_BUILD", "NINJA_CORE_ADDITION", "NINJA_BUILD_IN_BACKGROUND", "GOMA_DISABLED" ]
[]
["NINJA_CORE_MULTIPLIER", "NINJA_SUMMARIZE_BUILD", "NINJA_CORE_ADDITION", "NINJA_BUILD_IN_BACKGROUND", "GOMA_DISABLED"]
python
5
0
config/config.go
package config import ( "os" "strconv" ) type Config struct { DataPath string HttpPort int } var _singleConfig Config func Get() Config { return _singleConfig } func InitConfig() { _singleConfig = Config{DataPath: "/tmp", HttpPort: 8087} tmp := os.Getenv("TOTPD_DATA_PATH") if len(tmp) > 0 { _singleConfig.DataPath = tmp } tmp = os.Getenv("TOTPD_HTTP_PORT") if len(tmp) > 0 { var err error _singleConfig.HttpPort, err = strconv.Atoi(tmp) if err != nil { panic(err) } } }
[ "\"TOTPD_DATA_PATH\"", "\"TOTPD_HTTP_PORT\"" ]
[]
[ "TOTPD_HTTP_PORT", "TOTPD_DATA_PATH" ]
[]
["TOTPD_HTTP_PORT", "TOTPD_DATA_PATH"]
go
2
0
python/inserting_into_sorted_dll.py
#!/bin/python3 # https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/ # import os class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = DoublyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node node.prev = self.tail self.tail = node def print_doubly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) def sortedInsert(head, data): # Write your code here new_node = DoublyLinkedListNode(node_data=data) if not head: return new_node elif data <= head.data: new_node.next = head head.prev = new_node return new_node else: next_node = sortedInsert(head=head.next, data=data) head.next = next_node next_node.prev = head return head if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): llist_count = int(input()) llist = DoublyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) data = int(input()) llist1 = sortedInsert(llist.head, data) print_doubly_linked_list(llist1, ' ', fptr) fptr.write('\n') fptr.close()
[]
[]
[ "OUTPUT_PATH" ]
[]
["OUTPUT_PATH"]
python
1
0
pytest_django/fixtures.py
"""All pytest-django fixtures""" from __future__ import with_statement import copy import os import pytest from . import live_server_helper from .db_reuse import monkey_patch_creation_for_db_reuse from .django_compat import is_django_unittest from .lazy_django import skip_if_no_django __all__ = ['_django_db_setup', 'db', 'transactional_db', 'client', 'admin_client', 'rf', 'settings', 'live_server', '_live_server_helper'] ################ Internal Fixtures ################ @pytest.fixture(scope='session') def _django_db_setup(request, _django_runner, _django_cursor_wrapper): """Session-wide database setup, internal to pytest-django""" skip_if_no_django() from django.core import management # Disable south's syncdb command commands = management.get_commands() if commands['syncdb'] == 'south': management._commands['syncdb'] = 'django.core' with _django_cursor_wrapper: # Monkey patch Django's setup code to support database re-use if request.config.getvalue('reuse_db'): if not request.config.getvalue('create_db'): monkey_patch_creation_for_db_reuse() _django_runner.teardown_databases = lambda db_cfg: None # Create the database db_cfg = _django_runner.setup_databases() def teardown_database(): with _django_cursor_wrapper: _django_runner.teardown_databases(db_cfg) request.addfinalizer(teardown_database) ################ User visible fixtures ################ @pytest.fixture(scope='function') def db(request, _django_db_setup, _django_cursor_wrapper): """Require a django test database This database will be setup with the default fixtures and will have the transaction management disabled. At the end of the test the transaction will be rolled back to undo any changes to the database. This is more limited then the ``transaction_db`` resource but faster. If both this and ``transaction_db`` are requested then the database setup will behave as only ``transaction_db`` was requested. """ if ('transactional_db' not in request.funcargnames and 'live_server' not in request.funcargnames and not is_django_unittest(request.node)): from django.test import TestCase _django_cursor_wrapper.enable() case = TestCase(methodName='__init__') case._pre_setup() request.addfinalizer(case._post_teardown) request.addfinalizer(_django_cursor_wrapper.disable) @pytest.fixture(scope='function') def transactional_db(request, _django_db_setup, _django_cursor_wrapper): """Require a django test database with transaction support This will re-initialise the django database for each test and is thus slower then the normal ``db`` fixture. If you want to use the database with transactions you must request this resource. If both this and ``db`` are requested then the database setup will behave as only ``transaction_db`` was requested. """ if not is_django_unittest(request.node): _django_cursor_wrapper.enable() def flushdb(): """Flush the database and close database connections""" # Django does this by default *before* each test # instead of after. from django.db import connections from django.core.management import call_command for db in connections: call_command('flush', verbosity=0, interactive=False, database=db) for conn in connections.all(): conn.close() request.addfinalizer(_django_cursor_wrapper.disable) request.addfinalizer(flushdb) @pytest.fixture() def client(): """A Django test client instance""" skip_if_no_django() from django.test.client import Client return Client() @pytest.fixture() def admin_client(db): """A Django test client logged in as an admin user""" from django.contrib.auth.models import User from django.test.client import Client try: User.objects.get(username='admin') except User.DoesNotExist: user = User.objects.create_user('admin', '[email protected]', 'password') user.is_staff = True user.is_superuser = True user.save() client = Client() client.login(username='admin', password='password') return client @pytest.fixture() def rf(): """RequestFactory instance""" skip_if_no_django() from django.test.client import RequestFactory return RequestFactory() @pytest.fixture() def settings(request): """A Django settings object which restores changes after the testrun""" # XXX Consider automatically resetting the settings for each test. skip_if_no_django() import django.conf orig_wrapped = django.conf.settings._wrapped django.conf.settings._wrapped = copy.deepcopy(orig_wrapped) def restore_settings(): django.conf.settings._wrapped = orig_wrapped request.addfinalizer(restore_settings) return django.conf.settings @pytest.fixture(scope='session') def live_server(request): """Run a live Django server in the background during tests The address the server is started from is taken from the --liveserver command line option or if this is not provided from the DJANGO_LIVE_TEST_SERVER_ADDRESS environment variable. If neither is provided ``localhost:8081,8100-8200`` is used. See the Django documentation for it's full syntax. NOTE: If the live server needs database access to handle a request your test will have to request database access. Furthermore when the tests want to see data added by the live-server (or the other way around) transactional database access will be needed as data inside a transaction is not shared between the live server and test code. """ skip_if_no_django() addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = live_server_helper.LiveServer(addr) request.addfinalizer(server.stop) return server @pytest.fixture(autouse=True, scope='function') def _live_server_helper(request): """Helper to make live_server work, internal to pytest-django This helper will dynamically request the transactional_db fixture for a tests which uses the live_server fixture. This allows the server and test to access the database whithout having to mark this explicitly which is handy since it is usually required and matches the Django behaviour. The separate helper is required since live_server can not request transactional_db directly since it is session scoped instead of function-scoped. """ if 'live_server' in request.funcargnames: request.getfuncargvalue('transactional_db')
[]
[]
[ "DJANGO_TEST_LIVE_SERVER_ADDRESS" ]
[]
["DJANGO_TEST_LIVE_SERVER_ADDRESS"]
python
1
0
students/K33401/Goncharov_Vladimir/Lr3/hotel/hotel/asgi.py
""" ASGI config for hotel project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hotel.settings') application = get_asgi_application()
[]
[]
[]
[]
[]
python
0
0
manimlib/constants.py
import numpy as np import os # Initialize directories env_MEDIA_DIR = os.getenv("MEDIA_DIR") if env_MEDIA_DIR: MEDIA_DIR = env_MEDIA_DIR elif os.path.isfile("media_dir.txt"): with open("media_dir.txt", 'rU') as media_file: MEDIA_DIR = media_file.readline().strip() else: MEDIA_DIR = os.path.join( os.path.expanduser('~'), "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder" ) if not os.path.isdir(MEDIA_DIR): MEDIA_DIR = "media" # print( # f"Media will be stored in {MEDIA_DIR + os.sep}. You can change " # "this behavior by writing a different directory to media_dir.txt." # ) VIDEO_DIR = os.path.join(MEDIA_DIR, "videos") RASTER_IMAGE_DIR = os.path.join(MEDIA_DIR, "designs", "raster_images") SVG_IMAGE_DIR = os.path.join(MEDIA_DIR, "designs", "svg_images") SOUND_DIR = os.path.join(MEDIA_DIR, "designs", "sounds") ### THIS_DIR = os.path.dirname(os.path.realpath(__file__)) FILE_DIR = os.path.join(os.getenv("FILE_DIR", default=THIS_DIR), "files") TEX_DIR = os.path.join(FILE_DIR, "Tex") # These two may be depricated now. MOBJECT_DIR = os.path.join(FILE_DIR, "mobjects") IMAGE_MOBJECT_DIR = os.path.join(MOBJECT_DIR, "image") for folder in [FILE_DIR, RASTER_IMAGE_DIR, SVG_IMAGE_DIR, VIDEO_DIR, TEX_DIR, MOBJECT_DIR, IMAGE_MOBJECT_DIR]: if not os.path.exists(folder): os.makedirs(folder) TEX_USE_CTEX = False TEX_TEXT_TO_REPLACE = "YourTextHere" TEMPLATE_TEX_FILE = os.path.join( THIS_DIR, "tex_template.tex" if not TEX_USE_CTEX else "ctex_template.tex" ) with open(TEMPLATE_TEX_FILE, "r") as infile: TEMPLATE_TEXT_FILE_BODY = infile.read() TEMPLATE_TEX_FILE_BODY = TEMPLATE_TEXT_FILE_BODY.replace( TEX_TEXT_TO_REPLACE, "\\begin{align*}\n" + TEX_TEXT_TO_REPLACE + "\n\\end{align*}", ) HELP_MESSAGE = """ Usage: python extract_scene.py <module> [<scene name>] -p preview in low quality -s show and save picture of last frame -w write result to file [this is default if nothing else is stated] -o <file_name> write to a different file_name -l use low quality -m use medium quality -a run and save every scene in the script, or all args for the given scene -q don't print progress -f when writing to a movie file, export the frames in png sequence -t use transperency when exporting images -n specify the number of the animation to start from -r specify a resolution -c specify a background color """ SCENE_NOT_FOUND_MESSAGE = """ {} is not in the script """ CHOOSE_NUMBER_MESSAGE = """ Choose number corresponding to desired scene/arguments. (Use comma separated list for multiple entries) Choice(s): """ INVALID_NUMBER_MESSAGE = "Fine then, if you don't want to give a valid number I'll just quit" NO_SCENE_MESSAGE = """ There are no scenes inside that module """ # There might be other configuration than pixel shape later... PRODUCTION_QUALITY_CAMERA_CONFIG = { "pixel_height": 1440, "pixel_width": 2560, "frame_rate": 60, } HIGH_QUALITY_CAMERA_CONFIG = { "pixel_height": 1080, "pixel_width": 1920, "frame_rate": 30, } MEDIUM_QUALITY_CAMERA_CONFIG = { "pixel_height": 720, "pixel_width": 1280, "frame_rate": 30, } LOW_QUALITY_CAMERA_CONFIG = { "pixel_height": 480, "pixel_width": 854, "frame_rate": 15, } DEFAULT_PIXEL_HEIGHT = PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_height"] DEFAULT_PIXEL_WIDTH = PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_width"] DEFAULT_FRAME_RATE = 60 DEFAULT_POINT_DENSITY_2D = 25 DEFAULT_POINT_DENSITY_1D = 250 DEFAULT_STROKE_WIDTH = 4 FRAME_HEIGHT = 8.0 FRAME_WIDTH = FRAME_HEIGHT * DEFAULT_PIXEL_WIDTH / DEFAULT_PIXEL_HEIGHT FRAME_Y_RADIUS = FRAME_HEIGHT / 2 FRAME_X_RADIUS = FRAME_WIDTH / 2 SMALL_BUFF = 0.1 MED_SMALL_BUFF = 0.25 MED_LARGE_BUFF = 0.5 LARGE_BUFF = 1 DEFAULT_MOBJECT_TO_EDGE_BUFFER = MED_LARGE_BUFF DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = MED_SMALL_BUFF # All in seconds DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0 DEFAULT_WAIT_TIME = 1.0 ORIGIN = np.array((0., 0., 0.)) UP = np.array((0., 1., 0.)) DOWN = np.array((0., -1., 0.)) RIGHT = np.array((1., 0., 0.)) LEFT = np.array((-1., 0., 0.)) IN = np.array((0., 0., -1.)) OUT = np.array((0., 0., 1.)) X_AXIS = np.array((1., 0., 0.)) Y_AXIS = np.array((0., 1., 0.)) Z_AXIS = np.array((0., 0., 1.)) # Useful abbreviations for diagonals UL = UP + LEFT UR = UP + RIGHT DL = DOWN + LEFT DR = DOWN + RIGHT TOP = FRAME_Y_RADIUS * UP BOTTOM = FRAME_Y_RADIUS * DOWN LEFT_SIDE = FRAME_X_RADIUS * LEFT RIGHT_SIDE = FRAME_X_RADIUS * RIGHT PI = np.pi TAU = 2 * PI DEGREES = TAU / 360 FFMPEG_BIN = "ffmpeg" # Colors COLOR_MAP = { "DARK_BLUE": "#236B8E", "DARK_BROWN": "#8B4513", "LIGHT_BROWN": "#CD853F", "BLUE_E": "#1C758A", "BLUE_D": "#29ABCA", "BLUE_C": "#58C4DD", "BLUE_B": "#9CDCEB", "BLUE_A": "#C7E9F1", "TEAL_E": "#49A88F", "TEAL_D": "#55C1A7", "TEAL_C": "#5CD0B3", "TEAL_B": "#76DDC0", "TEAL_A": "#ACEAD7", "GREEN_E": "#699C52", "GREEN_D": "#77B05D", "GREEN_C": "#83C167", "GREEN_B": "#A6CF8C", "GREEN_A": "#C9E2AE", "YELLOW_E": "#E8C11C", "YELLOW_D": "#F4D345", "YELLOW_C": "#FFFF00", "YELLOW_B": "#FFEA94", "YELLOW_A": "#FFF1B6", "GOLD_E": "#C78D46", "GOLD_D": "#E1A158", "GOLD_C": "#F0AC5F", "GOLD_B": "#F9B775", "GOLD_A": "#F7C797", "RED_E": "#CF5044", "RED_D": "#E65A4C", "RED_C": "#FC6255", "RED_B": "#FF8080", "RED_A": "#F7A1A3", "MAROON_E": "#94424F", "MAROON_D": "#A24D61", "MAROON_C": "#C55F73", "MAROON_B": "#EC92AB", "MAROON_A": "#ECABC1", "PURPLE_E": "#644172", "PURPLE_D": "#715582", "PURPLE_C": "#9A72AC", "PURPLE_B": "#B189C6", "PURPLE_A": "#CAA3E8", "WHITE": "#FFFFFF", "BLACK": "#000000", "LIGHT_GRAY": "#BBBBBB", "LIGHT_GREY": "#BBBBBB", "GRAY": "#888888", "GREY": "#888888", "DARK_GREY": "#444444", "DARK_GRAY": "#444444", "GREY_BROWN": "#736357", "PINK": "#D147BD", "GREEN_SCREEN": "#00FF00", "ORANGE": "#FF862F", } PALETTE = list(COLOR_MAP.values()) locals().update(COLOR_MAP) for name in [s for s in list(COLOR_MAP.keys()) if s.endswith("_C")]: locals()[name.replace("_C", "")] = locals()[name] # Streaming related configuration LIVE_STREAM_NAME = "LiveStream" TWITCH_STREAM_KEY = "YOUR_STREAM_KEY" STREAMING_PROTOCOL = "tcp" STREAMING_IP = "127.0.0.1" STREAMING_PORT = "2000" STREAMING_CLIENT = "ffplay" STREAMING_URL = f"{STREAMING_PROTOCOL}://{STREAMING_IP}:{STREAMING_PORT}?listen" STREAMING_CONSOLE_BANNER = """ Manim is now running in streaming mode. Stream animations by passing them to manim.play(), e.g. >>> c = Circle() >>> manim.play(ShowCreation(c)) """
[]
[]
[ "FILE_DIR", "MEDIA_DIR" ]
[]
["FILE_DIR", "MEDIA_DIR"]
python
2
0
cmd/peer-list/main.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // A small utility program to lookup hostnames of endpoints in a service. package main import ( "flag" "fmt" "io/ioutil" "log" "net" "os" "os/exec" "os/signal" "regexp" "sort" "strings" "syscall" "time" "k8s.io/apimachinery/pkg/util/sets" ) const ( pollPeriod = 1 * time.Second ) var ( onChange = flag.String("on-change", "", "Script to run on change, must accept a new line separated list of peers via stdin.") onStart = flag.String("on-start", "", "Script to run on start, must accept a new line separated list of peers via stdin.") svc = flag.String("service", "", "Governing service responsible for the DNS records of the domain this pod is in.") namespace = flag.String("ns", "", "The namespace this pod is running in. If unspecified, the POD_NAMESPACE env var is used.") domain = flag.String("domain", "", "The Cluster Domain which is used by the Cluster, if not set tries to determine it from /etc/resolv.conf file.") ) func lookup(svcName string) (sets.String, error) { endpoints := sets.NewString() _, srvRecords, err := net.LookupSRV("", "", svcName) if err != nil { return endpoints, err } for _, srvRecord := range srvRecords { // The SRV records ends in a "." for the root domain ep := fmt.Sprintf("%v", srvRecord.Target[:len(srvRecord.Target)-1]) endpoints.Insert(ep) } return endpoints, nil } func shellOut(sendStdin, script string) { log.Printf("execing: %v with stdin: %v", script, sendStdin) // TODO: Switch to sending stdin from go out, err := exec.Command("bash", "-c", fmt.Sprintf("echo -e '%v' | %v", sendStdin, script)).CombinedOutput() if err != nil { log.Fatalf("Failed to execute %v: %v, err: %v", script, string(out), err) } log.Print(string(out)) } func main() { // Custom signal handler for SIGUSR1. This is needed because the // Docker image (percona/percona-xtradb-cluster-operator:$version-haproxy) // sets the STOPSIGNAL to SIGUSR1 to shutdown HAProxy gracefully. signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGUSR1) go func() { <-signalChan os.Exit(0) }() flag.Parse() ns := *namespace if ns == "" { ns = os.Getenv("POD_NAMESPACE") } log.Printf("Peer finder enter") var domainName string // If domain is not provided, try to get it from resolv.conf if *domain == "" { resolvConfBytes, err := ioutil.ReadFile("/etc/resolv.conf") resolvConf := string(resolvConfBytes) if err != nil { log.Fatal("Unable to read /etc/resolv.conf") } var re *regexp.Regexp if ns == "" { // Looking for a domain that looks like with *.svc.** re, err = regexp.Compile(`\A(.*\n)*search\s{1,}(.*\s{1,})*(?P<goal>[a-zA-Z0-9-]{1,63}.svc.([a-zA-Z0-9-]{1,63}\.)*[a-zA-Z0-9]{2,63})`) } else { // Looking for a domain that looks like svc.** re, err = regexp.Compile(`\A(.*\n)*search\s{1,}(.*\s{1,})*(?P<goal>svc.([a-zA-Z0-9-]{1,63}\.)*[a-zA-Z0-9]{2,63})`) } if err != nil { log.Fatalf("Failed to create regular expression: %v", err) } groupNames := re.SubexpNames() result := re.FindStringSubmatch(resolvConf) for k, v := range result { if groupNames[k] == "goal" { if ns == "" { // Domain is complete if ns is empty domainName = v } else { // Need to convert svc.** into ns.svc.** domainName = ns + "." + v } break } } log.Printf("Determined Domain to be %s", domainName) } else { domainName = strings.Join([]string{ns, "svc", *domain}, ".") } if *svc == "" || domainName == "" || (*onChange == "" && *onStart == "") { log.Fatalf("Incomplete args, require -on-change and/or -on-start, -service and -ns or an env var for POD_NAMESPACE.") } script := *onStart if script == "" { script = *onChange log.Printf("No on-start supplied, on-change %v will be applied on start.", script) } newPeers := sets.NewString() var err error for peers := sets.NewString(); script != ""; time.Sleep(pollPeriod) { newPeers, err = lookup(*svc) if err != nil { log.Printf("%v", err) if lerr, ok := err.(*net.DNSError); ok && lerr.IsNotFound { // Service not resolved - no endpoints, so reset peers list peers = sets.NewString() continue } } peerList := newPeers.List() sort.Strings(peerList) if strings.Join(peers.List(), ":") != strings.Join(newPeers.List(), ":") { log.Printf("Peer list updated\nwas %v\nnow %v", peers.List(), newPeers.List()) shellOut(strings.Join(peerList, "\n"), script) peers = newPeers } script = *onChange } // TODO: Exit if there's no on-change? log.Printf("Peer finder exiting") }
[ "\"POD_NAMESPACE\"" ]
[]
[ "POD_NAMESPACE" ]
[]
["POD_NAMESPACE"]
go
1
0
app/job/main/videoup-report/dao/email/dao_test.go
package email import ( "flag" "go-common/app/job/main/videoup-report/conf" "os" "testing" ) var ( d *Dao ) func TestMain(m *testing.M) { if os.Getenv("DEPLOY_ENV") != "" { flag.Set("app_id", "videoup-report") flag.Set("conf_token", "") flag.Set("tree_id", "") flag.Set("conf_version", "server-1") flag.Set("deploy_env", "uat") flag.Set("conf_host", "config.bilibili.co") flag.Set("conf_path", "/tmp") flag.Set("region", "sh") flag.Set("zone", "sh001") } else { flag.Set("conf", "../../cmd/videoup-report-job.toml") } flag.Parse() if err := conf.Init(); err != nil { panic(err) } d = New(conf.Conf) m.Run() os.Exit(0) }
[ "\"DEPLOY_ENV\"" ]
[]
[ "DEPLOY_ENV" ]
[]
["DEPLOY_ENV"]
go
1
0